lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | b8bfee913af4f404560ebf8306c3a722d7f1cfeb | 0 | oneilcin/monasca-events-api,openstack/monasca-api,hpcloud-mon/monasca-events-api,stackforge/monasca-api,stackforge/monasca-api,openstack/monasca-api,hpcloud-mon/monasca-events-api,hpcloud-mon/monasca-events-api,stackforge/monasca-api,sapcc/monasca-api,oneilcin/monasca-events-api,stackforge/monasca-api,openstack/monasca-api,oneilcin/monasca-events-api,sapcc/monasca-api,sapcc/monasca-api,oneilcin/monasca-events-api,hpcloud-mon/monasca-events-api | /*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.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
*
* 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 monasca.api.infrastructure.persistence.influxdb;
import com.google.inject.Inject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URLEncoder;
import monasca.api.ApiConfig;
public class InfluxV9RepoReader {
private static final Logger logger = LoggerFactory.getLogger(InfluxV9RepoReader.class);
private final ApiConfig config;
private final String influxName;
private final String influxUrl;
private final String influxCreds;
private final String influxUser;
private final String influxPass;
private final String baseAuthHeader;
private final CloseableHttpClient httpClient;
@Inject
public InfluxV9RepoReader(final ApiConfig config) {
this.config = config;
this.influxName = config.influxDB.getName();
this.influxUrl = config.influxDB.getUrl() + "/query";
this.influxUser = config.influxDB.getUser();
this.influxPass = config.influxDB.getPassword();
this.influxCreds = this.influxUser + ":" + this.influxPass;
this.baseAuthHeader = "Basic " + new String(Base64.encodeBase64(this.influxCreds.getBytes()));
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(config.influxDB.getMaxHttpConnections());
// We inject InfluxV9RepoReader as a singleton. So, we must share connections safely.
this.httpClient =
HttpClients.custom().setConnectionManager(cm)
.addInterceptorFirst(new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
}).addInterceptorFirst(new HttpResponseInterceptor() {
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
}
}).build();
}
protected String read(final String query) throws Exception {
HttpGet request = new HttpGet(this.influxUrl + "?q=" + URLEncoder.encode(query, "UTF-8")
+ "&db=" + URLEncoder.encode(this.influxName, "UTF-8"));
request.addHeader("content-type", "application/json");
request.addHeader("Authorization", this.baseAuthHeader);
try {
logger.debug("Sending query {} to influx database {} at {}", query, this.influxName,
this.influxUrl);
HttpResponse response = this.httpClient.execute(request);
int rc = response.getStatusLine().getStatusCode();
logger.debug("Received {} status code from influx database", rc);
if (rc != HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
logger.error("Failed to query influx database {} at {}: {}",
this.influxName, this.influxUrl, String.valueOf(rc));
logger.error("Http response: {}", responseString);
throw new Exception(rc + ":" + responseString);
}
logger.debug("Successfully queried influx database {} at {}",
this.influxName, this.influxUrl);
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} finally {
request.releaseConnection();
}
}
}
| java/src/main/java/monasca/api/infrastructure/persistence/influxdb/InfluxV9RepoReader.java | /*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.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
*
* 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 monasca.api.infrastructure.persistence.influxdb;
import com.google.inject.Inject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLEncoder;
import monasca.api.ApiConfig;
public class InfluxV9RepoReader {
private static final Logger logger = LoggerFactory.getLogger(InfluxV9RepoReader.class);
private final ApiConfig config;
private final String influxName;
private final String influxUrl;
private final String influxCreds;
private final String influxUser;
private final String influxPass;
private final String baseAuthHeader;
private final CloseableHttpClient httpClient;
@Inject
public InfluxV9RepoReader(final ApiConfig config) {
this.config = config;
this.influxName = config.influxDB.getName();
this.influxUrl = config.influxDB.getUrl() + "/query";
this.influxUser = config.influxDB.getUser();
this.influxPass = config.influxDB.getPassword();
this.influxCreds = this.influxUser + ":" + this.influxPass;
this.baseAuthHeader = "Basic " + new String(Base64.encodeBase64(this.influxCreds.getBytes()));
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(config.influxDB.getMaxHttpConnections());
// We inject InfluxV9RepoReader as a singleton. So, we must share connections safely.
this.httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
protected String read(final String query) throws Exception {
HttpGet request = new HttpGet(this.influxUrl + "?q=" + URLEncoder.encode(query, "UTF-8")
+ "&db=" + URLEncoder.encode(this.influxName, "UTF-8"));
request.addHeader("content-type", "application/json");
request.addHeader("Authorization", this.baseAuthHeader);
try {
logger.debug("Sending query {} to influx database {} at {}", query, this.influxName,
this.influxUrl);
HttpResponse response = this.httpClient.execute(request);
int rc = response.getStatusLine().getStatusCode();
logger.debug("Received {} status code from influx database", rc);
if (rc != HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
logger.error("Failed to query influx database {} at {}: {}",
this.influxName, this.influxUrl, String.valueOf(rc));
logger.error("Http response: {}", responseString);
throw new Exception(rc + ":" + responseString);
}
logger.debug("Successfully queried influx database {} at {}",
this.influxName, this.influxUrl);
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} finally {
request.releaseConnection();
}
}
}
| Accept gzip results from influxdb
Change-Id: I4f986b8247d854774dbeb217cb11e5e253b912ac
| java/src/main/java/monasca/api/infrastructure/persistence/influxdb/InfluxV9RepoReader.java | Accept gzip results from influxdb | <ide><path>ava/src/main/java/monasca/api/infrastructure/persistence/influxdb/InfluxV9RepoReader.java
<ide> import com.google.inject.Inject;
<ide>
<ide> import org.apache.commons.codec.binary.Base64;
<add>import org.apache.http.Header;
<add>import org.apache.http.HeaderElement;
<ide> import org.apache.http.HttpEntity;
<add>import org.apache.http.HttpException;
<add>import org.apache.http.HttpRequest;
<add>import org.apache.http.HttpRequestInterceptor;
<ide> import org.apache.http.HttpResponse;
<add>import org.apache.http.HttpResponseInterceptor;
<ide> import org.apache.http.HttpStatus;
<add>import org.apache.http.client.entity.GzipDecompressingEntity;
<ide> import org.apache.http.client.methods.HttpGet;
<ide> import org.apache.http.impl.client.CloseableHttpClient;
<ide> import org.apache.http.impl.client.HttpClients;
<ide> import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
<add>import org.apache.http.protocol.HttpContext;
<ide> import org.apache.http.util.EntityUtils;
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<add>import java.io.IOException;
<ide> import java.net.URLEncoder;
<ide>
<ide> import monasca.api.ApiConfig;
<ide> cm.setMaxTotal(config.influxDB.getMaxHttpConnections());
<ide>
<ide> // We inject InfluxV9RepoReader as a singleton. So, we must share connections safely.
<del> this.httpClient = HttpClients.custom().setConnectionManager(cm).build();
<add> this.httpClient =
<add> HttpClients.custom().setConnectionManager(cm)
<add> .addInterceptorFirst(new HttpRequestInterceptor() {
<add>
<add> public void process(final HttpRequest request, final HttpContext context)
<add> throws HttpException, IOException {
<add> if (!request.containsHeader("Accept-Encoding")) {
<add> request.addHeader("Accept-Encoding", "gzip");
<add> }
<add> }
<add> }).addInterceptorFirst(new HttpResponseInterceptor() {
<add>
<add> public void process(final HttpResponse response, final HttpContext context)
<add> throws HttpException, IOException {
<add> HttpEntity entity = response.getEntity();
<add> if (entity != null) {
<add> Header ceheader = entity.getContentEncoding();
<add> if (ceheader != null) {
<add> HeaderElement[] codecs = ceheader.getElements();
<add> for (int i = 0; i < codecs.length; i++) {
<add> if (codecs[i].getName().equalsIgnoreCase("gzip")) {
<add> response.setEntity(new GzipDecompressingEntity(response.getEntity()));
<add> return;
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> }).build();
<ide>
<ide> }
<ide> |
|
JavaScript | mit | 4c7cba60dda379c631c72b3de808885e87e9f519 | 0 | kjirou/puyopuyo-console | const EventEmitter = require('events');
const icepick = require('icepick');
const {PARAMETERS, PUYOPUYO_COLOR_TYPES, PUYOPUYO_FIELD_SIZE} = require('./constants');
const DIRECTIONS = {
UP: 'UP',
RIGHT: 'RIGHT',
DOWN: 'DOWN',
LEFT: 'LEFT',
};
const DIRECTIONS_TO_COORDINATE_DELTAS = {
UP: {
rowIndex: -1,
columnIndex: 0,
},
RIGHT: {
rowIndex: 0,
columnIndex: 1,
},
DOWN: {
rowIndex: 1,
columnIndex: 0,
},
LEFT: {
rowIndex: 0,
columnIndex: -1,
},
};
const FALLING_PUYO_FREE_FALL_INTERVAL = 300;
const FALLING_PUYO_ROTATION = ['UP', 'RIGHT', 'DOWN', 'LEFT'];
class Store {
static _generatePuyopuyoFieldSquareMatrix(rowLength, columnLength) {
const matrix = [];
for (let rowIndex = 0; rowIndex < PUYOPUYO_FIELD_SIZE.rowLength; rowIndex += 1) {
const line = [];
matrix.push(line);
for (let columnIndex = 0; columnIndex < PUYOPUYO_FIELD_SIZE.columnLength; columnIndex += 1) {
line.push({
rowIndex,
columnIndex,
colorType: PUYOPUYO_COLOR_TYPES.NONE,
});
}
}
return matrix;
}
static _getSquare(puyopuyoFieldSquareMatrix, rowIndex, columnIndex) {
const line = puyopuyoFieldSquareMatrix[rowIndex];
if (!line) {
return null;
}
return line[columnIndex] || null;
}
static _canPlacePuyo(puyopuyoFieldSquareMatrix, rowIndex, columnIndex) {
const square = Store._getSquare(puyopuyoFieldSquareMatrix, rowIndex, columnIndex);
if (!square) {
return false;
}
return square.colorType === PUYOPUYO_COLOR_TYPES.NONE;
}
static _convertFallingPuyoToSquares(coordinate, colorTypes, direction) {
const baseSquare = Object.assign({}, coordinate, {
colorType: colorTypes[0],
});
const delta = DIRECTIONS_TO_COORDINATE_DELTAS[direction];
const followingSquare = {
rowIndex: coordinate.rowIndex + delta.rowIndex,
columnIndex: coordinate.columnIndex + delta.columnIndex,
colorType: colorTypes[1],
};
return [baseSquare, followingSquare];
}
constructor() {
// It has a "change" event only.
this._emitter = new EventEmitter();
this._state = {
fallingPuyo: {
coordinate: {
rowIndex: 0,
columnIndex: 2,
},
isFalling: true,
lastMovedAt: 0,
colorTypes: ['RED', 'YELLOW'],
direction: DIRECTIONS.UP,
},
puyopuyoFieldSquareMatrix: Store._generatePuyopuyoFieldSquareMatrix(
PUYOPUYO_FIELD_SIZE.rowLength,
PUYOPUYO_FIELD_SIZE.columnLength
),
gameLoopId: 0,
gameTime: 0,
};
this._gameLoopTimerId = null;
// Tmp
//setTimeout(() => {
// this._state.puyopuyoFieldSquareMatrix[0][0].colorType = 'RED';
// this._emitChange();
//}, 1000);
}
get emitter() {
return this._emitter;
}
_emitChange() {
this._emitter.emit('change');
}
getState() {
return this._state;
}
static generateFallingPuyoSquares(state) {
return state.fallingPuyo.isFalling
? Store._convertFallingPuyoToSquares(
state.fallingPuyo.coordinate,
state.fallingPuyo.colorTypes,
state.fallingPuyo.direction
)
: []
;
}
static _nextGameLoopState(state) {
let newState = state;
// Falling Puyo
if (state.fallingPuyo.isFalling) {
// TODO: Apply control
// Apply free fall
if (state.fallingPuyo.lastMovedAt + FALLING_PUYO_FREE_FALL_INTERVAL <= newState.gameTime) {
const nextCoordinate = {
rowIndex: state.fallingPuyo.coordinate.rowIndex + 1,
columnIndex: state.fallingPuyo.coordinate.columnIndex,
};
const fallingPuyoSquares = Store.generateFallingPuyoSquares(newState);
const nextFallingPuyoSquares = fallingPuyoSquares.map(square => {
return Object.assign({}, square, {
rowIndex: square.rowIndex + 1,
});
});
// Touch the ground/other-puyos or not
if (
nextFallingPuyoSquares.some(square => {
return !Store._canPlacePuyo(
newState.puyopuyoFieldSquareMatrix,
square.rowIndex,
square.columnIndex
);
})
) {
fallingPuyoSquares.forEach(square => {
newState = icepick.assocIn(
newState,
['puyopuyoFieldSquareMatrix', square.rowIndex, square.columnIndex, 'colorType'],
square.colorType
);
});
newState = icepick.assocIn(newState, ['fallingPuyo'], {
// TODO: Generalize the shape
coordinate: {
rowIndex: 0,
columnIndex: 2,
},
isFalling: true,
lastMovedAt: 0,
colorTypes: ['RED', 'YELLOW'],
direction: DIRECTIONS.UP,
});
} else {
newState = icepick.assocIn(newState, ['fallingPuyo', 'coordinate'], nextCoordinate);
newState = icepick.assocIn(newState, ['fallingPuyo', 'lastMovedAt'], newState.gameTime);
}
}
} else {
// TODO: Reserve new falling puyo
}
// Game time
newState = icepick.assocIn(newState, ['gameLoopId'], newState.gameLoopId + 1);
newState = icepick.assocIn(newState, ['gameTime'], newState.gameTime + PARAMETERS.GAME_LOOP_INTERVAL);
return newState;
}
startGame() {
const _handleGameLoop = () => {
this._state = Store._nextGameLoopState(this._state);
this._emitChange();
};
this._gameLoopTimerId = setInterval(_handleGameLoop, PARAMETERS.GAME_LOOP_INTERVAL);
}
}
module.exports = Store;
| lib/Store.js | const EventEmitter = require('events');
const icepick = require('icepick');
const {PARAMETERS, PUYOPUYO_COLOR_TYPES, PUYOPUYO_FIELD_SIZE} = require('./constants');
const DIRECTIONS = {
UP: 'UP',
RIGHT: 'RIGHT',
DOWN: 'DOWN',
LEFT: 'LEFT',
};
const DIRECTIONS_TO_COORDINATE_DELTAS = {
UP: {
rowIndex: -1,
columnIndex: 0,
},
RIGHT: {
rowIndex: 0,
columnIndex: 1,
},
DOWN: {
rowIndex: 1,
columnIndex: 0,
},
LEFT: {
rowIndex: 0,
columnIndex: -1,
},
};
const FALLING_PUYO_FREE_FALL_INTERVAL = 500;
const FALLING_PUYO_ROTATION = ['UP', 'RIGHT', 'DOWN', 'LEFT'];
class Store {
static _generatePuyopuyoFieldSquareMatrix(rowLength, columnLength) {
const matrix = [];
for (let rowIndex = 0; rowIndex < PUYOPUYO_FIELD_SIZE.rowLength; rowIndex += 1) {
const line = [];
matrix.push(line);
for (let columnIndex = 0; columnIndex < PUYOPUYO_FIELD_SIZE.columnLength; columnIndex += 1) {
line.push({
rowIndex,
columnIndex,
colorType: PUYOPUYO_COLOR_TYPES.NONE,
});
}
}
return matrix;
}
static _convertFallingPuyoToSquares(coordinate, colorTypes, direction) {
const baseSquare = Object.assign({}, coordinate, {
colorType: colorTypes[0],
});
const delta = DIRECTIONS_TO_COORDINATE_DELTAS[direction];
const followingSquare = {
rowIndex: coordinate.rowIndex + delta.rowIndex,
columnIndex: coordinate.columnIndex + delta.columnIndex,
colorType: colorTypes[1],
};
return [baseSquare, followingSquare];
}
constructor() {
// It has a "change" event only.
this._emitter = new EventEmitter();
this._state = {
fallingPuyo: {
coordinate: {
rowIndex: 0,
columnIndex: 2,
},
isFalling: true,
lastMovedAt: 0,
colorTypes: ['RED', 'YELLOW'],
direction: DIRECTIONS.UP,
},
puyopuyoFieldSquareMatrix: Store._generatePuyopuyoFieldSquareMatrix(
PUYOPUYO_FIELD_SIZE.rowLength,
PUYOPUYO_FIELD_SIZE.columnLength
),
gameLoopId: 0,
gameTime: 0,
};
this._gameLoopTimerId = null;
// Tmp
//setTimeout(() => {
// this._state.puyopuyoFieldSquareMatrix[0][0].colorType = 'RED';
// this._emitChange();
//}, 1000);
}
get emitter() {
return this._emitter;
}
_emitChange() {
this._emitter.emit('change');
}
getState() {
return this._state;
}
static generateFallingPuyoSquares(state) {
return state.fallingPuyo.isFalling
? Store._convertFallingPuyoToSquares(
state.fallingPuyo.coordinate,
state.fallingPuyo.colorTypes,
state.fallingPuyo.direction
)
: []
;
}
static _nextGameLoopState(state) {
let newState = state;
// Falling Puyo
if (state.fallingPuyo.isFalling) {
// TODO: Apply control
// Apply free fall
if (state.fallingPuyo.lastMovedAt + FALLING_PUYO_FREE_FALL_INTERVAL <= newState.gameTime) {
const nextCoordinate = {
rowIndex: state.fallingPuyo.coordinate.rowIndex + 1,
columnIndex: state.fallingPuyo.coordinate.columnIndex,
};
// Touch the ground or not
if (false) {
// TODO:
} else {
newState = icepick.assocIn(newState, ['fallingPuyo', 'coordinate'], nextCoordinate);
newState = icepick.assocIn(newState, ['fallingPuyo', 'lastMovedAt'], newState.gameTime);
}
}
} else {
// TODO: Reserve new falling puyo
}
// Game time
newState = icepick.assocIn(newState, ['gameLoopId'], newState.gameLoopId + 1);
newState = icepick.assocIn(newState, ['gameTime'], newState.gameTime + PARAMETERS.GAME_LOOP_INTERVAL);
return newState;
}
startGame() {
const _handleGameLoop = () => {
this._state = Store._nextGameLoopState(this._state);
this._emitChange();
};
this._gameLoopTimerId = setInterval(_handleGameLoop, PARAMETERS.GAME_LOOP_INTERVAL);
}
}
module.exports = Store;
| Make to stack puyos by free-fall
| lib/Store.js | Make to stack puyos by free-fall | <ide><path>ib/Store.js
<ide> columnIndex: -1,
<ide> },
<ide> };
<del>const FALLING_PUYO_FREE_FALL_INTERVAL = 500;
<add>const FALLING_PUYO_FREE_FALL_INTERVAL = 300;
<ide> const FALLING_PUYO_ROTATION = ['UP', 'RIGHT', 'DOWN', 'LEFT'];
<ide>
<ide> class Store {
<ide> }
<ide>
<ide> return matrix;
<add> }
<add>
<add> static _getSquare(puyopuyoFieldSquareMatrix, rowIndex, columnIndex) {
<add> const line = puyopuyoFieldSquareMatrix[rowIndex];
<add> if (!line) {
<add> return null;
<add> }
<add> return line[columnIndex] || null;
<add> }
<add>
<add> static _canPlacePuyo(puyopuyoFieldSquareMatrix, rowIndex, columnIndex) {
<add> const square = Store._getSquare(puyopuyoFieldSquareMatrix, rowIndex, columnIndex);
<add> if (!square) {
<add> return false;
<add> }
<add> return square.colorType === PUYOPUYO_COLOR_TYPES.NONE;
<ide> }
<ide>
<ide> static _convertFallingPuyoToSquares(coordinate, colorTypes, direction) {
<ide> rowIndex: state.fallingPuyo.coordinate.rowIndex + 1,
<ide> columnIndex: state.fallingPuyo.coordinate.columnIndex,
<ide> };
<del>
<del> // Touch the ground or not
<del> if (false) {
<del> // TODO:
<add> const fallingPuyoSquares = Store.generateFallingPuyoSquares(newState);
<add> const nextFallingPuyoSquares = fallingPuyoSquares.map(square => {
<add> return Object.assign({}, square, {
<add> rowIndex: square.rowIndex + 1,
<add> });
<add> });
<add>
<add> // Touch the ground/other-puyos or not
<add> if (
<add> nextFallingPuyoSquares.some(square => {
<add> return !Store._canPlacePuyo(
<add> newState.puyopuyoFieldSquareMatrix,
<add> square.rowIndex,
<add> square.columnIndex
<add> );
<add> })
<add> ) {
<add> fallingPuyoSquares.forEach(square => {
<add> newState = icepick.assocIn(
<add> newState,
<add> ['puyopuyoFieldSquareMatrix', square.rowIndex, square.columnIndex, 'colorType'],
<add> square.colorType
<add> );
<add> });
<add> newState = icepick.assocIn(newState, ['fallingPuyo'], {
<add> // TODO: Generalize the shape
<add> coordinate: {
<add> rowIndex: 0,
<add> columnIndex: 2,
<add> },
<add> isFalling: true,
<add> lastMovedAt: 0,
<add> colorTypes: ['RED', 'YELLOW'],
<add> direction: DIRECTIONS.UP,
<add> });
<ide> } else {
<ide> newState = icepick.assocIn(newState, ['fallingPuyo', 'coordinate'], nextCoordinate);
<ide> newState = icepick.assocIn(newState, ['fallingPuyo', 'lastMovedAt'], newState.gameTime); |
|
Java | lgpl-2.1 | 733cf124d4efd89920d0fd1e4e114f79fafa12bd | 0 | spotbugs/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,johnscancella/spotbugs,sewe/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,sewe/spotbugs,johnscancella/spotbugs | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2006, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.IllegalFormatException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.io.IO;
/**
* @author pugh
*/
public class SystemProperties {
private static Properties properties = new Properties();
public final static boolean ASSERTIONS_ENABLED;
public static boolean RUNNING_IN_ECLIPSE = SystemProperties.class.getClassLoader().getClass().getCanonicalName()
.startsWith("org.eclipse.osgi");
final static String OS_NAME;
static {
boolean tmp = false;
assert tmp = true; // set tmp to true if assertions are enabled
ASSERTIONS_ENABLED = tmp;
String osName;
try {
osName = "." + System.getProperty("os.name", "Unknown").replace(' ', '_');
} catch (Throwable e) {
osName = ".Unknown";
}
OS_NAME = osName;
loadPropertiesFromConfigFile();
if (getBoolean("findbugs.dumpProperties")) {
FileOutputStream out = null;
try {
out = new FileOutputStream("/tmp/outProperties.txt");
System.getProperties().store(out, "System properties dump");
properties.store(out, "FindBugs properties dump");
} catch (IOException e) {
assert true;
} finally {
IO.close(out);
}
}
}
private static void loadPropertiesFromConfigFile() {
URL systemProperties = DetectorFactoryCollection.getCoreResource("systemProperties.properties");
loadPropertiesFromURL(systemProperties);
String u = System.getProperty("findbugs.loadPropertiesFrom");
if (u != null)
try {
URL configURL = new URL(u);
loadPropertiesFromURL(configURL);
} catch (MalformedURLException e) {
AnalysisContext.logError("Unable to load properties from " + u, e);
}
}
public static Properties getLocalProperties() {
return properties;
}
public static Properties getAllProperties() {
Properties result = System.getProperties();
result.putAll(properties);
return result;
}
/**
* This method is public to allow clients to set system properties via any
* {@link URL}
*
* @param url
* an url to load system properties from, may be nullerrorMsg
*/
public static void loadPropertiesFromURL(URL url) {
if (url == null) {
return;
}
InputStream in = null;
try {
in = url.openStream();
properties.load(in);
} catch (IOException e) {
AnalysisContext.logError("Unable to load properties from " + url, e);
} finally {
IO.close(in);
}
}
/**
* Get boolean property, returning false if a security manager prevents us
* from accessing system properties
* <p>
* (incomplete) list of known system properties
* <ul>
* <li>
* "report_TESTING_pattern_in_standard_detectors" - default is false
* </li>
* </ul>
*
* @return true if the property exists and is set to true
*/
public static boolean getBoolean(String name) {
return getBoolean(name, false);
}
public static boolean getBoolean(String name, boolean defaultValue) {
boolean result = defaultValue;
try {
String value = getProperty(name);
if (value == null)
return defaultValue;
result = toBoolean(value);
} catch (IllegalArgumentException e) {
} catch (NullPointerException e) {
}
return result;
}
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
/**
* @param arg0
* property name
* @param arg1
* default value
* @return the int value (or arg1 if the property does not exist)
* @deprecated Use {@link #getInt(String,int)} instead
*/
@Deprecated
public static Integer getInteger(String arg0, int arg1) {
return getInt(arg0, arg1);
}
/**
* @param name
* property name
* @param defaultValue
* default value
* @return the int value (or defaultValue if the property does not exist)
*/
public static int getInt(String name, int defaultValue) {
try {
String value = getProperty(name);
if (value != null)
return Integer.decode(value);
} catch (Exception e) {
assert true;
}
return defaultValue;
}
/**
* @param name
* property name
* @return string value (or null if the property does not exist)
*/
public static String getOSDependentProperty(String name) {
String osDependentName = name + OS_NAME;
String value = getProperty(osDependentName);
if (value != null)
return value;
return getProperty(name);
}
/**
* @param name
* property name
* @return string value (or null if the property does not exist)
*/
public static String getProperty(String name) {
try {
String value = properties.getProperty(name);
if (value != null)
return value;
return System.getProperty(name);
} catch (Exception e) {
return null;
}
}
public static void setProperty(String name, String value) {
properties.setProperty(name, value);
}
/**
* @param name
* property name
* @param defaultValue
* default value
* @return string value (or defaultValue if the property does not exist)
*/
public static String getProperty(String name, String defaultValue) {
try {
String value = properties.getProperty(name);
if (value != null)
return value;
return System.getProperty(name, defaultValue);
} catch (Exception e) {
return defaultValue;
}
}
private static final String URL_REWRITE_PATTERN_STRING = getOSDependentProperty("findbugs.urlRewritePattern");
private static final String URL_REWRITE_FORMAT = getOSDependentProperty("findbugs.urlRewriteFormat");
private static final Pattern URL_REWRITE_PATTERN;
static {
Pattern p = null;
if (URL_REWRITE_PATTERN_STRING != null && URL_REWRITE_FORMAT != null) {
try {
p = Pattern.compile(URL_REWRITE_PATTERN_STRING);
String ignored = String.format(URL_REWRITE_FORMAT, "");
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Bad findbugs.urlRewritePattern '" + URL_REWRITE_PATTERN_STRING + "' - "
+ e.getClass().getSimpleName() + ": "+ e.getMessage());
} catch (IllegalFormatException e) {
throw new IllegalArgumentException("Bad findbugs.urlRewriteFormat '" + URL_REWRITE_FORMAT + "' - "
+ e.getClass().getSimpleName() + ": " + e.getMessage());
}
} else if (URL_REWRITE_PATTERN_STRING != null) {
throw new IllegalArgumentException("findbugs.urlRewritePattern is set but not findbugs.urlRewriteFormat");
} else if (URL_REWRITE_FORMAT != null) {
throw new IllegalArgumentException("findbugs.urlRewriteFormat is set but not findbugs.urlRewritePattern");
}
URL_REWRITE_PATTERN = p;
}
public static String rewriteURLAccordingToProperties(String u) {
if (URL_REWRITE_PATTERN == null || URL_REWRITE_FORMAT == null)
return u;
Matcher m = URL_REWRITE_PATTERN.matcher(u);
if (!m.matches() || m.groupCount() == 0)
return u;
String result = String.format(URL_REWRITE_FORMAT, m.group(1));
return result;
}
}
| findbugs/src/java/edu/umd/cs/findbugs/SystemProperties.java | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2006, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.io.IO;
/**
* @author pugh
*/
public class SystemProperties {
private static Properties properties = new Properties();
public final static boolean ASSERTIONS_ENABLED;
public static boolean RUNNING_IN_ECLIPSE = SystemProperties.class.getClassLoader().getClass().getCanonicalName()
.startsWith("org.eclipse.osgi");
final static String OS_NAME;
static {
boolean tmp = false;
assert tmp = true; // set tmp to true if assertions are enabled
ASSERTIONS_ENABLED = tmp;
String osName;
try {
osName = "." + System.getProperty("os.name", "Unknown").replace(' ', '_');
} catch (Throwable e) {
osName = ".Unknown";
}
OS_NAME = osName;
loadPropertiesFromConfigFile();
if (getBoolean("findbugs.dumpProperties")) {
FileOutputStream out = null;
try {
out = new FileOutputStream("/tmp/outProperties.txt");
System.getProperties().store(out, "System properties dump");
properties.store(out, "FindBugs properties dump");
} catch (IOException e) {
assert true;
} finally {
IO.close(out);
}
}
}
private static void loadPropertiesFromConfigFile() {
URL systemProperties = DetectorFactoryCollection.getCoreResource("systemProperties.properties");
loadPropertiesFromURL(systemProperties);
String u = System.getProperty("findbugs.loadPropertiesFrom");
if (u != null)
try {
URL configURL = new URL(u);
loadPropertiesFromURL(configURL);
} catch (MalformedURLException e) {
AnalysisContext.logError("Unable to load properties from " + u, e);
}
}
public static Properties getLocalProperties() {
return properties;
}
public static Properties getAllProperties() {
Properties result = System.getProperties();
result.putAll(properties);
return result;
}
/**
* This method is public to allow clients to set system properties via any
* {@link URL}
*
* @param url
* an url to load system properties from, may be nullerrorMsg
*/
public static void loadPropertiesFromURL(URL url) {
if (url == null) {
return;
}
InputStream in = null;
try {
in = url.openStream();
properties.load(in);
} catch (IOException e) {
AnalysisContext.logError("Unable to load properties from " + url, e);
} finally {
IO.close(in);
}
}
/**
* Get boolean property, returning false if a security manager prevents us
* from accessing system properties
* <p>
* (incomplete) list of known system properties
* <ul>
* <li>
* "report_TESTING_pattern_in_standard_detectors" - default is false
* </li>
* </ul>
*
* @return true if the property exists and is set to true
*/
public static boolean getBoolean(String name) {
return getBoolean(name, false);
}
public static boolean getBoolean(String name, boolean defaultValue) {
boolean result = defaultValue;
try {
String value = getProperty(name);
if (value == null)
return defaultValue;
result = toBoolean(value);
} catch (IllegalArgumentException e) {
} catch (NullPointerException e) {
}
return result;
}
private static boolean toBoolean(String name) {
return ((name != null) && name.equalsIgnoreCase("true"));
}
/**
* @param arg0
* property name
* @param arg1
* default value
* @return the int value (or arg1 if the property does not exist)
* @deprecated Use {@link #getInt(String,int)} instead
*/
@Deprecated
public static Integer getInteger(String arg0, int arg1) {
return getInt(arg0, arg1);
}
/**
* @param name
* property name
* @param defaultValue
* default value
* @return the int value (or defaultValue if the property does not exist)
*/
public static int getInt(String name, int defaultValue) {
try {
String value = getProperty(name);
if (value != null)
return Integer.decode(value);
} catch (Exception e) {
assert true;
}
return defaultValue;
}
/**
* @param name
* property name
* @return string value (or null if the property does not exist)
*/
public static String getOSDependentProperty(String name) {
String osDependentName = name + OS_NAME;
String value = getProperty(osDependentName);
if (value != null)
return value;
return getProperty(name);
}
/**
* @param name
* property name
* @return string value (or null if the property does not exist)
*/
public static String getProperty(String name) {
try {
String value = properties.getProperty(name);
if (value != null)
return value;
return System.getProperty(name);
} catch (Exception e) {
return null;
}
}
public static void setProperty(String name, String value) {
properties.setProperty(name, value);
}
/**
* @param name
* property name
* @param defaultValue
* default value
* @return string value (or defaultValue if the property does not exist)
*/
public static String getProperty(String name, String defaultValue) {
try {
String value = properties.getProperty(name);
if (value != null)
return value;
return System.getProperty(name, defaultValue);
} catch (Exception e) {
return defaultValue;
}
}
private static final String URL_REWRITE_PATTERN_STRING = getOSDependentProperty("findbugs.urlRewritePattern");
private static final String URL_REWRITE_FORMAT = getOSDependentProperty("findbugs.urlRewriteFormat");
private static final Pattern URL_REWRITE_PATTERN;
static {
Pattern p = null;
if (URL_REWRITE_PATTERN_STRING != null && URL_REWRITE_FORMAT != null)
try {
p = Pattern.compile(URL_REWRITE_PATTERN_STRING);
} catch (Exception e) {
assert true;
}
URL_REWRITE_PATTERN = p;
}
public static String rewriteURLAccordingToProperties(String u) {
if (URL_REWRITE_PATTERN == null || URL_REWRITE_FORMAT == null)
return u;
Matcher m = URL_REWRITE_PATTERN.matcher(u);
if (!m.matches())
return u;
String result = String.format(URL_REWRITE_FORMAT, m.group(1));
return result;
}
}
| Make problems with findbugs.urlRewritePattern and findbugs.urlRewriteFormat into fatal problems,
rather than something that gets silently ignored.
Fix #1203 Crash with wrong URL Rewrite Format
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@14837 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
| findbugs/src/java/edu/umd/cs/findbugs/SystemProperties.java | Make problems with findbugs.urlRewritePattern and findbugs.urlRewriteFormat into fatal problems, rather than something that gets silently ignored. | <ide><path>indbugs/src/java/edu/umd/cs/findbugs/SystemProperties.java
<ide> import java.io.InputStream;
<ide> import java.net.MalformedURLException;
<ide> import java.net.URL;
<add>import java.util.IllegalFormatException;
<ide> import java.util.Properties;
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<add>import java.util.regex.PatternSyntaxException;
<ide>
<ide> import edu.umd.cs.findbugs.ba.AnalysisContext;
<ide> import edu.umd.cs.findbugs.io.IO;
<ide> private static final String URL_REWRITE_FORMAT = getOSDependentProperty("findbugs.urlRewriteFormat");
<ide>
<ide> private static final Pattern URL_REWRITE_PATTERN;
<add>
<ide> static {
<ide> Pattern p = null;
<del> if (URL_REWRITE_PATTERN_STRING != null && URL_REWRITE_FORMAT != null)
<add> if (URL_REWRITE_PATTERN_STRING != null && URL_REWRITE_FORMAT != null) {
<ide> try {
<ide> p = Pattern.compile(URL_REWRITE_PATTERN_STRING);
<del> } catch (Exception e) {
<del> assert true;
<add> String ignored = String.format(URL_REWRITE_FORMAT, "");
<add> } catch (PatternSyntaxException e) {
<add> throw new IllegalArgumentException("Bad findbugs.urlRewritePattern '" + URL_REWRITE_PATTERN_STRING + "' - "
<add> + e.getClass().getSimpleName() + ": "+ e.getMessage());
<add> } catch (IllegalFormatException e) {
<add> throw new IllegalArgumentException("Bad findbugs.urlRewriteFormat '" + URL_REWRITE_FORMAT + "' - "
<add> + e.getClass().getSimpleName() + ": " + e.getMessage());
<ide> }
<add> } else if (URL_REWRITE_PATTERN_STRING != null) {
<add> throw new IllegalArgumentException("findbugs.urlRewritePattern is set but not findbugs.urlRewriteFormat");
<add> } else if (URL_REWRITE_FORMAT != null) {
<add> throw new IllegalArgumentException("findbugs.urlRewriteFormat is set but not findbugs.urlRewritePattern");
<add> }
<ide> URL_REWRITE_PATTERN = p;
<ide> }
<ide>
<ide> if (URL_REWRITE_PATTERN == null || URL_REWRITE_FORMAT == null)
<ide> return u;
<ide> Matcher m = URL_REWRITE_PATTERN.matcher(u);
<del> if (!m.matches())
<add> if (!m.matches() || m.groupCount() == 0)
<ide> return u;
<ide> String result = String.format(URL_REWRITE_FORMAT, m.group(1));
<ide> return result; |
|
Java | mit | error: pathspec 'app/src/main/java/me/cvhc/equationsolver/DecimalInputView.java' did not match any file(s) known to git
| a4afcfce2a686d5f642042a52baa0c23600e320c | 1 | cuihaoleo/AndroidEquationSolver,cuihaoleo/AndroidEquationSolver | package me.cvhc.equationsolver;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public class DecimalInputView extends TextView {
Double mValue;
String mEditDialogTitle = "Setting";
Double mDefaultValue;
final OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final DecimalInputView label = (DecimalInputView)v;
final DecimalSettingView settingView = new DecimalSettingView(getContext());
AlertDialog.Builder alert = new AlertDialog.Builder(getContext())
.setTitle(mEditDialogTitle)
.setView(settingView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
label.setValue(settingView.getInputValue());
}
})
.setNegativeButton(android.R.string.cancel, null);
final AlertDialog dialog = alert.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
if (mValue != null) {
settingView.setDefaultValue(mValue);
}
if (mDefaultValue != null) {
settingView.setDefaultValue(mDefaultValue);
}
dialog.show();
}
};
public DecimalInputView(Context context) {
super(context);
initView();
}
public DecimalInputView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public DecimalInputView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
public void initView() {
setOnClickListener(mOnClickListener);
}
public void setValue(Number value) {
mValue = value.doubleValue();
setText(mValue.toString());
}
public void setDefaultValue(Number number) {
mDefaultValue = number.doubleValue();
setHint(mDefaultValue.toString());
}
public double getValue() {
return mValue == null ? mDefaultValue : mValue;
}
}
| app/src/main/java/me/cvhc/equationsolver/DecimalInputView.java | forgot to add DecimalInputView.java
| app/src/main/java/me/cvhc/equationsolver/DecimalInputView.java | forgot to add DecimalInputView.java | <ide><path>pp/src/main/java/me/cvhc/equationsolver/DecimalInputView.java
<add>package me.cvhc.equationsolver;
<add>
<add>
<add>import android.app.AlertDialog;
<add>import android.content.Context;
<add>import android.content.DialogInterface;
<add>import android.util.AttributeSet;
<add>import android.view.View;
<add>import android.view.WindowManager;
<add>import android.widget.TextView;
<add>
<add>
<add>public class DecimalInputView extends TextView {
<add> Double mValue;
<add> String mEditDialogTitle = "Setting";
<add> Double mDefaultValue;
<add>
<add> final OnClickListener mOnClickListener = new OnClickListener() {
<add> @Override
<add> public void onClick(View v) {
<add> final DecimalInputView label = (DecimalInputView)v;
<add> final DecimalSettingView settingView = new DecimalSettingView(getContext());
<add>
<add> AlertDialog.Builder alert = new AlertDialog.Builder(getContext())
<add> .setTitle(mEditDialogTitle)
<add> .setView(settingView)
<add> .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
<add> @Override
<add> public void onClick(DialogInterface dialog, int which) {
<add> label.setValue(settingView.getInputValue());
<add> }
<add> })
<add> .setNegativeButton(android.R.string.cancel, null);
<add>
<add> final AlertDialog dialog = alert.create();
<add> dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
<add>
<add> if (mValue != null) {
<add> settingView.setDefaultValue(mValue);
<add> }
<add>
<add> if (mDefaultValue != null) {
<add> settingView.setDefaultValue(mDefaultValue);
<add> }
<add>
<add> dialog.show();
<add> }
<add> };
<add>
<add> public DecimalInputView(Context context) {
<add> super(context);
<add> initView();
<add> }
<add>
<add> public DecimalInputView(Context context, AttributeSet attrs) {
<add> super(context, attrs);
<add> initView();
<add> }
<add>
<add> public DecimalInputView(Context context, AttributeSet attrs, int defStyleAttr) {
<add> super(context, attrs, defStyleAttr);
<add> initView();
<add> }
<add>
<add> public void initView() {
<add> setOnClickListener(mOnClickListener);
<add> }
<add>
<add> public void setValue(Number value) {
<add> mValue = value.doubleValue();
<add> setText(mValue.toString());
<add> }
<add>
<add> public void setDefaultValue(Number number) {
<add> mDefaultValue = number.doubleValue();
<add> setHint(mDefaultValue.toString());
<add> }
<add>
<add> public double getValue() {
<add> return mValue == null ? mDefaultValue : mValue;
<add> }
<add>} |
|
Java | mit | 3d36efde76471f6b40f12d24e6b28e0836a8d13a | 0 | LostCodeStudios/JavaLib | package com.punchline.javalib.entities.systems;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Peripheral;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.punchline.javalib.entities.Entity;
/**
* Base class for any {@link EntitySystem} that can take user input.
* @author Natman64
* @created Jul 24, 2013
*/
public abstract class InputSystem extends EntitySystem implements InputProcessor {
//region Fields
/**
* The game's {@link InputMultiplexer}.
*/
protected InputMultiplexer input;
/**
* Whether this InputSystem processes accelerometer input. By default, this is automatically enabled if an accelerometer is available.
* Performance will be improved if subclasses set this to false.
*/
protected boolean tiltEnabled;
/**
* The accelerometer's x value, if it surpasses {@link #tiltThresholdX}.
*/
protected float tiltX;
/**
* The accelerometer's y value, if it surpasses {@link #tiltThresholdY}.
*/
protected float tiltY;
/**
* The accelerometer's z value, if it surpasses {@link #tiltThresholdZ}.
*/
protected float tiltZ;
//TODO tweak for best thresholds.
/**
* The minimum accelerometer x value that will trigger a tilt event.
*/
protected float tiltThresholdX = 1.5f;
/**
* The minimum accelerometer y value that will trigger a tilt event.
*/
protected float tiltThresholdY = 3f;
/**
* The minimum accelerometer z value that will trigger a tilt event.
*/
protected float tiltThresholdZ = 3f;
//endregion
//region Initialization/Disposal
/**
* Constructs an InputSystem.
* @param input The game's {@link InputMultiplexer}.
*/
public InputSystem(InputMultiplexer input) {
this.input = input;
input.addProcessor(this);
tiltEnabled = Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer);
}
/**
* Tells the game's {@link InputMultiplexer} to stop processing this
* system's input.
*/
@Override
public void dispose() {
input.removeProcessor(this);
}
//endregion
//region Processing
@Override
protected void process(Entity e) { }
@Override
public boolean canProcess(Entity e) {
return false; //By default, InputSystems don't process entities.
}
@Override
public void processEntities() {
//Process Accelerometer
if (tiltEnabled) {
//Get accelerometer info
float x = Gdx.input.getAccelerometerX();
float y = Gdx.input.getAccelerometerY();
float z = Gdx.input.getAccelerometerZ();
//Account for input thresholds
if (Math.abs(x) < tiltThresholdX) x = 0;
if (Math.abs(y) < tiltThresholdY) y = 0;
if (Math.abs(z) < tiltThresholdZ) z = 0;
//Trigger tilt events
if (x != tiltX) {
tiltX = x;
onTiltX(x);
}
if (y != tiltY) {
tiltY = y;
onTiltY(y);
}
if (z != tiltZ) {
tiltZ = z;
onTiltZ(z);
}
}
super.processEntities();
}
//endregion
//endregion
//region Events
@Override
public void pause() {
input.removeProcessor(this);
//Stop tilt events
tiltX = 0f;
tiltY = 0f;
tiltZ = 0f;
}
@Override
public void resume() {
input.addProcessor(this);
}
//endregion
//region Key Events
@Override
public boolean keyDown(int keycode) {
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
//endregion
//region Touch Events
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
//endregion
//region Mouse Events
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
//endregion
//region Tilt Events
/**
* Event called when the device's accelerometer x value changes.
* @param x The new accelerometer x value, or 0 if the real value falls below {@link #tiltThresholdX}.
*/
protected void onTiltX(float x) { }
/**
* Event called when the device's accelerometer y value changes.
* @param x The new accelerometer y value, or 0 if the real value falls below {@link #tiltThresholdY}.
*/
protected void onTiltY(float y) { }
/**
* Event called when the device's accelerometer z value changes.
* @param x The new accelerometer z value, or 0 if the real value falls below {@link #tiltThresholdZ}.
*/
protected void onTiltZ(float z) { }
//endregion
}
| JavaLib/src/com/punchline/javalib/entities/systems/InputSystem.java | package com.punchline.javalib.entities.systems;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.punchline.javalib.entities.Entity;
/**
* Base class for any {@link EntitySystem} that can take user input.
* @author Natman64
* @created Jul 24, 2013
*/
public abstract class InputSystem extends EntitySystem implements InputProcessor {
/**
* The game's {@link InputMultiplexer}.
*/
protected InputMultiplexer input;
//region Initialization/Disposal
/**
* Constructs an InputSystem.
* @param input The game's {@link InputMultiplexer}.
*/
public InputSystem(InputMultiplexer input) {
this.input = input;
input.addProcessor(this);
}
/**
* Tells the game's {@link InputMultiplexer} to stop processing this
* system's input.
*/
@Override
public void dispose() {
input.removeProcessor(this);
}
//endregion
@Override
protected void process(Entity e) {
//Empty so all InputSystems don't have to define it
}
//region Events
@Override
public void pause() {
input.removeProcessor(this);
}
@Override
public void resume() {
input.addProcessor(this);
}
//endregion
//region Input Events
@Override
public boolean keyDown(int keycode) {
return false;
}
@Override
public boolean canProcess(Entity e) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
//endregion
}
| Added accelerometer support to InputSystem. Fixes #35.
| JavaLib/src/com/punchline/javalib/entities/systems/InputSystem.java | Added accelerometer support to InputSystem. Fixes #35. | <ide><path>avaLib/src/com/punchline/javalib/entities/systems/InputSystem.java
<ide> package com.punchline.javalib.entities.systems;
<ide>
<add>import com.badlogic.gdx.Gdx;
<add>import com.badlogic.gdx.Input.Peripheral;
<ide> import com.badlogic.gdx.InputMultiplexer;
<ide> import com.badlogic.gdx.InputProcessor;
<ide> import com.punchline.javalib.entities.Entity;
<ide> */
<ide> public abstract class InputSystem extends EntitySystem implements InputProcessor {
<ide>
<add> //region Fields
<add>
<ide> /**
<ide> * The game's {@link InputMultiplexer}.
<ide> */
<ide> protected InputMultiplexer input;
<add>
<add> /**
<add> * Whether this InputSystem processes accelerometer input. By default, this is automatically enabled if an accelerometer is available.
<add> * Performance will be improved if subclasses set this to false.
<add> */
<add> protected boolean tiltEnabled;
<add>
<add> /**
<add> * The accelerometer's x value, if it surpasses {@link #tiltThresholdX}.
<add> */
<add> protected float tiltX;
<add>
<add> /**
<add> * The accelerometer's y value, if it surpasses {@link #tiltThresholdY}.
<add> */
<add> protected float tiltY;
<add>
<add> /**
<add> * The accelerometer's z value, if it surpasses {@link #tiltThresholdZ}.
<add> */
<add> protected float tiltZ;
<add>
<add> //TODO tweak for best thresholds.
<add>
<add> /**
<add> * The minimum accelerometer x value that will trigger a tilt event.
<add> */
<add> protected float tiltThresholdX = 1.5f;
<add>
<add> /**
<add> * The minimum accelerometer y value that will trigger a tilt event.
<add> */
<add> protected float tiltThresholdY = 3f;
<add>
<add> /**
<add> * The minimum accelerometer z value that will trigger a tilt event.
<add> */
<add> protected float tiltThresholdZ = 3f;
<add>
<add> //endregion
<ide>
<ide> //region Initialization/Disposal
<ide>
<ide> public InputSystem(InputMultiplexer input) {
<ide> this.input = input;
<ide> input.addProcessor(this);
<add>
<add> tiltEnabled = Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer);
<ide> }
<ide>
<ide> /**
<ide>
<ide> //endregion
<ide>
<del> @Override
<del> protected void process(Entity e) {
<del> //Empty so all InputSystems don't have to define it
<del> }
<del>
<add> //region Processing
<add>
<add> @Override
<add> protected void process(Entity e) { }
<add>
<add> @Override
<add> public boolean canProcess(Entity e) {
<add> return false; //By default, InputSystems don't process entities.
<add> }
<add>
<add> @Override
<add> public void processEntities() {
<add>
<add> //Process Accelerometer
<add> if (tiltEnabled) {
<add>
<add> //Get accelerometer info
<add> float x = Gdx.input.getAccelerometerX();
<add> float y = Gdx.input.getAccelerometerY();
<add> float z = Gdx.input.getAccelerometerZ();
<add>
<add> //Account for input thresholds
<add> if (Math.abs(x) < tiltThresholdX) x = 0;
<add> if (Math.abs(y) < tiltThresholdY) y = 0;
<add> if (Math.abs(z) < tiltThresholdZ) z = 0;
<add>
<add> //Trigger tilt events
<add> if (x != tiltX) {
<add> tiltX = x;
<add> onTiltX(x);
<add> }
<add>
<add> if (y != tiltY) {
<add> tiltY = y;
<add> onTiltY(y);
<add> }
<add>
<add> if (z != tiltZ) {
<add> tiltZ = z;
<add> onTiltZ(z);
<add> }
<add>
<add> }
<add>
<add> super.processEntities();
<add>
<add> }
<add>
<add> //endregion
<add>
<add> //endregion
<add>
<ide> //region Events
<del>
<add>
<ide> @Override
<ide> public void pause() {
<ide> input.removeProcessor(this);
<add>
<add> //Stop tilt events
<add> tiltX = 0f;
<add> tiltY = 0f;
<add> tiltZ = 0f;
<ide> }
<ide>
<ide> @Override
<ide>
<ide> //endregion
<ide>
<del> //region Input Events
<add> //region Key Events
<ide>
<ide> @Override
<ide> public boolean keyDown(int keycode) {
<ide> }
<ide>
<ide> @Override
<del> public boolean canProcess(Entity e) {
<del> // TODO Auto-generated method stub
<del> return false;
<del> }
<del>
<del> @Override
<ide> public boolean keyUp(int keycode) {
<ide> return false;
<ide> }
<ide> return false;
<ide> }
<ide>
<add> //endregion
<add>
<add> //region Touch Events
<add>
<ide> @Override
<ide> public boolean touchDown(int screenX, int screenY, int pointer, int button) {
<ide> return false;
<ide> return false;
<ide> }
<ide>
<add> //endregion
<add>
<add> //region Mouse Events
<add>
<ide> @Override
<ide> public boolean mouseMoved(int screenX, int screenY) {
<ide> return false;
<ide> public boolean scrolled(int amount) {
<ide> return false;
<ide> }
<del>
<add>
<add> //endregion
<add>
<add> //region Tilt Events
<add>
<add> /**
<add> * Event called when the device's accelerometer x value changes.
<add> * @param x The new accelerometer x value, or 0 if the real value falls below {@link #tiltThresholdX}.
<add> */
<add> protected void onTiltX(float x) { }
<add>
<add> /**
<add> * Event called when the device's accelerometer y value changes.
<add> * @param x The new accelerometer y value, or 0 if the real value falls below {@link #tiltThresholdY}.
<add> */
<add> protected void onTiltY(float y) { }
<add>
<add> /**
<add> * Event called when the device's accelerometer z value changes.
<add> * @param x The new accelerometer z value, or 0 if the real value falls below {@link #tiltThresholdZ}.
<add> */
<add> protected void onTiltZ(float z) { }
<add>
<ide> //endregion
<ide>
<ide> } |
|
Java | mit | 3063176b23d0dcb12af6129e9ed61ce984bbd364 | 0 | jugglinmike/es6draft,jugglinmike/es6draft,anba/es6draft,anba/es6draft,jugglinmike/es6draft,anba/es6draft,jugglinmike/es6draft | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.objects;
import static com.github.anba.es6draft.runtime.AbstractOperations.*;
import static com.github.anba.es6draft.runtime.internal.Errors.throwTypeError;
import static com.github.anba.es6draft.runtime.internal.Properties.createProperties;
import static com.github.anba.es6draft.runtime.types.Null.NULL;
import static com.github.anba.es6draft.runtime.types.Undefined.UNDEFINED;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.Initialisable;
import com.github.anba.es6draft.runtime.internal.Messages;
import com.github.anba.es6draft.runtime.internal.Properties.Accessor;
import com.github.anba.es6draft.runtime.internal.Properties.Function;
import com.github.anba.es6draft.runtime.internal.Properties.Prototype;
import com.github.anba.es6draft.runtime.internal.Properties.Value;
import com.github.anba.es6draft.runtime.internal.ScriptException;
import com.github.anba.es6draft.runtime.types.BuiltinSymbol;
import com.github.anba.es6draft.runtime.types.Intrinsics;
import com.github.anba.es6draft.runtime.types.Property;
import com.github.anba.es6draft.runtime.types.ScriptObject;
import com.github.anba.es6draft.runtime.types.Symbol;
import com.github.anba.es6draft.runtime.types.Type;
import com.github.anba.es6draft.runtime.types.builtins.BuiltinFunction;
import com.github.anba.es6draft.runtime.types.builtins.ExoticArguments;
import com.github.anba.es6draft.runtime.types.builtins.ExoticArray;
import com.github.anba.es6draft.runtime.types.builtins.ExoticBoundFunction;
import com.github.anba.es6draft.runtime.types.builtins.ExoticString;
import com.github.anba.es6draft.runtime.types.builtins.OrdinaryFunction;
import com.github.anba.es6draft.runtime.types.builtins.OrdinaryGenerator;
import com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject;
/**
* <h1>15 Standard Built-in ECMAScript Objects</h1><br>
* <h2>15.2 Object Objects</h2>
* <ul>
* <li>15.2.4 Properties of the Object Prototype Object
* <li>15.2.5 Properties of Object Instances
* </ul>
*/
public class ObjectPrototype extends OrdinaryObject implements Initialisable {
public ObjectPrototype(Realm realm) {
super(realm);
}
@Override
public void initialise(ExecutionContext cx) {
createProperties(this, cx, Properties.class);
}
public enum Properties {
;
@Prototype
public static final ScriptObject __proto__ = null;
/**
* 15.2.4.1 Object.prototype.constructor
*/
@Value(name = "constructor")
public static final Intrinsics constructor = Intrinsics.Object;
/**
* 15.2.4.2 Object.prototype.toString ( )
*/
@Function(name = "toString", arity = 0)
public static Object toString(ExecutionContext cx, Object thisValue) {
if (Type.isUndefined(thisValue)) {
return "[object Undefined]";
}
if (Type.isNull(thisValue)) {
return "[object Null]";
}
ScriptObject o = ToObject(cx, thisValue);
if (o instanceof Symbol) {
return "[object Symbol]";
}
String builtinTag;
if (o instanceof ExoticArray) {
builtinTag = "Array";
} else if (o instanceof ExoticString) {
builtinTag = "String";
} else if (o instanceof ExoticArguments) {
builtinTag = "Arguments";
} else if (o instanceof OrdinaryFunction || o instanceof OrdinaryGenerator
|| o instanceof BuiltinFunction || o instanceof ExoticBoundFunction) {
builtinTag = "Function";
} else if (o instanceof ErrorObject) {
builtinTag = "Error";
} else if (o instanceof BooleanObject) {
builtinTag = "Boolean";
} else if (o instanceof NumberObject) {
builtinTag = "Number";
} else if (o instanceof DateObject) {
builtinTag = "Date";
} else if (o instanceof RegExpObject) {
builtinTag = "RegExp";
} else if (o instanceof MathObject) {
builtinTag = "Math";
} else if (o instanceof JSONObject) {
builtinTag = "JSON";
} else {
builtinTag = "Object";
}
String tag;
boolean hasTag = HasProperty(cx, o, BuiltinSymbol.toStringTag.get());
if (!hasTag) {
tag = builtinTag;
} else {
try {
Object ttag = Get(cx, o, BuiltinSymbol.toStringTag.get());
if (Type.isString(ttag)) {
tag = Type.stringValue(ttag).toString();
} else {
tag = "???";
}
} catch (ScriptException e) {
tag = "???";
}
// FIXME: spec bug? (censor 'Object' again, but see Bug 1148) (Bug 1408/1459)
if (censoredNames.contains(tag) && !builtinTag.equals(tag)) {
tag = "~" + tag;
}
}
return "[object " + tag + "]";
}
private static final Set<String> censoredNames;
static {
List<String> names = Arrays.asList("Arguments", "Array", "Boolean", "Date", "Error",
"Function", "JSON", "Math", "Number", "RegExp", "String");
censoredNames = new HashSet<>(names);
}
/**
* 15.2.4.3 Object.prototype.toLocaleString ( )
*/
@Function(name = "toLocaleString", arity = 0)
public static Object toLocaleString(ExecutionContext cx, Object thisValue) {
return Invoke(cx, thisValue, "toString");
}
/**
* 15.2.4.4 Object.prototype.valueOf ( )
*/
@Function(name = "valueOf", arity = 0)
public static Object valueOf(ExecutionContext cx, Object thisValue) {
ScriptObject o = ToObject(cx, thisValue);
return o;
}
/**
* 15.2.4.5 Object.prototype.hasOwnProperty (V)
*/
@Function(name = "hasOwnProperty", arity = 1)
public static Object hasOwnProperty(ExecutionContext cx, Object thisValue, Object v) {
Object p = ToPropertyKey(cx, v);
ScriptObject o = ToObject(cx, thisValue);
if (p instanceof String) {
return o.hasOwnProperty(cx, (String) p);
} else {
return o.hasOwnProperty(cx, (Symbol) p);
}
}
/**
* 15.2.4.6 Object.prototype.isPrototypeOf (V)
*/
@Function(name = "isPrototypeOf", arity = 1)
public static Object isPrototypeOf(ExecutionContext cx, Object thisValue, Object v) {
if (!Type.isObject(v)) {
return false;
}
ScriptObject w = Type.objectValue(v);
ScriptObject o = ToObject(cx, thisValue);
for (;;) {
w = w.getPrototype(cx);
if (w == null) {
return false;
}
if (o == w) {
return true;
}
}
}
/**
* 15.2.4.7 Object.prototype.propertyIsEnumerable (V)
*/
@Function(name = "propertyIsEnumerable", arity = 1)
public static Object propertyIsEnumerable(ExecutionContext cx, Object thisValue, Object v) {
String p = ToFlatString(cx, v);
ScriptObject o = ToObject(cx, thisValue);
Property desc = o.getOwnProperty(cx, p);
if (desc == null) {
return false;
}
return desc.isEnumerable();
}
/**
* B.3.1.1 Object.prototype.__proto__
*/
@Accessor(name = "__proto__", type = Accessor.Type.Getter)
public static Object getPrototype(ExecutionContext cx, Object thisValue) {
ScriptObject o = ToObject(cx, thisValue);
ScriptObject p = o.getPrototype(cx);
return (p != null ? p : NULL);
}
/**
* B.3.1.1 Object.prototype.__proto__
*/
@Accessor(name = "__proto__", type = Accessor.Type.Setter)
public static Object setPrototype(ExecutionContext cx, Object thisValue, Object p) {
ScriptObject o = ToObject(cx, thisValue);
if (o.getRealm() != cx.getRealm()) {
throwTypeError(cx, Messages.Key.ObjectSetProtoCrossRealm);
}
if (!IsExtensible(cx, o)) {
throwTypeError(cx, Messages.Key.NotExtensible);
}
if (Type.isNull(p)) {
o.setPrototype(cx, null);
} else if (Type.isObject(p)) {
// TODO: check for cycles in proto-chain
o.setPrototype(cx, Type.objectValue(p));
}
return UNDEFINED;
}
}
}
| src/main/java/com/github/anba/es6draft/runtime/objects/ObjectPrototype.java | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.runtime.objects;
import static com.github.anba.es6draft.runtime.AbstractOperations.*;
import static com.github.anba.es6draft.runtime.internal.Errors.throwTypeError;
import static com.github.anba.es6draft.runtime.internal.Properties.createProperties;
import static com.github.anba.es6draft.runtime.types.Null.NULL;
import static com.github.anba.es6draft.runtime.types.Undefined.UNDEFINED;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.Initialisable;
import com.github.anba.es6draft.runtime.internal.Messages;
import com.github.anba.es6draft.runtime.internal.Properties.Accessor;
import com.github.anba.es6draft.runtime.internal.Properties.Function;
import com.github.anba.es6draft.runtime.internal.Properties.Prototype;
import com.github.anba.es6draft.runtime.internal.Properties.Value;
import com.github.anba.es6draft.runtime.internal.ScriptException;
import com.github.anba.es6draft.runtime.types.BuiltinSymbol;
import com.github.anba.es6draft.runtime.types.Intrinsics;
import com.github.anba.es6draft.runtime.types.Property;
import com.github.anba.es6draft.runtime.types.ScriptObject;
import com.github.anba.es6draft.runtime.types.Symbol;
import com.github.anba.es6draft.runtime.types.Type;
import com.github.anba.es6draft.runtime.types.builtins.BuiltinFunction;
import com.github.anba.es6draft.runtime.types.builtins.ExoticArguments;
import com.github.anba.es6draft.runtime.types.builtins.ExoticArray;
import com.github.anba.es6draft.runtime.types.builtins.ExoticBoundFunction;
import com.github.anba.es6draft.runtime.types.builtins.ExoticString;
import com.github.anba.es6draft.runtime.types.builtins.OrdinaryFunction;
import com.github.anba.es6draft.runtime.types.builtins.OrdinaryGenerator;
import com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject;
/**
* <h1>15 Standard Built-in ECMAScript Objects</h1><br>
* <h2>15.2 Object Objects</h2>
* <ul>
* <li>15.2.4 Properties of the Object Prototype Object
* <li>15.2.5 Properties of Object Instances
* </ul>
*/
public class ObjectPrototype extends OrdinaryObject implements Initialisable {
public ObjectPrototype(Realm realm) {
super(realm);
}
@Override
public void initialise(ExecutionContext cx) {
createProperties(this, cx, Properties.class);
}
public enum Properties {
;
@Prototype
public static final ScriptObject __proto__ = null;
/**
* 15.2.4.1 Object.prototype.constructor
*/
@Value(name = "constructor")
public static final Intrinsics constructor = Intrinsics.Object;
/**
* 15.2.4.2 Object.prototype.toString ( )
*/
@Function(name = "toString", arity = 0)
public static Object toString(ExecutionContext cx, Object thisValue) {
if (Type.isUndefined(thisValue)) {
return "[object Undefined]";
}
if (Type.isNull(thisValue)) {
return "[object Null]";
}
ScriptObject o = ToObject(cx, thisValue);
if (o instanceof Symbol) {
return "[object Symbol]";
}
String builtinTag;
if (o instanceof ExoticArray) {
builtinTag = "Array";
} else if (o instanceof ExoticString) {
builtinTag = "String";
} else if (o instanceof ExoticArguments) {
builtinTag = "Arguments";
} else if (o instanceof OrdinaryFunction || o instanceof OrdinaryGenerator
|| o instanceof BuiltinFunction || o instanceof ExoticBoundFunction) {
builtinTag = "Function";
} else if (o instanceof ErrorObject) {
builtinTag = "Error";
} else if (o instanceof BooleanObject) {
builtinTag = "Boolean";
} else if (o instanceof NumberObject) {
builtinTag = "Number";
} else if (o instanceof DateObject) {
builtinTag = "Date";
} else if (o instanceof RegExpObject) {
builtinTag = "RegExp";
} else if (o instanceof MathObject) {
builtinTag = "Math";
} else if (o instanceof JSONObject) {
builtinTag = "JSON";
} else {
builtinTag = "Object";
}
String tag;
boolean hasTag = HasProperty(cx, o, BuiltinSymbol.toStringTag.get());
if (!hasTag) {
tag = builtinTag;
} else {
try {
Object ttag = Get(cx, o, BuiltinSymbol.toStringTag.get());
if (Type.isString(ttag)) {
tag = Type.stringValue(ttag).toString();
} else {
tag = "???";
}
} catch (ScriptException e) {
tag = "???";
}
// FIXME: spec bug? (censor 'Object' again, but see Bug 1148) (Bug 1408)
if (censoredNames.contains(tag) && !builtinTag.equals(tag)) {
tag = "~" + tag;
}
}
return "[object " + tag + "]";
}
private static final Set<String> censoredNames;
static {
List<String> names = Arrays.asList("Arguments", "Array", "Boolean", "Date", "Error",
"Function", "JSON", "Math", "Number", "RegExp", "String");
censoredNames = new HashSet<>(names);
}
/**
* 15.2.4.3 Object.prototype.toLocaleString ( )
*/
@Function(name = "toLocaleString", arity = 0)
public static Object toLocaleString(ExecutionContext cx, Object thisValue) {
return Invoke(cx, thisValue, "toString");
}
/**
* 15.2.4.4 Object.prototype.valueOf ( )
*/
@Function(name = "valueOf", arity = 0)
public static Object valueOf(ExecutionContext cx, Object thisValue) {
ScriptObject o = ToObject(cx, thisValue);
return o;
}
/**
* 15.2.4.5 Object.prototype.hasOwnProperty (V)
*/
@Function(name = "hasOwnProperty", arity = 1)
public static Object hasOwnProperty(ExecutionContext cx, Object thisValue, Object v) {
Object p = ToPropertyKey(cx, v);
ScriptObject o = ToObject(cx, thisValue);
if (p instanceof String) {
return o.hasOwnProperty(cx, (String) p);
} else {
return o.hasOwnProperty(cx, (Symbol) p);
}
}
/**
* 15.2.4.6 Object.prototype.isPrototypeOf (V)
*/
@Function(name = "isPrototypeOf", arity = 1)
public static Object isPrototypeOf(ExecutionContext cx, Object thisValue, Object v) {
if (!Type.isObject(v)) {
return false;
}
ScriptObject w = Type.objectValue(v);
ScriptObject o = ToObject(cx, thisValue);
for (;;) {
w = w.getPrototype(cx);
if (w == null) {
return false;
}
if (o == w) {
return true;
}
}
}
/**
* 15.2.4.7 Object.prototype.propertyIsEnumerable (V)
*/
@Function(name = "propertyIsEnumerable", arity = 1)
public static Object propertyIsEnumerable(ExecutionContext cx, Object thisValue, Object v) {
String p = ToFlatString(cx, v);
ScriptObject o = ToObject(cx, thisValue);
Property desc = o.getOwnProperty(cx, p);
if (desc == null) {
return false;
}
return desc.isEnumerable();
}
/**
* B.3.1.1 Object.prototype.__proto__
*/
@Accessor(name = "__proto__", type = Accessor.Type.Getter)
public static Object getPrototype(ExecutionContext cx, Object thisValue) {
ScriptObject o = ToObject(cx, thisValue);
ScriptObject p = o.getPrototype(cx);
return (p != null ? p : NULL);
}
/**
* B.3.1.1 Object.prototype.__proto__
*/
@Accessor(name = "__proto__", type = Accessor.Type.Setter)
public static Object setPrototype(ExecutionContext cx, Object thisValue, Object p) {
ScriptObject o = ToObject(cx, thisValue);
if (o.getRealm() != cx.getRealm()) {
throwTypeError(cx, Messages.Key.ObjectSetProtoCrossRealm);
}
if (!IsExtensible(cx, o)) {
throwTypeError(cx, Messages.Key.NotExtensible);
}
if (Type.isNull(p)) {
o.setPrototype(cx, null);
} else if (Type.isObject(p)) {
// TODO: check for cycles in proto-chain
o.setPrototype(cx, Type.objectValue(p));
}
return UNDEFINED;
}
}
}
| Just add a comment
| src/main/java/com/github/anba/es6draft/runtime/objects/ObjectPrototype.java | Just add a comment | <ide><path>rc/main/java/com/github/anba/es6draft/runtime/objects/ObjectPrototype.java
<ide> } catch (ScriptException e) {
<ide> tag = "???";
<ide> }
<del> // FIXME: spec bug? (censor 'Object' again, but see Bug 1148) (Bug 1408)
<add> // FIXME: spec bug? (censor 'Object' again, but see Bug 1148) (Bug 1408/1459)
<ide> if (censoredNames.contains(tag) && !builtinTag.equals(tag)) {
<ide> tag = "~" + tag;
<ide> } |
|
Java | apache-2.0 | error: pathspec 'src/test/java/com/agapsys/jpa/PersistenceUnitTest.java' did not match any file(s) known to git
| 149cf2703be274727739a7db45b9d2b2060c3552 | 1 | agapsys/jpa-utils | /*
* Copyright 2015 Agapsys Tecnologia Ltda-ME.
*
* 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.agapsys.jpa;
import javax.persistence.EntityManager;
import org.junit.Test;
public class PersistenceUnitTest {
@Test
public void getEntityManager() {
PersistenceUnit persistenceUnit = PersistenceUnitFactory.getInstance();
EntityManager em = persistenceUnit.getEntityManager();
em.close();
}
}
| src/test/java/com/agapsys/jpa/PersistenceUnitTest.java | Added test for persistence unit | src/test/java/com/agapsys/jpa/PersistenceUnitTest.java | Added test for persistence unit | <ide><path>rc/test/java/com/agapsys/jpa/PersistenceUnitTest.java
<add>/*
<add> * Copyright 2015 Agapsys Tecnologia Ltda-ME.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package com.agapsys.jpa;
<add>
<add>import javax.persistence.EntityManager;
<add>import org.junit.Test;
<add>
<add>public class PersistenceUnitTest {
<add> @Test
<add> public void getEntityManager() {
<add> PersistenceUnit persistenceUnit = PersistenceUnitFactory.getInstance();
<add> EntityManager em = persistenceUnit.getEntityManager();
<add> em.close();
<add> }
<add>} |
|
Java | bsd-3-clause | 8fc1c73d6aa5d52db3ffd21e47e54d89ad92718c | 0 | lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon | /*
* $Id: XmlPropertyLoader.java,v 1.4 2004-06-17 22:44:19 smorabito Exp $
*/
/*
Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.util;
import java.util.*;
import java.io.*;
import javax.xml.parsers.*;
import org.mortbay.tools.PropertyTree;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.lockss.daemon.Configuration;
public class XmlPropertyLoader {
public static char PROPERTY_SEPARATOR = '.';
private static final String TAG_LOCKSSCONFIG = "lockss-config";
private static final String TAG_PROPERTY = "property";
private static final String TAG_VALUE = "value";
private static final String TAG_LIST = "list";
private static final String TAG_IF = "if";
private static final String TAG_THEN = "then";
private static final String TAG_ELSE = "else";
private static final String TAG_AND = "and";
private static final String TAG_OR = "or";
private static final String TAG_NOT = "not";
private static final String TAG_TEST = "test";
private static Logger log = Logger.getLogger("XmlPropertyLoader");
/**
* Load a set of XML properties from the input stream.
*/
public boolean load(PropertyTree props, InputStream istr) {
boolean isLoaded = false;
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(false);
SAXParser parser = factory.newSAXParser();
parser.parse(istr, new LockssConfigHandler(props));
isLoaded = true;
} catch (ParserConfigurationException ex) {
// Really shouldn't ever happen.
log.warning("parser configuration exception: " + ex);
} catch (SAXException ex) {
log.warning("SAX Exception: " + ex);
} catch (IOException ex) {
log.warning("IO Exception: " + ex);
}
return isLoaded;
}
public Version getDaemonVersion() {
return Configuration.getDaemonVersion();
}
public Version getPlatformVersion() {
return Configuration.getPlatformVersion();
}
public String getPlatformHostname() {
return Configuration.getPlatformHostname();
}
public String getPlatformGroup() {
return Configuration.getPlatformGroup();
}
/**
* SAX parser handler.
*/
class LockssConfigHandler extends DefaultHandler {
// Simple stack that helps us know what our current level in
// the property tree is.
private Stack m_propStack = new Stack();
// When building a list of configuration values for a single key.
private List m_propList = null;
// True iff the parser is currently inside a "value" element.
private boolean m_inValue = false;
// True iff the parser is currently inside a "list" element.
private boolean m_inList = false;
// True iff the parser is currently inside an "if" element.
private boolean m_inIf = false;
// True iff the parser is currently inside an "else" element.
private boolean m_inElse = false;
// True iff the parser is currently inside a "then" element.
private boolean m_inThen = false;
// True iff the parser is currently inside an "and" element.
private boolean m_inAnd = false;
// True iff the parser is currently inside an "or" element.
private boolean m_inOr = false;
// True iff the parser is currently inside a "not" element.
private boolean m_inNot = false;
// True iff the parser is currently inside a "test" element.
private boolean m_inTest = false;
// False iff the conditions in the propgroup attribute conditionals
// are not satisfied.
private boolean m_evalIf = false;
// The property tree we're adding to.
private PropertyTree m_props;
// Save the current running daemon and platform version
private Version m_sysPlatformVer = getPlatformVersion();
private Version m_sysDaemonVer = getDaemonVersion();
private String m_sysGroup = getPlatformGroup();
private String m_sysHostname = getPlatformHostname();
/**
* Default constructor.
*/
public LockssConfigHandler(PropertyTree props) {
super();
m_props = props;
}
/**
* <p>Evaluate this property iff:</p>
* <ol>
* <li>We're not in a propgroup conditional, or</li>
* <li>We're in a propgroup that we eval to true AND we're
* in a <then></li>
* <li>We're in a propgroup that we eval to false AND we're
* in an <else></li>
* <li>We're in a propgroup that we eval to true AND we're
* in neither a <then> or an <else></li>
* </ol>
*/
private boolean doEval() {
return (!m_inIf ||
((m_evalIf && m_inThen) ||
(!m_evalIf && m_inElse)) ||
(m_evalIf && !m_inThen && !m_inElse));
}
/**
* Handle the starting tags of elements. Based on the name of the
* tag, call the appropriate handler method.
*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes attrs)
throws SAXException {
if (TAG_IF.equals(qName)) {
startIfTag(attrs);
} else if (TAG_ELSE.equals(qName)) {
startElseTag();
} else if (TAG_LIST.equals(qName)) {
startListTag();
} else if (TAG_PROPERTY.equals(qName)) {
startPropertyTag(attrs);
} else if (TAG_THEN.equals(qName)) {
startThenTag();
} else if (TAG_VALUE.equals(qName)) {
startValueTag();
} else if (TAG_AND.equals(qName)) {
startAndTag();
} else if (TAG_OR.equals(qName)) {
startOrTag();
} else if (TAG_NOT.equals(qName)) {
startNotTag();
} else if (TAG_TEST.equals(qName)) {
startTestTag(attrs);
} else if (TAG_LOCKSSCONFIG.equals(qName)) {
; // do nothing
} else {
throw new IllegalArgumentException("Unexpected tag: " + qName);
}
}
/**
* Handle the ending tags of elements.
*/
public void endElement(String namespaceURI, String localName,
String qName)
throws SAXException {
if (TAG_IF.equals(qName)) {
endIfTag();
} else if (TAG_ELSE.equals(qName)) {
endElseTag();
} else if (TAG_LIST.equals(qName)) {
endListTag();
} else if (TAG_PROPERTY.equals(qName)) {
endPropertyTag();
} else if (TAG_THEN.equals(qName)) {
endThenTag();
} else if (TAG_VALUE.equals(qName)) {
endValueTag();
} else if (TAG_AND.equals(qName)) {
endAndTag();
} else if (TAG_OR.equals(qName)) {
endOrTag();
} else if (TAG_NOT.equals(qName)) {
endNotTag();
} else if (TAG_TEST.equals(qName)) {
endTestTag();
} else if (TAG_LOCKSSCONFIG.equals(qName)) {
; // do nothing
} else {
throw new IllegalArgumentException("Unexpected tag: " + qName);
}
}
/**
* Handle character data encountered in a tag. The character data
* should never be anything other than a property value.
*/
public void characters(char[] ch, int start, int length)
throws SAXException {
if (doEval()) {
String s = (new String(ch, start, length)).trim();
// The only character data in the property file should be
// inside "value" tags! It doesn't belong anywhere else.
if (m_inValue) {
if (m_inList) {
// If we're inside a list, we need to add this value to the
// current temporary property list.
m_propList.add(s);
} else {
// Otherwise, just add the property key and value to the prop
// tree.
setProperty(s);
}
}
}
}
/**
* Handle encountering the start of an "else" tag.
*/
private void startElseTag() {
m_inElse = true;
}
/**
* Handle encountering the start of a "list" tag.
*/
private void startListTag() {
if (doEval()) {
m_inList = true;
m_propList = new ArrayList();
}
}
/**
* Handle encountering a starting "property" tag. Get the
* property's name and value (if any). Name is required, value is
* not.
*/
private void startPropertyTag(Attributes attrs) {
if (doEval()) {
boolean hasValueAttr = false;
String name = attrs.getValue("name");
String value = attrs.getValue("value");
if (value != null) hasValueAttr = true;
m_propStack.push(name);
// If we have both a name and a value we can add it to the
// property tree right away.
if (hasValueAttr) {
setProperty(value);
}
}
}
/**
* Handle encountering the start of an "if" tag by parsing
* the conditional attributes and acting on them accordingly.
*/
private void startIfTag(Attributes attrs) {
m_inIf = true;
m_evalIf = evaluateAttributes(attrs);
}
/**
* Handle encountering a starting "then" tag.
*/
private void startThenTag() {
m_inThen = true;
}
/**
* Handle encountering a starting "value" tag.
*/
private void startValueTag() {
if (doEval()) {
// Inside a "value" element.
m_inValue = true;
}
}
/**
* Handle encountering a starting "and" tag.
*/
private void startAndTag() {
m_inAnd = true;
m_evalIf = true; // 'and' evaluates to true by default.
}
/**
* Handle encountering a starting "or" tag.
*/
private void startOrTag() {
m_inOr = true;
m_evalIf = false; // 'or' evaluates to false by default.
}
/**
* Handle encountering a starting "not" tag.
*/
private void startNotTag() {
m_inNot = true;
m_evalIf = true; // 'not' evaluates to true by default.
}
/**
* Depending on whether we are evaluating a test in an "and", an
* "or", or a "not", do the right thing.
*/
private void startTestTag(Attributes attrs) {
m_inTest = true;
if (m_inAnd) {
m_evalIf &= evaluateAttributes(attrs);
} else if (m_inOr) {
m_evalIf |= evaluateAttributes(attrs);
} else if (m_inNot) {
m_evalIf ^= evaluateAttributes(attrs);
}
}
/**
* Handle encoutering the end of an "else" tag.
*/
private void endElseTag() {
m_inElse = false;
}
/**
* Handle encountering the end of a "list" tag.
*/
private void endListTag() {
if (doEval()) {
setProperty(m_propList);
// Clean-up.
m_propList = null;
m_inList = false;
}
}
/**
* Handle encountering the end of a "property" tag.
*/
private void endPropertyTag() {
if (doEval()) {
m_propStack.pop();
}
}
/**
* Handle encountering the end of a "propgroup" tag.
*/
private void endIfTag() {
m_inIf = false;
m_evalIf = false; // Reset the evaluation boolean.
}
/**
* Handle encountering the end of a "then" tag.
*/
private void endThenTag() {
m_inThen = false;
}
/**
* Handle encountering the end of a "value" tag.
*/
private void endValueTag() {
if (doEval()) {
m_inValue = false;
}
}
/**
* Handle encountering the end of an "and" tag.
*/
private void endAndTag() {
m_inAnd = false;
}
/**
* Handle encountering the end of an "or" tag.
*/
private void endOrTag() {
m_inOr = false;
}
/**
* Handle encountering the end of a "not" tag.
*/
private void endNotTag() {
m_inNot = false;
}
/**
* Handle encountering the end of a "test" tag.
*/
private void endTestTag() {
m_inTest = false;
}
/**
* Return the current property name.
*/
private String getPropname() {
return StringUtil.separatedString(m_propStack, ".");
}
/**
* Log a warning if overwriting an existing property.
*/
public void setProperty(Object value) {
String prop = getPropname();
if (m_props.get(prop) != null) {
log.warning("Overwriting property '" + prop + "'. Was: '" +
m_props.get(prop) + "'," + "Now: '" + value + "'");
}
m_props.put(prop, value);
}
/**
* Evaluate the attributes of this test (whether an <if...> or a
* <test...> tag) and return the boolean value.
*/
public boolean evaluateAttributes(Attributes attrs) {
boolean returnVal = true;
// If we don't have any attributes, short-circuit.
if (attrs.getLength() == 0) {
return returnVal;
}
// Evaluate the attributes of the tag and set the
// value "returnVal" appropriately.
// Get the XML element attributes
String group = null;
String hostname = null;
Version daemonMin = null;
Version daemonMax = null;
Version platformMin = null;
Version platformMax = null;
group = attrs.getValue("group");
hostname = attrs.getValue("hostname");
if (attrs.getValue("daemonVersionMin") != null) {
daemonMin = new DaemonVersion(attrs.getValue("daemonVersionMin"));
}
if (attrs.getValue("daemonVersionMax") != null) {
daemonMax = new DaemonVersion(attrs.getValue("daemonVersionMax"));
}
if (attrs.getValue("daemonVersion") != null) {
if (daemonMin != null || daemonMax != null) {
throw new IllegalArgumentException("Cannot mix daemonMin, daemonMax " +
"and daemonVersion!");
}
daemonMin = daemonMax =
new DaemonVersion(attrs.getValue("daemonVersion"));
}
if (attrs.getValue("platformVersionMin") != null) {
platformMin = new PlatformVersion(attrs.getValue("platformVersionMin"));
}
if (attrs.getValue("platformVersionMax") != null) {
platformMax = new PlatformVersion(attrs.getValue("platformVersionMax"));
}
if (attrs.getValue("platformVersion") != null) {
if (platformMin != null || platformMax != null) {
throw new IllegalArgumentException("Cannot mix platformMin, " +
"platformMax and platformVersion!");
}
platformMin = platformMax =
new PlatformVersion(attrs.getValue("platformVersion"));
}
/*
* Group membership checking.
*/
if (group != null && m_sysGroup != null) {
returnVal &= StringUtil.equalStringsIgnoreCase(m_sysGroup, group);
}
/*
* Hostname checking.
*/
if (hostname != null && m_sysHostname != null) {
returnVal &= StringUtil.equalStringsIgnoreCase(m_sysHostname, hostname);
}
/*
* Daemon version checking.
*/
if (m_sysDaemonVer != null) {
if (daemonMin != null && daemonMax != null) {
// Have both daemon min and max...
returnVal &= ((m_sysDaemonVer.toLong() >= daemonMin.toLong()) &&
(m_sysDaemonVer.toLong() <= daemonMax.toLong()));
} else if (daemonMin != null) {
// Have only daemon min...
returnVal &= (m_sysDaemonVer.toLong() >= daemonMin.toLong());
} else if (daemonMax != null) {
// Have only daemon max...
returnVal &= (m_sysDaemonVer.toLong() <= daemonMax.toLong());
}
}
/*
* Platform version checking.
*/
if (m_sysPlatformVer != null) {
if (platformMin != null && platformMax != null) {
// Have both platform min and max...
returnVal &= ((m_sysPlatformVer.toLong() >= platformMin.toLong()) &&
(m_sysPlatformVer.toLong() <= platformMax.toLong()));
} else if (platformMin != null) {
// Have only platform min...
returnVal &= (m_sysPlatformVer.toLong() >= platformMin.toLong());
} else if (platformMax != null) {
// Have only platform max...
returnVal &= (m_sysPlatformVer.toLong() <= platformMax.toLong());
}
}
return returnVal;
}
}
}
| src/org/lockss/util/XmlPropertyLoader.java | /*
* $Id: XmlPropertyLoader.java,v 1.3 2004-06-15 21:43:23 smorabito Exp $
*/
/*
Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.util;
import java.util.*;
import java.io.*;
import javax.xml.parsers.*;
import org.mortbay.tools.PropertyTree;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.lockss.daemon.Configuration;
public class XmlPropertyLoader {
public static char PROPERTY_SEPARATOR = '.';
private static final String TAG_LOCKSSCONFIG = "lockss-config";
private static final String TAG_PROPERTY = "property";
private static final String TAG_VALUE = "value";
private static final String TAG_LIST = "list";
private static final String TAG_IF = "if";
private static final String TAG_THEN = "then";
private static final String TAG_ELSE = "else";
private static final String TAG_AND = "and";
private static final String TAG_OR = "or";
private static final String TAG_NOT = "not";
private static final String TAG_TEST = "test";
private static Logger log = Logger.getLogger("XmlPropertyLoader");
/**
* Load a set of XML properties from the input stream.
*/
public boolean load(PropertyTree props, InputStream istr) {
boolean isLoaded = false;
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(false);
SAXParser parser = factory.newSAXParser();
parser.parse(istr, new LockssConfigHandler(props));
isLoaded = true;
} catch (ParserConfigurationException ex) {
// Really shouldn't ever happen.
log.warning("parser configuration exception: " + ex);
} catch (SAXException ex) {
log.warning("SAX Exception: " + ex);
} catch (IOException ex) {
log.warning("IO Exception: " + ex);
}
return isLoaded;
}
public Version getDaemonVersion() {
return Configuration.getDaemonVersion();
}
public Version getPlatformVersion() {
return Configuration.getPlatformVersion();
}
public String getPlatformHostname() {
return Configuration.getPlatformHostname();
}
public String getPlatformGroup() {
return Configuration.getPlatformGroup();
}
/**
* SAX parser handler.
*/
class LockssConfigHandler extends DefaultHandler {
// Simple stack that helps us know what our current level in
// the property tree is.
private Stack m_propStack = new Stack();
// When building a list of configuration values for a single key.
private List m_propList = null;
// True iff the parser is currently inside a "value" element.
private boolean m_inValue = false;
// True iff the parser is currently inside a "list" element.
private boolean m_inList = false;
// True iff the parser is currently inside an "if" element.
private boolean m_inIf = false;
// True iff the parser is currently inside an "else" element.
private boolean m_inElse = false;
// True iff the parser is currently inside a "then" element.
private boolean m_inThen = false;
// True iff the parser is currently inside an "and" element.
private boolean m_inAnd = false;
// True iff the parser is currently inside an "or" element.
private boolean m_inOr = false;
// True iff the parser is currently inside a "not" element.
private boolean m_inNot = false;
// True iff the parser is currently inside a "test" element.
private boolean m_inTest = false;
// False iff the conditions in the propgroup attribute conditionals
// are not satisfied.
private boolean m_evalIf = false;
// The property tree we're adding to.
private PropertyTree m_props;
// Save the current running daemon and platform version
private Version m_sysPlatformVer = getPlatformVersion();
private Version m_sysDaemonVer = getDaemonVersion();
private String m_sysGroup = getPlatformGroup();
private String m_sysHostname = getPlatformHostname();
/**
* Default constructor.
*/
public LockssConfigHandler(PropertyTree props) {
super();
m_props = props;
}
/**
* <p>Evaluate this property iff:</p>
* <ol>
* <li>We're not in a propgroup conditional, or</li>
* <li>We're in a propgroup that we eval to true AND we're
* in a <then></li>
* <li>We're in a propgroup that we eval to false AND we're
* in an <else></li>
* <li>We're in a propgroup that we eval to true AND we're
* in neither a <then> or an <else></li>
* </ol>
*/
private boolean doEval() {
return (!m_inIf ||
((m_evalIf && m_inThen) ||
(!m_evalIf && m_inElse)) ||
(m_evalIf && !m_inThen && !m_inElse));
}
/**
* Handle the starting tags of elements. Based on the name of the
* tag, call the appropriate handler method.
*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes attrs)
throws SAXException {
if (TAG_IF.equals(qName)) {
startIfTag(attrs);
} else if (TAG_ELSE.equals(qName)) {
startElseTag();
} else if (TAG_LIST.equals(qName)) {
startListTag();
} else if (TAG_PROPERTY.equals(qName)) {
startPropertyTag(attrs);
} else if (TAG_THEN.equals(qName)) {
startThenTag();
} else if (TAG_VALUE.equals(qName)) {
startValueTag();
} else if (TAG_AND.equals(qName)) {
startAndTag();
} else if (TAG_OR.equals(qName)) {
startOrTag();
} else if (TAG_NOT.equals(qName)) {
startNotTag();
} else if (TAG_TEST.equals(qName)) {
startTestTag(attrs);
} else if (TAG_LOCKSSCONFIG.equals(qName)) {
; // do nothing
} else {
throw new IllegalArgumentException("Unexpected tag: " + qName);
}
}
/**
* Handle the ending tags of elements.
*/
public void endElement(String namespaceURI, String localName,
String qName)
throws SAXException {
if (TAG_IF.equals(qName)) {
endIfTag();
} else if (TAG_ELSE.equals(qName)) {
endElseTag();
} else if (TAG_LIST.equals(qName)) {
endListTag();
} else if (TAG_PROPERTY.equals(qName)) {
endPropertyTag();
} else if (TAG_THEN.equals(qName)) {
endThenTag();
} else if (TAG_VALUE.equals(qName)) {
endValueTag();
} else if (TAG_AND.equals(qName)) {
endAndTag();
} else if (TAG_OR.equals(qName)) {
endOrTag();
} else if (TAG_NOT.equals(qName)) {
endNotTag();
} else if (TAG_TEST.equals(qName)) {
endTestTag();
} else if (TAG_LOCKSSCONFIG.equals(qName)) {
; // do nothing
} else {
throw new IllegalArgumentException("Unexpected tag: " + qName);
}
}
/**
* Handle character data encountered in a tag. The character data
* should never be anything other than a property value.
*/
public void characters(char[] ch, int start, int length)
throws SAXException {
if (doEval()) {
String s = (new String(ch, start, length)).trim();
// The only character data in the property file should be
// inside "value" tags! It doesn't belong anywhere else.
if (m_inValue) {
if (m_inList) {
// If we're inside a list, we need to add this value to the
// current temporary property list.
m_propList.add(s);
} else {
// Otherwise, just add the property key and value to the prop
// tree.
setProperty(s);
}
}
}
}
/**
* Handle encountering the start of an "else" tag.
*/
private void startElseTag() {
m_inElse = true;
}
/**
* Handle encountering the start of a "list" tag.
*/
private void startListTag() {
if (doEval()) {
m_inList = true;
m_propList = new ArrayList();
}
}
/**
* Handle encountering a starting "property" tag. Get the
* property's name and value (if any). Name is required, value is
* not.
*/
private void startPropertyTag(Attributes attrs) {
if (doEval()) {
boolean hasValueAttr = false;
String name = attrs.getValue("name");
String value = attrs.getValue("value");
if (value != null) hasValueAttr = true;
m_propStack.push(name);
// If we have both a name and a value we can add it to the
// property tree right away.
if (hasValueAttr) {
setProperty(value);
}
}
}
/**
* Handle encountering the start of an "if" tag by parsing
* the conditional attributes and acting on them accordingly.
*/
private void startIfTag(Attributes attrs) {
m_inIf = true;
m_evalIf = evaluateAttributes(attrs);
}
/**
* Handle encountering a starting "then" tag.
*/
private void startThenTag() {
m_inThen = true;
}
/**
* Handle encountering a starting "value" tag.
*/
private void startValueTag() {
if (doEval()) {
// Inside a "value" element.
m_inValue = true;
}
}
/**
* Handle encountering a starting "and" tag.
*/
private void startAndTag() {
m_inAnd = true;
m_evalIf = true; // 'and' evaluates to true by default.
}
/**
* Handle encountering a starting "or" tag.
*/
private void startOrTag() {
m_inOr = true;
m_evalIf = false; // 'or' evaluates to false by default.
}
/**
* Handle encountering a starting "not" tag.
*/
private void startNotTag() {
m_inNot = true;
m_evalIf = true; // 'not' evaluates to true by default.
}
/**
* Depending on whether we are evaluating a test in an "and", an
* "or", or a "not", do the right thing.
*/
private void startTestTag(Attributes attrs) {
m_inTest = true;
if (m_inAnd) {
m_evalIf &= evaluateAttributes(attrs);
} else if (m_inOr) {
m_evalIf |= evaluateAttributes(attrs);
} else if (m_inNot) {
m_evalIf ^= evaluateAttributes(attrs);
}
}
/**
* Handle encoutering the end of an "else" tag.
*/
private void endElseTag() {
m_inElse = false;
}
/**
* Handle encountering the end of a "list" tag.
*/
private void endListTag() {
if (doEval()) {
setProperty(m_propList);
// Clean-up.
m_propList = null;
m_inList = false;
}
}
/**
* Handle encountering the end of a "property" tag.
*/
private void endPropertyTag() {
if (doEval()) {
m_propStack.pop();
}
}
/**
* Handle encountering the end of a "propgroup" tag.
*/
private void endIfTag() {
m_inIf = false;
m_evalIf = false; // Reset the evaluation boolean.
}
/**
* Handle encountering the end of a "then" tag.
*/
private void endThenTag() {
m_inThen = false;
}
/**
* Handle encountering the end of a "value" tag.
*/
private void endValueTag() {
if (doEval()) {
m_inValue = false;
}
}
/**
* Handle encountering the end of an "and" tag.
*/
private void endAndTag() {
m_inAnd = false;
}
/**
* Handle encountering the end of an "or" tag.
*/
private void endOrTag() {
m_inOr = false;
}
/**
* Handle encountering the end of a "not" tag.
*/
private void endNotTag() {
m_inNot = false;
}
/**
* Handle encountering the end of a "test" tag.
*/
private void endTestTag() {
m_inTest = false;
}
/**
* Return the current property name.
*/
private String getPropname() {
return StringUtil.separatedString(m_propStack, ".");
}
/**
* Log a warning if overwriting an existing property.
*/
public void setProperty(Object value) {
String prop = getPropname();
if (m_props.get(prop) == null) {
log.warning("Overwriting property '" + prop + "'. Was: '" +
m_props.get(prop) + "'," + "Now: '" + value + "'");
}
m_props.put(prop, value);
}
/**
* Evaluate the attributes of this test (whether an <if...> or a
* <test...> tag) and return the boolean value.
*/
public boolean evaluateAttributes(Attributes attrs) {
boolean returnVal = true;
// If we don't have any attributes, short-circuit.
if (attrs.getLength() == 0) {
return returnVal;
}
// Evaluate the attributes of the tag and set the
// value "returnVal" appropriately.
// Get the XML element attributes
String group = null;
String hostname = null;
Version daemonMin = null;
Version daemonMax = null;
Version platformMin = null;
Version platformMax = null;
group = attrs.getValue("group");
hostname = attrs.getValue("hostname");
if (attrs.getValue("daemonVersionMin") != null) {
daemonMin = new DaemonVersion(attrs.getValue("daemonVersionMin"));
}
if (attrs.getValue("daemonVersionMax") != null) {
daemonMax = new DaemonVersion(attrs.getValue("daemonVersionMax"));
}
if (attrs.getValue("daemonVersion") != null) {
if (daemonMin != null || daemonMax != null) {
throw new IllegalArgumentException("Cannot mix daemonMin, daemonMax " +
"and daemonVersion!");
}
daemonMin = daemonMax =
new DaemonVersion(attrs.getValue("daemonVersion"));
}
if (attrs.getValue("platformVersionMin") != null) {
platformMin = new PlatformVersion(attrs.getValue("platformVersionMin"));
}
if (attrs.getValue("platformVersionMax") != null) {
platformMax = new PlatformVersion(attrs.getValue("platformVersionMax"));
}
if (attrs.getValue("platformVersion") != null) {
if (platformMin != null || platformMax != null) {
throw new IllegalArgumentException("Cannot mix platformMin, " +
"platformMax and platformVersion!");
}
platformMin = platformMax =
new PlatformVersion(attrs.getValue("platformVersion"));
}
/*
* Group membership checking.
*/
if (group != null && m_sysGroup != null) {
returnVal &= StringUtil.equalStringsIgnoreCase(m_sysGroup, group);
}
/*
* Hostname checking.
*/
if (hostname != null && m_sysHostname != null) {
returnVal &= StringUtil.equalStringsIgnoreCase(m_sysHostname, hostname);
}
/*
* Daemon version checking.
*/
if (m_sysDaemonVer != null) {
if (daemonMin != null && daemonMax != null) {
// Have both daemon min and max...
returnVal &= ((m_sysDaemonVer.toLong() >= daemonMin.toLong()) &&
(m_sysDaemonVer.toLong() <= daemonMax.toLong()));
} else if (daemonMin != null) {
// Have only daemon min...
returnVal &= (m_sysDaemonVer.toLong() >= daemonMin.toLong());
} else if (daemonMax != null) {
// Have only daemon max...
returnVal &= (m_sysDaemonVer.toLong() <= daemonMax.toLong());
}
}
/*
* Platform version checking.
*/
if (m_sysPlatformVer != null) {
if (platformMin != null && platformMax != null) {
// Have both platform min and max...
returnVal &= ((m_sysPlatformVer.toLong() >= platformMin.toLong()) &&
(m_sysPlatformVer.toLong() <= platformMax.toLong()));
} else if (platformMin != null) {
// Have only platform min...
returnVal &= (m_sysPlatformVer.toLong() >= platformMin.toLong());
} else if (platformMax != null) {
// Have only platform max...
returnVal &= (m_sysPlatformVer.toLong() <= platformMax.toLong());
}
}
return returnVal;
}
}
}
| Correcting a typo in setProperty() ( == should have been != )
git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@3048 4f837ed2-42f5-46e7-a7a5-fa17313484d4
| src/org/lockss/util/XmlPropertyLoader.java | Correcting a typo in setProperty() ( == should have been != ) | <ide><path>rc/org/lockss/util/XmlPropertyLoader.java
<ide> /*
<del> * $Id: XmlPropertyLoader.java,v 1.3 2004-06-15 21:43:23 smorabito Exp $
<add> * $Id: XmlPropertyLoader.java,v 1.4 2004-06-17 22:44:19 smorabito Exp $
<ide> */
<ide>
<ide> /*
<ide> */
<ide> public void setProperty(Object value) {
<ide> String prop = getPropname();
<del> if (m_props.get(prop) == null) {
<add> if (m_props.get(prop) != null) {
<ide> log.warning("Overwriting property '" + prop + "'. Was: '" +
<ide> m_props.get(prop) + "'," + "Now: '" + value + "'");
<ide> |
|
JavaScript | bsd-3-clause | 730fe9ea98c3117951136e247535db5c34bd4e78 | 0 | AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker | var mouseState = false;
document.onmousedown = function (e) {
mouseState = true;
}
document.onmouseup = function (e) {
mouseState = false;
}
function applyClass(klass) {
"use strict";
/*
Checks all the table elements,
if they are selected, it removes the
selected class (and all other classes)
and applies the passed in class
*/
$("#holiday-table")
.find("td")
.each(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass();
$(this).addClass(klass);
js_calendar[parseInt($(this).attr("usrid"))][parseInt($(this).text())] = klass;
}
});
return true;
}
function submit_all() {
"use strict";
/*
Submits all entries on the form
Takes no parameters and returns true
depending on success.
*/
// setup our ajax properties
$.ajaxSetup({
type: 'POST',
dataType: 'json'
});
$.ajax({
url: '/ajax/',
data: {
'form_type': 'mass_holidays',
'year': $("#holiday-table").attr("year"), // from the table header
'month': $("#holiday-table").attr("month"),
'mass_data': JSON.stringify(js_calendar)
},
success: function(data) {
if (data.success === true) {
alert("Holidays updated successfully");
} else {
alert(data.error);
}
change_table_data();
},
error: function(ajaxObj, textStatus, error) {
alert(error);
}
});
return true;
}
function submit_holidays(user_id) {
"use strict";
/*
En masse changes a set of holidays and
takes a user_id as a parameter.
Mass is true/false, if true it
Returns true for success, false for error
*/
if (!user_id) {
return true;
}
// create a map to hold the holidays
var daytypes = new Array()
// iterate through the table and check if it's
// selected or not, if it's selected, ignore it.
// else, add the number and the class to the map.
var x;
for (x = 1; x < js_calendar[user_id].length; x++) {
daytypes[x] = js_calendar[user_id][x];
}
// setup our ajax properties
$.ajaxSetup({
type: 'POST',
dataType: 'json'
});
var holiday_map = {};
holiday_map[user_id] = daytypes;
$.ajax({
url: '/ajax/',
data: {
'form_type': 'mass_holidays',
'year': $("#holiday-table").attr("year"), // from the table header
'month': $("#holiday-table").attr("month"),
'mass_data': JSON.stringify(holiday_map)
},
success: function(data) {
if (data.success === true) {
alert("Holidays updated successfully");
} else {
alert(data.error);
}
change_table_data();
},
error: function(ajaxObj, textStatus, error) {
alert(error);
}
});
// return true so programmatic callers can
// see we've completed
return true;
}
function addFunctions () {
"use strict";
// all the daytype classes
// are assigned a click handler which
// swaps the colour depending on what
// it currently is.
$("#holiday-table")
.find('.empty, .DAYOD, .TRAIN, '
+ '.WKDAY, .SICKD, .HOLIS, '
+ '.SPECI, .MEDIC, .PUABS, '
+ '.PUWRK, .SATUR, .RETRN, '
+ '.WKHOM, .OTHER, .ROVER, '
+ '.WKEND')
.not(":button")
.attr("unselectable", "on") // make it so you can't select text
.mouseover(function (e) {
if (mouseState) {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
e.preventDefault();
e.stopPropagation();
}
})
.mousedown(function (e) {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
});
$("#year_select").val($("#holiday-table").attr("year"));
$("#month_select").val($("#holiday-table").attr("month"));
$("#process_select").val($("#holiday-table").attr("process"));
$("#employees-select, #day_options").change(function () {
retrieveComments();
});
$("#year_select, #month_select, #process_select").change(function () {
change_table_data();
});
$("#holiday-table")
.attr("border", "1")
return true;
}
function change_table_data () {
"use strict";
/*
Function which takes the values of the select boxes
constructs an ajax call based on those and replaces
the table with the data returned from the ajax call
*/
var year = $("#year_select").val();
var month = $("#month_select").val();
var process = $("#process_select").val();
if (process === "ALL") {
process = "";
}
if (process == null) {
process = "";
}
var url = [
"/holiday_planning/", year,
"/", month, "/", process
].join('');
$.ajax({
type: "GET",
dataType: "HTML",
url: url,
success: function(data) {
$("#holiday-wrapper, #comments-wrapper").fadeTo(500, 0, function() {
/*
IE7 doesn't work with .html('<htmlstring>') so we use
the .load() function instead.
*/
if ( $("#isie").attr("isie") === "true" ) {
$("#comments-wrapper").load(
url + " #com-field"
);
$("#holiday-wrapper").load(
url + " #holiday-table",
function() {
addFunctions();
retrieveComments();
});
} else {
var holiday_html = $(data).find("#holiday-wrapper").html();
var comments_html = $(data).find("#comments-wrapper").html();
var table_year = $(data).find("#holiday-table").attr("year");
var table_month = $(data).find("#holiday-table").attr("month");
$("#com-field").html(comments_html);
$("#holiday-table").html(holiday_html);
}
$("#holiday-table").attr("year", table_year);
$("#holiday-table").attr("month", table_month);
addFunctions();
$("#year_select").val(year);
$("#month_select").val(month);
if (process === "") {
$("#process_select").val("ALL");
} else {
$("#process_select").val(process);
}
$(data).find("div").each(function() {
if ($(this).attr("id") === "newjs") {
eval($(this).text());
}
});
$("#holiday-wrapper, #comments-wrapper").fadeTo(500, 1);
});
}
});
return true;
}
function removeComment() {
"use strict";
/*
Function which removes a comment from the database for a specific
tracking entry.
*/
$.ajaxSetup({
type: "POST",
dataType: "json"
});
$.ajax({
url: '/ajax/',
data: {
form_type: 'remove_comment',
year: $("#holiday-table").attr("year"),
month: $("#holiday-table").attr("month"),
user: $("#user_select").val(),
day: $("#day_options").val()
},
success: function (data) {
if (data.success) {
retrieveComments();
change_table_data();
} else {
alert(data.error)
}
},
error: function (data) {
alert(data.error);
}
});
}
function insertComment() {
"use strict";
/*
Function which inserts a comment into the database for a specific
tracking entry.
*/
$.ajaxSetup({
type: "POST",
dataType: "json"
});
$.ajax({
url: '/ajax/',
data: {
form_type: 'add_comment',
year: $("#holiday-table").attr("year"),
month: $("#holiday-table").attr("month"),
user: $("#user_select").val(),
day: $("#day_options").val(),
comment: $("#comments-field-comment").val()
},
success: function (data) {
if (data.success) {
retrieveComments();
change_table_data();
} else {
alert(data.error)
}
},
error: function (data) {
alert(data.error);
}
});
}
function retrieveComments() {
"use strict";
/*
Function which retrieves the comment associated with a tracking entry,
this allows managers to apply a comment onto a field and edit the
comments that they have already added onto a field by selecting the
dates that they used it on.
*/
$.ajaxSetup({
type: "GET",
dataType: "json"
});
$("#comments-field-comment").val('');
$.ajax({
url: '/ajax/',
data: {
form_type: 'get_comments',
year: $("#holiday-table").attr("year"),
month: $("#holiday-table").attr("month"),
user: $("#user_select").val(),
day: $("#day_options").val()
},
success: function (data) {
if (data.success) {
$("#comments-field-comment").val(data.comment);
} else {
alert(data.error)
}
},
error: function(data) {
alert(data.error);
}
});
return true;
}
$(function () {
"use strict";
addFunctions();
});
| static/js/holiday_page.js | var mouseState = false;
document.onmousedown = function (e) {
mouseState = true;
}
document.onmouseup = function (e) {
mouseState = false;
}
function applyClass(klass) {
"use strict";
/*
Checks all the table elements,
if they are selected, it removes the
selected class (and all other classes)
and applies the passed in class
*/
$("#holiday-table")
.find("td")
.each(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass();
$(this).addClass(klass);
js_calendar[parseInt($(this).attr("usrid"))][parseInt($(this).text())] = klass;
}
});
return true;
}
function submit_all() {
"use strict";
/*
Submits all entries on the form
Takes no parameters and returns true
depending on success.
*/
// setup our ajax properties
$.ajaxSetup({
type: 'POST',
dataType: 'json'
});
$.ajax({
url: '/ajax/',
data: {
'form_type': 'mass_holidays',
'year': $("#holiday-table").attr("year"), // from the table header
'month': $("#holiday-table").attr("month"),
'mass_data': JSON.stringify(js_calendar)
},
success: function(data) {
if (data.success === true) {
alert("Holidays updated successfully");
} else {
alert(data.error);
}
change_table_data();
},
error: function(ajaxObj, textStatus, error) {
alert(error);
}
});
return true;
}
function submit_holidays(user_id) {
"use strict";
/*
En masse changes a set of holidays and
takes a user_id as a parameter.
Mass is true/false, if true it
Returns true for success, false for error
*/
if (!user_id) {
return true;
}
// create a map to hold the holidays
var daytypes = new Array()
// iterate through the table and check if it's
// selected or not, if it's selected, ignore it.
// else, add the number and the class to the map.
var x;
for (x = 1; x < js_calendar[user_id].length; x++) {
daytypes[x] = js_calendar[user_id][x];
}
// setup our ajax properties
$.ajaxSetup({
type: 'POST',
dataType: 'json'
});
var holiday_map = JSON;
holiday_map[user_id] = daytypes;
$.ajax({
url: '/ajax/',
data: {
'form_type': 'mass_holidays',
'year': $("#holiday-table").attr("year"), // from the table header
'month': $("#holiday-table").attr("month"),
'mass_data': JSON.stringify(holiday_map)
},
success: function(data) {
if (data.success === true) {
alert("Holidays updated successfully");
} else {
alert(data.error);
}
change_table_data();
},
error: function(ajaxObj, textStatus, error) {
alert(error);
}
});
// return true so programmatic callers can
// see we've completed
return true;
}
function addFunctions () {
"use strict";
// all the daytype classes
// are assigned a click handler which
// swaps the colour depending on what
// it currently is.
$("#holiday-table")
.find('.empty, .DAYOD, .TRAIN, '
+ '.WKDAY, .SICKD, .HOLIS, '
+ '.SPECI, .MEDIC, .PUABS, '
+ '.PUWRK, .SATUR, .RETRN, '
+ '.WKHOM, .OTHER, .ROVER, '
+ '.WKEND')
.not(":button")
.attr("unselectable", "on") // make it so you can't select text
.mouseover(function (e) {
if (mouseState) {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
e.preventDefault();
e.stopPropagation();
}
})
.mousedown(function (e) {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
});
$("#year_select").val($("#holiday-table").attr("year"));
$("#month_select").val($("#holiday-table").attr("month"));
$("#process_select").val($("#holiday-table").attr("process"));
$("#employees-select, #day_options").change(function () {
retrieveComments();
});
$("#year_select, #month_select, #process_select").change(function () {
change_table_data();
});
$("#holiday-table")
.attr("border", "1")
return true;
}
function change_table_data () {
"use strict";
/*
Function which takes the values of the select boxes
constructs an ajax call based on those and replaces
the table with the data returned from the ajax call
*/
var year = $("#year_select").val();
var month = $("#month_select").val();
var process = $("#process_select").val();
if (process === "ALL") {
process = "";
}
if (process == null) {
process = "";
}
var url = [
"/holiday_planning/", year,
"/", month, "/", process
].join('');
$.ajax({
type: "GET",
dataType: "HTML",
url: url,
success: function(data) {
$("#holiday-wrapper, #comments-wrapper").fadeTo(500, 0, function() {
/*
IE7 doesn't work with .html('<htmlstring>') so we use
the .load() function instead.
*/
if ( $("#isie").attr("isie") === "true" ) {
$("#comments-wrapper").load(
url + " #com-field"
);
$("#holiday-wrapper").load(
url + " #holiday-table",
function() {
addFunctions();
retrieveComments();
});
} else {
var holiday_html = $(data).find("#holiday-wrapper").html();
var comments_html = $(data).find("#comments-wrapper").html();
var table_year = $(data).find("#holiday-table").attr("year");
var table_month = $(data).find("#holiday-table").attr("month");
$("#com-field").html(comments_html);
$("#holiday-table").html(holiday_html);
}
$("#holiday-table").attr("year", table_year);
$("#holiday-table").attr("month", table_month);
addFunctions();
$("#year_select").val(year);
$("#month_select").val(month);
if (process === "") {
$("#process_select").val("ALL");
} else {
$("#process_select").val(process);
}
$(data).find("div").each(function() {
if ($(this).attr("id") === "newjs") {
eval($(this).text());
}
});
console.log(js_calendar);
$("#holiday-wrapper, #comments-wrapper").fadeTo(500, 1);
});
}
});
return true;
}
function removeComment() {
"use strict";
/*
Function which removes a comment from the database for a specific
tracking entry.
*/
$.ajaxSetup({
type: "POST",
dataType: "json"
});
$.ajax({
url: '/ajax/',
data: {
form_type: 'remove_comment',
year: $("#holiday-table").attr("year"),
month: $("#holiday-table").attr("month"),
user: $("#user_select").val(),
day: $("#day_options").val()
},
success: function (data) {
if (data.success) {
retrieveComments();
change_table_data();
} else {
alert(data.error)
}
},
error: function (data) {
alert(data.error);
}
});
}
function insertComment() {
"use strict";
/*
Function which inserts a comment into the database for a specific
tracking entry.
*/
$.ajaxSetup({
type: "POST",
dataType: "json"
});
$.ajax({
url: '/ajax/',
data: {
form_type: 'add_comment',
year: $("#holiday-table").attr("year"),
month: $("#holiday-table").attr("month"),
user: $("#user_select").val(),
day: $("#day_options").val(),
comment: $("#comments-field-comment").val()
},
success: function (data) {
if (data.success) {
retrieveComments();
change_table_data();
} else {
alert(data.error)
}
},
error: function (data) {
alert(data.error);
}
});
}
function retrieveComments() {
"use strict";
/*
Function which retrieves the comment associated with a tracking entry,
this allows managers to apply a comment onto a field and edit the
comments that they have already added onto a field by selecting the
dates that they used it on.
*/
$.ajaxSetup({
type: "GET",
dataType: "json"
});
$("#comments-field-comment").val('');
$.ajax({
url: '/ajax/',
data: {
form_type: 'get_comments',
year: $("#holiday-table").attr("year"),
month: $("#holiday-table").attr("month"),
user: $("#user_select").val(),
day: $("#day_options").val()
},
success: function (data) {
if (data.success) {
$("#comments-field-comment").val(data.comment);
} else {
alert(data.error)
}
},
error: function(data) {
alert(data.error);
}
});
return true;
}
$(function () {
"use strict";
addFunctions();
});
| Finally. Possibly. Maybe. Fixed the heisenbug for phantom entries.
| static/js/holiday_page.js | Finally. Possibly. Maybe. Fixed the heisenbug for phantom entries. | <ide><path>tatic/js/holiday_page.js
<ide> dataType: 'json'
<ide> });
<ide>
<del> var holiday_map = JSON;
<del> holiday_map[user_id] = daytypes;
<del>
<add> var holiday_map = {};
<add> holiday_map[user_id] = daytypes;
<ide> $.ajax({
<ide> url: '/ajax/',
<ide> data: {
<ide> eval($(this).text());
<ide> }
<ide> });
<del> console.log(js_calendar);
<ide> $("#holiday-wrapper, #comments-wrapper").fadeTo(500, 1);
<ide> });
<ide> } |
|
JavaScript | agpl-3.0 | 7047d46132e55fc7e1468e59c3883172f560cf07 | 0 | ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs | "use strict";
var g_fontManager2 = null;
function CClipManager()
{
this.clipRects = [];
this.curRect = new _rect();
this.BaseObject = null;
this.AddRect = function(x, y, w, h)
{
var _count = this.clipRects.length;
if (0 == _count)
{
this.curRect.x = x;
this.curRect.y = y;
this.curRect.w = w;
this.curRect.h = h;
var _r = new _rect();
_r.x = x;
_r.y = y;
_r.w = w;
_r.h = h;
this.clipRects[_count] = _r;
this.BaseObject.SetClip(this.curRect);
}
else
{
this.BaseObject.RemoveClip();
var _r = new _rect();
_r.x = x;
_r.y = y;
_r.w = w;
_r.h = h;
this.clipRects[_count] = _r;
this.curRect = this.IntersectRect(this.curRect, _r);
this.BaseObject.SetClip(this.curRect);
}
}
this.RemoveRect = function()
{
var _count = this.clipRects.length;
if (0 != _count)
{
this.clipRects.splice(_count - 1, 1);
--_count;
this.BaseObject.RemoveClip();
if (0 != _count)
{
this.curRect.x = this.clipRects[0].x;
this.curRect.y = this.clipRects[0].y;
this.curRect.w = this.clipRects[0].w;
this.curRect.h = this.clipRects[0].h;
for (var i = 1; i < _count; i++)
this.curRect = this.IntersectRect(this.curRect, this.clipRects[i]);
this.BaseObject.SetClip(this.curRect);
}
}
}
this.IntersectRect = function(r1, r2)
{
var res = new _rect();
res.x = Math.max(r1.x, r2.x);
res.y = Math.max(r1.y, r2.y);
res.w = Math.min(r1.x + r1.w, r2.x + r2.w) - res.x;
res.h = Math.min(r1.y + r1.h, r2.y + r2.h) - res.y;
if (0 > res.w)
res.w = 0;
if (0 > res.h)
res.h = 0;
return res;
}
}
function CPen()
{
this.Color = { R : 255, G : 255, B : 255, A : 255 };
this.Style = 0;
this.LineCap = 0;
this.LineJoin = 0;
this.LineWidth = 1;
}
function CBrush()
{
this.Color1 = { R : 255, G : 255, B : 255, A : 255 };
this.Color2 = { R : 255, G : 255, B : 255, A : 255 };
this.Type = 0;
}
var MATRIX_ORDER_PREPEND = 0;
var MATRIX_ORDER_APPEND = 1;
var bIsChrome = AscBrowser.isChrome;
var bIsSafari = AscBrowser.isSafari;
var bIsIE = AscBrowser.isIE;
var bIsAndroid = AscBrowser.isAndroid;
function deg2rad(deg){
return deg * Math.PI / 180.0;
}
function rad2deg(rad){
return rad * 180.0 / Math.PI;
}
function CMatrix()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
}
CMatrix.prototype =
{
Reset : function(){
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
},
// ���������
Multiply : function(matrix,order){
if (MATRIX_ORDER_PREPEND == order)
{
var m = new CMatrix();
m.sx = matrix.sx;
m.shx = matrix.shx;
m.shy = matrix.shy;
m.sy = matrix.sy;
m.tx = matrix.tx;
m.ty = matrix.ty;
m.Multiply(this, MATRIX_ORDER_APPEND);
this.sx = m.sx;
this.shx = m.shx;
this.shy = m.shy;
this.sy = m.sy;
this.tx = m.tx;
this.ty = m.ty;
}
else
{
var t0 = this.sx * matrix.sx + this.shy * matrix.shx;
var t2 = this.shx * matrix.sx + this.sy * matrix.shx;
var t4 = this.tx * matrix.sx + this.ty * matrix.shx + matrix.tx;
this.shy = this.sx * matrix.shy + this.shy * matrix.sy;
this.sy = this.shx * matrix.shy + this.sy * matrix.sy;
this.ty = this.tx * matrix.shy + this.ty * matrix.sy + matrix.ty;
this.sx = t0;
this.shx = t2;
this.tx = t4;
}
return this;
},
// � ������ ������� ������ ���������� (��� �������� �����������)
Translate : function(x,y,order){
var m = new CMatrix();
m.tx = x;
m.ty = y;
this.Multiply(m,order);
},
Scale : function(x,y,order){
var m = new CMatrix();
m.sx = x;
m.sy = y;
this.Multiply(m,order);
},
Rotate : function(a,order){
var m = new CMatrix();
var rad = deg2rad(a);
m.sx = Math.cos(rad);
m.shx = Math.sin(rad);
m.shy = -Math.sin(rad);
m.sy = Math.cos(rad);
this.Multiply(m,order);
},
RotateAt : function(a,x,y,order){
this.Translate(-x,-y,order);
this.Rotate(a,order);
this.Translate(x,y,order);
},
// determinant
Determinant : function(){
return this.sx * this.sy - this.shy * this.shx;
},
// invert
Invert : function(){
var det = this.Determinant();
if (0.0001 > Math.abs(det))
return;
var d = 1 / det;
var t0 = this.sy * d;
this.sy = this.sx * d;
this.shy = -this.shy * d;
this.shx = -this.shx * d;
var t4 = -this.tx * t0 - this.ty * this.shx;
this.ty = -this.tx * this.shy - this.ty * this.sy;
this.sx = t0;
this.tx = t4;
return this;
},
// transform point
TransformPointX : function(x,y){
return x * this.sx + y * this.shx + this.tx;
},
TransformPointY : function(x,y){
return x * this.shy + y * this.sy + this.ty;
},
// calculate rotate angle
GetRotation : function(){
var x1 = 0.0;
var y1 = 0.0;
var x2 = 1.0;
var y2 = 0.0;
this.TransformPoint(x1, y1);
this.TransformPoint(x2, y2);
var a = Math.atan2(y2-y1,x2-x1);
return rad2deg(a);
},
// ������� ���������
CreateDublicate : function(){
var m = new CMatrix();
m.sx = this.sx;
m.shx = this.shx;
m.shy = this.shy;
m.sy = this.sy;
m.tx = this.tx;
m.ty = this.ty;
return m;
},
IsIdentity : function()
{
if (this.sx == 1.0 &&
this.shx == 0.0 &&
this.shy == 0.0 &&
this.sy == 1.0 &&
this.tx == 0.0 &&
this.ty == 0.0)
{
return true;
}
return false;
},
IsIdentity2 : function()
{
if (this.sx == 1.0 &&
this.shx == 0.0 &&
this.shy == 0.0 &&
this.sy == 1.0)
{
return true;
}
return false;
}
};
function CMatrixL()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
}
CMatrixL.prototype =
{
CreateDublicate : function()
{
var m = new CMatrixL();
m.sx = this.sx;
m.shx = this.shx;
m.shy = this.shy;
m.sy = this.sy;
m.tx = this.tx;
m.ty = this.ty;
return m;
},
Reset : function()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
},
TransformPointX : function(x,y)
{
return x * this.sx + y * this.shx + this.tx;
},
TransformPointY : function(x,y)
{
return x * this.shy + y * this.sy + this.ty;
}
};
function CGlobalMatrixTransformer()
{
this.TranslateAppend = function(m, _tx, _ty)
{
m.tx += _tx;
m.ty += _ty;
}
this.ScaleAppend = function(m, _sx, _sy)
{
m.sx *= _sx;
m.shx *= _sx;
m.shy *= _sy;
m.sy *= _sy;
m.tx *= _sx;
m.ty *= _sy;
}
this.RotateRadAppend = function(m, _rad)
{
var _sx = Math.cos(_rad);
var _shx = Math.sin(_rad);
var _shy = -Math.sin(_rad);
var _sy = Math.cos(_rad);
var t0 = m.sx * _sx + m.shy * _shx;
var t2 = m.shx * _sx + m.sy * _shx;
var t4 = m.tx * _sx + m.ty * _shx;
m.shy = m.sx * _shy + m.shy * _sy;
m.sy = m.shx * _shy + m.sy * _sy;
m.ty = m.tx * _shy + m.ty * _sy;
m.sx = t0;
m.shx = t2;
m.tx = t4;
}
this.MultiplyAppend = function(m1, m2)
{
var t0 = m1.sx * m2.sx + m1.shy * m2.shx;
var t2 = m1.shx * m2.sx + m1.sy * m2.shx;
var t4 = m1.tx * m2.sx + m1.ty * m2.shx + m2.tx;
m1.shy = m1.sx * m2.shy + m1.shy * m2.sy;
m1.sy = m1.shx * m2.shy + m1.sy * m2.sy;
m1.ty = m1.tx * m2.shy + m1.ty * m2.sy + m2.ty;
m1.sx = t0;
m1.shx = t2;
m1.tx = t4;
}
this.Invert = function(m)
{
var newM = m.CreateDublicate();
var det = newM.sx * newM.sy - newM.shy * newM.shx;
if (0.0001 > Math.abs(det))
return newM;
var d = 1 / det;
var t0 = newM.sy * d;
newM.sy = newM.sx * d;
newM.shy = -newM.shy * d;
newM.shx = -newM.shx * d;
var t4 = -newM.tx * t0 - newM.ty * newM.shx;
newM.ty = -newM.tx * newM.shy - newM.ty * newM.sy;
newM.sx = t0;
newM.tx = t4;
return newM;
}
this.MultiplyAppendInvert = function(m1, m2)
{
var m = this.Invert(m2);
this.MultiplyAppend(m1, m);
}
this.MultiplyPrepend = function(m1, m2)
{
var m = new CMatrixL();
m.sx = m2.sx;
m.shx = m2.shx;
m.shy = m2.shy;
m.sy = m2.sy;
m.tx = m2.tx;
m.ty = m2.ty;
this.MultiplyAppend(m, m1);
m1.sx = m.sx;
m1.shx = m.shx;
m1.shy = m.shy;
m1.sy = m.sy;
m1.tx = m.tx;
m1.ty = m.ty;
}
this.CreateDublicateM = function(matrix)
{
var m = new CMatrixL();
m.sx = matrix.sx;
m.shx = matrix.shx;
m.shy = matrix.shy;
m.sy = matrix.sy;
m.tx = matrix.tx;
m.ty = matrix.ty;
}
this.IsIdentity = function(m)
{
if (m.sx == 1.0 &&
m.shx == 0.0 &&
m.shy == 0.0 &&
m.sy == 1.0 &&
m.tx == 0.0 &&
m.ty == 0.0)
{
return true;
}
return false;
}
this.IsIdentity2 = function(m)
{
if (m.sx == 1.0 &&
m.shx == 0.0 &&
m.shy == 0.0 &&
m.sy == 1.0)
{
return true;
}
return false;
}
}
var global_MatrixTransformer = new CGlobalMatrixTransformer();
function CGraphics()
{
this.m_oContext = null;
this.m_dWidthMM = 0;
this.m_dHeightMM = 0;
this.m_lWidthPix = 0;
this.m_lHeightPix = 0;
this.m_dDpiX = 96.0;
this.m_dDpiY = 96.0;
this.m_bIsBreak = false;
this.textBB_l = 10000;
this.textBB_t = 10000;
this.textBB_r = -10000;
this.textBB_b = -10000;
this.m_oPen = new CPen();
this.m_oBrush = new CBrush();
this.m_oAutoShapesTrack = null;
this.m_oFontManager = null;
this.m_bIsFillTextCanvasColor = 0;
this.m_oCoordTransform = new CMatrixL();
this.m_oBaseTransform = new CMatrixL();
this.m_oTransform = new CMatrixL();
this.m_oFullTransform = new CMatrixL();
this.m_oInvertFullTransform = new CMatrixL();
this.ArrayPoints = null;
this.m_oCurFont = null;
// RFonts
this.m_oTextPr = null;
this.m_oLastFont = new CFontSetup();
this.m_bIntegerGrid = true;
this.ClipManager = new CClipManager();
this.ClipManager.BaseObject = this;
this.TextureFillTransformScaleX = 1;
this.TextureFillTransformScaleY = 1;
this.IsThumbnail = false;
this.GrState = new CGrState();
this.GrState.Parent = this;
this.globalAlpha = 1;
this.TextClipRect = null;
this.IsClipContext = false;
this.ClearMode = false;
this.IsUseFonts2 = false;
this.m_oFontManager2 = null;
this.m_oLastFont2 = null;
this.ClearMode = false;
this.IsRetina = false;
}
CGraphics.prototype =
{
init : function(context,width_px,height_px,width_mm,height_mm)
{
this.m_oContext = context;
this.m_lHeightPix = height_px;
this.m_lWidthPix = width_px;
this.m_dWidthMM = width_mm;
this.m_dHeightMM = height_mm;
this.m_dDpiX = 25.4 * this.m_lWidthPix / this.m_dWidthMM;
this.m_dDpiY = 25.4 * this.m_lHeightPix / this.m_dHeightMM;
this.m_oCoordTransform.sx = this.m_dDpiX / 25.4;
this.m_oCoordTransform.sy = this.m_dDpiY / 25.4;
this.TextureFillTransformScaleX = 1 / this.m_oCoordTransform.sx;
this.TextureFillTransformScaleY = 1 / this.m_oCoordTransform.sy;
if (this.IsThumbnail)
{
this.TextureFillTransformScaleX *= (width_px / (width_mm * g_dKoef_mm_to_pix));
this.TextureFillTransformScaleY *= (height_px / (height_mm * g_dKoef_mm_to_pix))
}
/*
if (true == this.m_oContext.mozImageSmoothingEnabled)
this.m_oContext.mozImageSmoothingEnabled = false;
*/
this.m_oLastFont.Clear();
this.m_oContext.save();
},
EndDraw : function()
{
},
put_GlobalAlpha : function(enable, alpha)
{
if (false === enable)
{
this.globalAlpha = 1;
this.m_oContext.globalAlpha = 1;
}
else
{
this.globalAlpha = alpha;
this.m_oContext.globalAlpha = alpha;
}
},
// pen methods
p_color : function(r,g,b,a)
{
var _c = this.m_oPen.Color;
_c.R = r;
_c.G = g;
_c.B = b;
_c.A = a;
this.m_oContext.strokeStyle = "rgba(" + _c.R + "," + _c.G + "," + _c.B + "," + (_c.A / 255) + ")";
},
p_width : function(w)
{
this.m_oPen.LineWidth = w / 1000;
if (!this.m_bIntegerGrid)
{
if (0 != this.m_oPen.LineWidth)
{
this.m_oContext.lineWidth = this.m_oPen.LineWidth;
}
else
{
var _x1 = this.m_oFullTransform.TransformPointX(0, 0);
var _y1 = this.m_oFullTransform.TransformPointY(0, 0);
var _x2 = this.m_oFullTransform.TransformPointX(1, 1);
var _y2 = this.m_oFullTransform.TransformPointY(1, 1);
var _koef = Math.sqrt(((_x2 - _x1)*(_x2 - _x1) + (_y2 - _y1)*(_y2 - _y1)) / 2);
this.m_oContext.lineWidth = 1 / _koef;
}
}
else
{
if (0 != this.m_oPen.LineWidth)
{
var _m = this.m_oFullTransform;
var x = _m.sx + _m.shx;
var y = _m.sy + _m.shy;
var koef = Math.sqrt((x * x + y * y) / 2);
this.m_oContext.lineWidth = this.m_oPen.LineWidth * koef;
}
else
{
this.m_oContext.lineWidth = 1;
}
}
},
// brush methods
b_color1 : function(r,g,b,a)
{
var _c = this.m_oBrush.Color1;
_c.R = r;
_c.G = g;
_c.B = b;
_c.A = a;
this.m_oContext.fillStyle = "rgba(" + _c.R + "," + _c.G + "," + _c.B + "," + (_c.A / 255) + ")";
this.m_bIsFillTextCanvasColor = 0;
},
b_color2 : function(r,g,b,a)
{
var _c = this.m_oBrush.Color2;
_c.R = r;
_c.G = g;
_c.B = b;
_c.A = a;
},
transform : function(sx,shy,shx,sy,tx,ty)
{
var _t = this.m_oTransform;
_t.sx = sx;
_t.shx = shx;
_t.shy = shy;
_t.sy = sy;
_t.tx = tx;
_t.ty = ty;
this.CalculateFullTransform();
if (false === this.m_bIntegerGrid)
{
var _ft = this.m_oFullTransform;
this.m_oContext.setTransform(_ft.sx,_ft.shy,_ft.shx,_ft.sy,_ft.tx,_ft.ty);
}
if (null != this.m_oFontManager)
{
this.m_oFontManager.SetTextMatrix(_t.sx,_t.shy,_t.shx,_t.sy,_t.tx,_t.ty);
}
},
CalculateFullTransform : function(isInvertNeed)
{
var _ft = this.m_oFullTransform;
var _t = this.m_oTransform;
_ft.sx = _t.sx;
_ft.shx = _t.shx;
_ft.shy = _t.shy;
_ft.sy = _t.sy;
_ft.tx = _t.tx;
_ft.ty = _t.ty;
global_MatrixTransformer.MultiplyAppend(_ft, this.m_oCoordTransform);
var _it = this.m_oInvertFullTransform;
_it.sx = _ft.sx;
_it.shx = _ft.shx;
_it.shy = _ft.shy;
_it.sy = _ft.sy;
_it.tx = _ft.tx;
_it.ty = _ft.ty;
if (false !== isInvertNeed)
{
global_MatrixTransformer.MultiplyAppendInvert(_it, _t);
}
},
// path commands
_s : function()
{
this.m_oContext.beginPath();
},
_e : function()
{
this.m_oContext.beginPath();
},
_z : function()
{
this.m_oContext.closePath();
},
_m : function(x,y)
{
if (false === this.m_bIntegerGrid)
{
this.m_oContext.moveTo(x,y);
if (this.ArrayPoints != null)
this.ArrayPoints[this.ArrayPoints.length] = {x: x, y: y};
}
else
{
var _x = (this.m_oFullTransform.TransformPointX(x,y)) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(x,y)) >> 0;
this.m_oContext.moveTo(_x + 0.5,_y + 0.5);
}
},
_l : function(x,y)
{
if (false === this.m_bIntegerGrid)
{
this.m_oContext.lineTo(x,y);
if (this.ArrayPoints != null)
this.ArrayPoints[this.ArrayPoints.length] = {x: x, y: y};
}
else
{
var _x = (this.m_oFullTransform.TransformPointX(x,y)) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(x,y)) >> 0;
this.m_oContext.lineTo(_x + 0.5,_y + 0.5);
}
},
_c : function(x1,y1,x2,y2,x3,y3)
{
if (false === this.m_bIntegerGrid)
{
this.m_oContext.bezierCurveTo(x1,y1,x2,y2,x3,y3);
if (this.ArrayPoints != null)
{
this.ArrayPoints[this.ArrayPoints.length] = {x: x1, y: y1};
this.ArrayPoints[this.ArrayPoints.length] = {x: x2, y: y2};
this.ArrayPoints[this.ArrayPoints.length] = {x: x3, y: y3};
}
}
else
{
var _x1 = (this.m_oFullTransform.TransformPointX(x1,y1)) >> 0;
var _y1 = (this.m_oFullTransform.TransformPointY(x1,y1)) >> 0;
var _x2 = (this.m_oFullTransform.TransformPointX(x2,y2)) >> 0;
var _y2 = (this.m_oFullTransform.TransformPointY(x2,y2)) >> 0;
var _x3 = (this.m_oFullTransform.TransformPointX(x3,y3)) >> 0;
var _y3 = (this.m_oFullTransform.TransformPointY(x3,y3)) >> 0;
this.m_oContext.bezierCurveTo(_x1 + 0.5,_y1 + 0.5,_x2 + 0.5,_y2 + 0.5,_x3 + 0.5,_y3 + 0.5);
}
},
_c2 : function(x1,y1,x2,y2)
{
if (false === this.m_bIntegerGrid)
{
this.m_oContext.quadraticCurveTo(x1,y1,x2,y2);
if (this.ArrayPoints != null)
{
this.ArrayPoints[this.ArrayPoints.length] = {x: x1, y: y1};
this.ArrayPoints[this.ArrayPoints.length] = {x: x2, y: y2};
}
}
else
{
var _x1 = (this.m_oFullTransform.TransformPointX(x1,y1)) >> 0;
var _y1 = (this.m_oFullTransform.TransformPointY(x1,y1)) >> 0;
var _x2 = (this.m_oFullTransform.TransformPointX(x2,y2)) >> 0;
var _y2 = (this.m_oFullTransform.TransformPointY(x2,y2)) >> 0;
this.m_oContext.quadraticCurveTo(_x1 + 0.5,_y1 + 0.5,_x2 + 0.5,_y2 + 0.5);
}
},
ds : function()
{
this.m_oContext.stroke();
},
df : function()
{
this.m_oContext.fill();
},
// canvas state
save : function()
{
this.m_oContext.save();
},
restore : function()
{
this.m_oContext.restore();
},
clip : function()
{
this.m_oContext.clip();
},
reset : function()
{
this.m_oTransform.Reset();
this.CalculateFullTransform(false);
this.m_oContext.setTransform(this.m_oCoordTransform.sx,0,0,this.m_oCoordTransform.sy,0, 0);
},
transform3 : function(m, isNeedInvert)
{
var _t = this.m_oTransform;
_t.sx = m.sx;
_t.shx = m.shx;
_t.shy = m.shy;
_t.sy = m.sy;
_t.tx = m.tx;
_t.ty = m.ty;
this.CalculateFullTransform(isNeedInvert);
var _ft = this.m_oFullTransform;
this.m_oContext.setTransform(_ft.sx,_ft.shy,_ft.shx,_ft.sy,_ft.tx,_ft.ty);
// теперь трансформ выставляется ТОЛЬКО при загрузке шрифта. Здесь другого быть и не может
/*
if (null != this.m_oFontManager && false !== isNeedInvert)
{
this.m_oFontManager.SetTextMatrix(this.m_oTransform.sx,this.m_oTransform.shy,this.m_oTransform.shx,
this.m_oTransform.sy,this.m_oTransform.tx,this.m_oTransform.ty);
}
*/
},
CheckUseFonts2 : function(_transform)
{
if (!global_MatrixTransformer.IsIdentity2(_transform))
{
if (window.g_fontManager2 == null)
{
window.g_fontManager2 = new CFontManager();
window.g_fontManager2.Initialize(true);
}
this.m_oFontManager2 = window.g_fontManager2;
if (null == this.m_oLastFont2)
this.m_oLastFont2 = new CFontSetup();
this.IsUseFonts2 = true;
}
},
UncheckUseFonts2 : function()
{
this.IsUseFonts2 = false;
},
FreeFont : function()
{
// это чтобы не сбросился кэш при отрисовке следующего шейпа
this.m_oFontManager.m_pFont = null;
},
// images
drawImage2 : function(img,x,y,w,h,alpha,srcRect)
{
var isA = (undefined !== alpha && null != alpha && 255 != alpha);
var _oldGA = 0;
if (isA)
{
_oldGA = this.m_oContext.globalAlpha;
this.m_oContext.globalAlpha = alpha / 255;
}
if (false === this.m_bIntegerGrid)
{
if (!srcRect)
{
// тут нужно проверить, можно ли нарисовать точно. т.е. может картинка ровно такая, какая нужна.
if (!global_MatrixTransformer.IsIdentity2(this.m_oTransform))
{
this.m_oContext.drawImage(img,x,y,w,h);
}
else
{
var xx = this.m_oFullTransform.TransformPointX(x, y);
var yy = this.m_oFullTransform.TransformPointY(x, y);
var rr = this.m_oFullTransform.TransformPointX(x + w, y + h);
var bb = this.m_oFullTransform.TransformPointY(x + w, y + h);
var ww = rr - xx;
var hh = bb - yy;
if (Math.abs(img.width - ww) < 2 && Math.abs(img.height - hh) < 2)
{
// рисуем точно
this.m_oContext.setTransform(1, 0, 0, 1, 0, 0);
this.m_oContext.drawImage(img, xx >> 0, yy >> 0);
var _ft = this.m_oFullTransform;
this.m_oContext.setTransform(_ft.sx,_ft.shy,_ft.shx,_ft.sy,_ft.tx,_ft.ty);
}
else
{
this.m_oContext.drawImage(img,x,y,w,h);
}
}
}
else
{
var _w = img.width;
var _h = img.height;
if (_w > 0 && _h > 0)
{
var __w = w;
var __h = h;
var _delW = Math.max(0, -srcRect.l) + Math.max(0, srcRect.r - 100) + 100;
var _delH = Math.max(0, -srcRect.t) + Math.max(0, srcRect.b - 100) + 100;
var _sx = 0;
if (srcRect.l > 0 && srcRect.l < 100)
_sx = Math.min((_w * srcRect.l / 100) >> 0, _w - 1);
else if (srcRect.l < 0)
{
var _off = ((-srcRect.l / _delW) * __w);
x += _off;
w -= _off;
}
var _sy = 0;
if (srcRect.t > 0 && srcRect.t < 100)
_sy = Math.min((_h * srcRect.t / 100) >> 0, _h - 1);
else if (srcRect.t < 0)
{
var _off = ((-srcRect.t / _delH) * __h);
y += _off;
h -= _off;
}
var _sr = _w;
if (srcRect.r > 0 && srcRect.r < 100)
_sr = Math.max(Math.min((_w * srcRect.r / 100) >> 0, _w - 1), _sx);
else if (srcRect.r > 100)
{
var _off = ((srcRect.r - 100) / _delW) * __w;
w -= _off;
}
var _sb = _h;
if (srcRect.b > 0 && srcRect.b < 100)
_sb = Math.max(Math.min((_h * srcRect.b / 100) >> 0, _h - 1), _sy);
else if (srcRect.b > 100)
{
var _off = ((srcRect.b - 100) / _delH) * __h;
h -= _off;
}
this.m_oContext.drawImage(img,_sx,_sy,_sr-_sx,_sb-_sy,x,y,w,h);
}
else
{
this.m_oContext.drawImage(img,x,y,w,h);
}
}
}
else
{
var _x1 = (this.m_oFullTransform.TransformPointX(x,y)) >> 0;
var _y1 = (this.m_oFullTransform.TransformPointY(x,y)) >> 0;
var _x2 = (this.m_oFullTransform.TransformPointX(x+w,y+h)) >> 0;
var _y2 = (this.m_oFullTransform.TransformPointY(x+w,y+h)) >> 0;
x = _x1;
y = _y1;
w = _x2 - _x1;
h = _y2 - _y1;
if (!srcRect)
{
// тут нужно проверить, можно ли нарисовать точно. т.е. может картинка ровно такая, какая нужна.
if (!global_MatrixTransformer.IsIdentity2(this.m_oTransform))
{
this.m_oContext.drawImage(img,_x1,_y1,w,h);
}
else
{
if (Math.abs(img.width - w) < 2 && Math.abs(img.height - h) < 2)
{
// рисуем точно
this.m_oContext.drawImage(img, x, y);
}
else
{
this.m_oContext.drawImage(img,_x1,_y1,w,h);
}
}
}
else
{
var _w = img.width;
var _h = img.height;
if (_w > 0 && _h > 0)
{
var __w = w;
var __h = h;
var _delW = Math.max(0, -srcRect.l) + Math.max(0, srcRect.r - 100) + 100;
var _delH = Math.max(0, -srcRect.t) + Math.max(0, srcRect.b - 100) + 100;
var _sx = 0;
if (srcRect.l > 0 && srcRect.l < 100)
_sx = Math.min((_w * srcRect.l / 100) >> 0, _w - 1);
else if (srcRect.l < 0)
{
var _off = ((-srcRect.l / _delW) * __w);
x += _off;
w -= _off;
}
var _sy = 0;
if (srcRect.t > 0 && srcRect.t < 100)
_sy = Math.min((_h * srcRect.t / 100) >> 0, _h - 1);
else if (srcRect.t < 0)
{
var _off = ((-srcRect.t / _delH) * __h);
y += _off;
h -= _off;
}
var _sr = _w;
if (srcRect.r > 0 && srcRect.r < 100)
_sr = Math.max(Math.min((_w * srcRect.r / 100) >> 0, _w - 1), _sx);
else if (srcRect.r > 100)
{
var _off = ((srcRect.r - 100) / _delW) * __w;
w -= _off;
}
var _sb = _h;
if (srcRect.b > 0 && srcRect.b < 100)
_sb = Math.max(Math.min((_h * srcRect.b / 100) >> 0, _h - 1), _sy);
else if (srcRect.b > 100)
{
var _off = ((srcRect.b - 100) / _delH) * __h;
h -= _off;
}
this.m_oContext.drawImage(img,_sx,_sy,_sr-_sx,_sb-_sy,x,y,w,h);
}
else
{
this.m_oContext.drawImage(img,x,y,w,h);
}
}
}
if (isA)
{
this.m_oContext.globalAlpha = _oldGA;
}
},
drawImage : function(img,x,y,w,h,alpha,srcRect,nativeImage)
{
if (nativeImage)
{
this.drawImage2(nativeImage,x,y,w,h,alpha,srcRect);
return;
}
var editor = window["Asc"]["editor"];
var _img = editor.ImageLoader.map_image_index[img];
if (_img != undefined && _img.Status == ImageLoadStatus.Loading)
{
// TODO: IMAGE_LOADING
}
else if (_img != undefined && _img.Image != null)
{
this.drawImage2(_img.Image,x,y,w,h,alpha,srcRect);
}
else
{
var _x = x;
var _y = y;
var _r = x+w;
var _b = y+h;
if (this.m_bIntegerGrid)
{
_x = this.m_oFullTransform.TransformPointX(x,y);
_y = this.m_oFullTransform.TransformPointY(x,y);
_r = this.m_oFullTransform.TransformPointX(x+w,y+h);
_b = this.m_oFullTransform.TransformPointY(x+w,y+h);
}
var ctx = this.m_oContext;
var old_p = ctx.lineWidth;
ctx.beginPath();
ctx.moveTo(_x,_y);
ctx.lineTo(_r,_b);
ctx.moveTo(_r,_y);
ctx.lineTo(_x,_b);
ctx.strokeStyle = "#FF0000";
ctx.stroke();
ctx.beginPath();
ctx.moveTo(_x,_y);
ctx.lineTo(_r,_y);
ctx.lineTo(_r,_b);
ctx.lineTo(_x,_b);
ctx.closePath();
ctx.lineWidth = 1;
ctx.strokeStyle = "#000000";
ctx.stroke();
ctx.beginPath();
ctx.lineWidth = old_p;
ctx.strokeStyle = "rgba(" + this.m_oPen.Color.R + "," + this.m_oPen.Color.G + "," +
this.m_oPen.Color.B + "," + (this.m_oPen.Color.A / 255) + ")";
}
},
// text
GetFont : function()
{
return this.m_oCurFont;
},
font : function(font_id,font_size,matrix)
{
window.g_font_infos[window.g_map_font_index[font_id]].LoadFont(editor.FontLoader, this.m_oFontManager, font_size, 0, this.m_dDpiX, this.m_dDpiY, /*matrix*/undefined);
},
SetFont : function(font)
{
if (null == font)
return;
this.m_oCurFont =
{
FontFamily :
{
Index : font.FontFamily.Index,
Name : font.FontFamily.Name
},
FontSize : font.FontSize,
Bold : font.Bold,
Italic : font.Italic
};
if (-1 == font.FontFamily.Index || undefined === font.FontFamily.Index || null == font.FontFamily.Index)
font.FontFamily.Index = window.g_map_font_index[font.FontFamily.Name];
if (font.FontFamily.Index == undefined || font.FontFamily.Index == -1)
return;
var bItalic = true === font.Italic;
var bBold = true === font.Bold;
var oFontStyle = FontStyle.FontStyleRegular;
if ( !bItalic && bBold )
oFontStyle = FontStyle.FontStyleBold;
else if ( bItalic && !bBold )
oFontStyle = FontStyle.FontStyleItalic;
else if ( bItalic && bBold )
oFontStyle = FontStyle.FontStyleBoldItalic;
var _last_font = this.IsUseFonts2 ? this.m_oLastFont2 : this.m_oLastFont;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
_last_font.SetUpIndex = font.FontFamily.Index;
_last_font.SetUpSize = font.FontSize;
_last_font.SetUpStyle = oFontStyle;
window.g_font_infos[font.FontFamily.Index].LoadFont(window.g_font_loader, _font_manager, font.FontSize, oFontStyle, this.m_dDpiX, this.m_dDpiY, this.m_oTransform);
var _mD = _last_font.SetUpMatrix;
var _mS = this.m_oTransform;
_mD.sx = _mS.sx;
_mD.sy = _mS.sy;
_mD.shx = _mS.shx;
_mD.shy = _mS.shy;
_mD.tx = _mS.tx;
_mD.ty = _mS.ty;
//_font_manager.SetTextMatrix(this.m_oTransform.sx,this.m_oTransform.shy,this.m_oTransform.shx,
// this.m_oTransform.sy,this.m_oTransform.tx,this.m_oTransform.ty);
},
SetTextPr : function(textPr, theme)
{
this.m_oTextPr = textPr.Copy();
this.theme = theme;
var FontScheme = theme.themeElements.fontScheme;
this.m_oTextPr.RFonts.Ascii = {Name: FontScheme.checkFont(this.m_oTextPr.RFonts.Ascii.Name), Index: -1};
this.m_oTextPr.RFonts.EastAsia = {Name: FontScheme.checkFont(this.m_oTextPr.RFonts.EastAsia.Name), Index: -1};
this.m_oTextPr.RFonts.HAnsi = {Name: FontScheme.checkFont(this.m_oTextPr.RFonts.HAnsi.Name), Index: -1};
this.m_oTextPr.RFonts.CS = {Name: FontScheme.checkFont(this.m_oTextPr.RFonts.CS.Name), Index: -1};
},
SetFontSlot : function(slot, fontSizeKoef)
{
var _rfonts = this.m_oTextPr.RFonts;
var _lastFont = this.IsUseFonts2 ? this.m_oLastFont2 : this.m_oLastFont;
switch (slot)
{
case fontslot_ASCII:
{
_lastFont.Name = _rfonts.Ascii.Name;
_lastFont.Index = _rfonts.Ascii.Index;
if (_lastFont.Index == -1 || _lastFont.Index === undefined)
{
_lastFont.Index = window.g_map_font_index[_lastFont.Name];
}
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
case fontslot_CS:
{
_lastFont.Name = _rfonts.CS.Name;
_lastFont.Index = _rfonts.CS.Index;
if (_lastFont.Index == -1 || _lastFont.Index === undefined)
{
_lastFont.Index = window.g_map_font_index[_lastFont.Name];
}
_lastFont.Size = this.m_oTextPr.FontSizeCS;
_lastFont.Bold = this.m_oTextPr.BoldCS;
_lastFont.Italic = this.m_oTextPr.ItalicCS;
break;
}
case fontslot_EastAsia:
{
_lastFont.Name = _rfonts.EastAsia.Name;
_lastFont.Index = _rfonts.EastAsia.Index;
if (_lastFont.Index == -1 || _lastFont.Index === undefined)
{
_lastFont.Index = window.g_map_font_index[_lastFont.Name];
}
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
case fontslot_HAnsi:
default:
{
_lastFont.Name = _rfonts.HAnsi.Name;
_lastFont.Index = _rfonts.HAnsi.Index;
if (_lastFont.Index == -1 || _lastFont.Index === undefined)
{
_lastFont.Index = window.g_map_font_index[_lastFont.Name];
}
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
}
if (undefined !== fontSizeKoef)
_lastFont.Size *= fontSizeKoef;
var _style = 0;
if (_lastFont.Italic)
_style += 2;
if (_lastFont.Bold)
_style += 1;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
if (_lastFont.Index != _lastFont.SetUpIndex || _lastFont.Size != _lastFont.SetUpSize || _style != _lastFont.SetUpStyle)
{
_lastFont.SetUpIndex = _lastFont.Index;
_lastFont.SetUpSize = _lastFont.Size;
_lastFont.SetUpStyle = _style;
window.g_font_infos[_lastFont.SetUpIndex].LoadFont(window.g_font_loader, _font_manager, _lastFont.SetUpSize, _lastFont.SetUpStyle, this.m_dDpiX, this.m_dDpiY, this.m_oTransform);
var _mD = _lastFont.SetUpMatrix;
var _mS = this.m_oTransform;
_mD.sx = _mS.sx;
_mD.sy = _mS.sy;
_mD.shx = _mS.shx;
_mD.shy = _mS.shy;
_mD.tx = _mS.tx;
_mD.ty = _mS.ty;
}
else
{
var _mD = _lastFont.SetUpMatrix;
var _mS = this.m_oTransform;
if (_mD.sx != _mS.sx || _mD.sy != _mS.sy || _mD.shx != _mS.shx || _mD.shy != _mS.shy || _mD.tx != _mS.tx || _mD.ty != _mS.ty)
{
_mD.sx = _mS.sx;
_mD.sy = _mS.sy;
_mD.shx = _mS.shx;
_mD.shy = _mS.shy;
_mD.tx = _mS.tx;
_mD.ty = _mS.ty;
_font_manager.SetTextMatrix(_mD.sx,_mD.shy,_mD.shx,_mD.sy,_mD.tx,_mD.ty);
}
}
//_font_manager.SetTextMatrix(this.m_oTransform.sx,this.m_oTransform.shy,this.m_oTransform.shx,
// this.m_oTransform.sy,this.m_oTransform.tx,this.m_oTransform.ty);
},
GetTextPr : function()
{
return this.m_oTextPr;
},
FillText : function(x,y,text)
{
// убыстеренный вариант. здесь везде заточка на то, что приходит одна буква
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString2C(text,_x,_y);
}
catch(err)
{
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(1,0,0,1,0,0);
}
var pGlyph = _font_manager.m_oGlyphString.m_pGlyphsBuffer[0];
if (null == pGlyph)
return;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyph(pGlyph);
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
t : function(text,x,y)
{
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString2(text,_x,_y);
}
catch(err)
{
}
this.m_oContext.setTransform(1,0,0,1,0,0);
while (true)
{
var pGlyph = _font_manager.GetNextChar2();
if (null == pGlyph)
break;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyph(pGlyph);
}
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
FillText2 : function(x,y,text,cropX,cropW)
{
// убыстеренный вариант. здесь везде заточка на то, что приходит одна буква
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString2C(text,_x,_y);
}
catch(err)
{
}
this.m_oContext.setTransform(1,0,0,1,0,0);
var pGlyph = _font_manager.m_oGlyphString.m_pGlyphsBuffer[0];
if (null == pGlyph)
return;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyphC(pGlyph,cropX,cropW);
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
t2 : function(text,x,y,cropX,cropW)
{
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString2(text,_x,_y);
}
catch(err)
{
}
this.m_oContext.setTransform(1,0,0,1,0,0);
while (true)
{
var pGlyph = _font_manager.GetNextChar2();
if (null == pGlyph)
break;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyphC(pGlyph,cropX,cropW);
}
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
FillTextCode : function(x,y,lUnicode)
{
// убыстеренный вариант. здесь везде заточка на то, что приходит одна буква
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString4C(lUnicode,_x,_y);
}
catch(err)
{
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(1,0,0,1,0,0);
}
var pGlyph = _font_manager.m_oGlyphString.m_pGlyphsBuffer[0];
if (null == pGlyph)
return;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyph(pGlyph);
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
tg : function(text,x,y)
{
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString3C(text,_x,_y);
}
catch(err)
{
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(1,0,0,1,0,0);
}
var pGlyph = _font_manager.m_oGlyphString.m_pGlyphsBuffer[0];
if (null == pGlyph)
return;
if (null != pGlyph.oBitmap)
{
var _a = this.m_oBrush.Color1.A;
if (255 != _a)
this.m_oContext.globalAlpha = _a / 255;
this.private_FillGlyph(pGlyph);
if (255 != _a)
this.m_oContext.globalAlpha = 1.0;
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
charspace : function(space)
{
},
// private methods
private_FillGlyph : function(pGlyph)
{
// new scheme
var nW = pGlyph.oBitmap.nWidth;
var nH = pGlyph.oBitmap.nHeight;
if (0 == nW || 0 == nH)
return;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
var nX = (_font_manager.m_oGlyphString.m_fX + pGlyph.fX + pGlyph.oBitmap.nX) >> 0;
var nY = (_font_manager.m_oGlyphString.m_fY + pGlyph.fY - pGlyph.oBitmap.nY) >> 0;
pGlyph.oBitmap.oGlyphData.checkColor(this.m_oBrush.Color1.R,this.m_oBrush.Color1.G,this.m_oBrush.Color1.B,nW,nH);
if (null == this.TextClipRect)
pGlyph.oBitmap.draw(this.m_oContext, nX, nY, this.TextClipRect);
else
pGlyph.oBitmap.drawCropInRect(this.m_oContext, nX, nY, this.TextClipRect);
},
private_FillGlyphC : function(pGlyph,cropX,cropW)
{
// new scheme
var nW = pGlyph.oBitmap.nWidth;
var nH = pGlyph.oBitmap.nHeight;
if (0 == nW || 0 == nH)
return;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
var nX = (_font_manager.m_oGlyphString.m_fX + pGlyph.fX + pGlyph.oBitmap.nX) >> 0;
var nY = (_font_manager.m_oGlyphString.m_fY + pGlyph.fY - pGlyph.oBitmap.nY) >> 0;
var d_koef = this.m_dDpiX / 25.4;
var cX = Math.max((cropX * d_koef) >> 0, 0);
var cW = Math.min((cropW * d_koef) >> 0, nW);
if (cW <= 0)
cW = 1;
pGlyph.oBitmap.oGlyphData.checkColor(this.m_oBrush.Color1.R,this.m_oBrush.Color1.G,this.m_oBrush.Color1.B,nW,nH);
pGlyph.oBitmap.drawCrop(this.m_oContext, nX, nY, cW, nH, cX);
},
private_FillGlyph2 : function(pGlyph)
{
var i = 0;
var j = 0;
var nW = pGlyph.oBitmap.nWidth;
var nH = pGlyph.oBitmap.nHeight;
if (0 == nW || 0 == nH)
return;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
var nX = (_font_manager.m_oGlyphString.m_fX + pGlyph.fX + pGlyph.oBitmap.nX) >> 0;
var nY = (_font_manager.m_oGlyphString.m_fY + pGlyph.fY - pGlyph.oBitmap.nY) >> 0;
var imageData = this.m_oContext.getImageData(nX,nY,nW,nH);
var pPixels = imageData.data;
var _r = this.m_oBrush.Color1.R;
var _g = this.m_oBrush.Color1.G;
var _b = this.m_oBrush.Color1.B;
for (; j < nH; ++j)
{
var indx = 4 * j * nW;
for (i = 0; i < nW; ++i)
{
var weight = pGlyph.oBitmap.pData[j * pGlyph.oBitmap.nWidth + i];
if (255 == weight)
{
pPixels[indx] = _r;
pPixels[indx + 1] = _g;
pPixels[indx + 2] = _b;
pPixels[indx + 3] = 255;
}
else
{
var r = pPixels[indx];
var g = pPixels[indx + 1];
var b = pPixels[indx + 2];
var a = pPixels[indx + 3];
pPixels[indx] = ((_r - r) * weight + (r << 8)) >>> 8;
pPixels[indx + 1] = ((_g - g) * weight + (g << 8)) >>> 8;
pPixels[indx + 2] = ((_b - b) * weight + (b << 8)) >>> 8;
pPixels[indx + 3] = (weight + a) - ((weight * a + 256) >>> 8);
}
indx += 4;
}
}
this.m_oContext.putImageData(imageData,nX,nY);
},
SetIntegerGrid : function(param)
{
if (true == param)
{
this.m_bIntegerGrid = true;
this.m_oContext.setTransform(1,0,0,1,0,0);
}
else
{
this.m_bIntegerGrid = false;
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
GetIntegerGrid : function()
{
return this.m_bIntegerGrid;
},
DrawHeaderEdit : function(yPos, lock_type)
{
var _y = this.m_oFullTransform.TransformPointY(0,yPos);
_y = (_y >> 0) + 0.5;
var _x = 0;
var _wmax = this.m_lWidthPix;
var _w1 = 6;
var _w2 = 3;
var ctx = this.m_oContext;
switch (lock_type)
{
case locktype_None:
case locktype_Mine:
{
this.p_color(155, 187, 277, 255);
ctx.lineWidth = 2;
break;
}
case locktype_Other:
case locktype_Other2:
{
this.p_color(238, 53, 37, 255);
ctx.lineWidth = 1;
_w1 = 2;
_w2 = 1;
break;
}
default:
{
this.p_color(155, 187, 277, 255);
ctx.lineWidth = 2;
_w1 = 2;
_w2 = 1;
}
}
if (true === this.m_bIntegerGrid)
{
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y);
_x+=_w1;
ctx.lineTo(_x,_y);
_x+=_w2;
}
this.ds();
}
else
{
this.SetIntegerGrid(true);
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y);
_x+=_w1;
ctx.lineTo(_x,_y);
_x+=_w2;
}
this.ds();
this.SetIntegerGrid(false);
}
},
DrawFooterEdit : function(yPos, lock_type)
{
var _y = this.m_oFullTransform.TransformPointY(0,yPos);
_y = (_y >> 0) + 0.5;
var _x = 0;
var _w1 = 6;
var _w2 = 3;
var ctx = this.m_oContext;
switch (lock_type)
{
case locktype_None:
case locktype_Mine:
{
this.p_color(155, 187, 277, 255);
ctx.lineWidth = 2;
break;
}
case locktype_Other:
case locktype_Other2:
{
this.p_color(238, 53, 37, 255);
ctx.lineWidth = 1;
_w1 = 2;
_w2 = 1;
break;
}
default:
{
this.p_color(155, 187, 277, 255);
ctx.lineWidth = 2;
_w1 = 2;
_w2 = 1;
}
}
var _wmax = this.m_lWidthPix;
if (true === this.m_bIntegerGrid)
{
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y);
_x+=_w1;
ctx.lineTo(_x,_y);
_x+=_w2;
}
this.ds();
}
else
{
this.SetIntegerGrid(true);
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y);
_x+=_w1;
ctx.lineTo(_x,_y);
_x+=_w2;
}
this.ds();
this.SetIntegerGrid(false);
}
},
DrawLockParagraph : function(lock_type, x, y1, y2)
{
if (lock_type == c_oAscLockTypes.kLockTypeNone || editor.WordControl.m_oDrawingDocument.IsLockObjectsEnable === false || editor.isViewMode)
return;
if (lock_type == c_oAscLockTypes.kLockTypeMine)
{
this.p_color(22, 156, 0, 255);
//this.p_color(155, 187, 277, 255);
}
else
this.p_color(238, 53, 37, 255);
var _x = this.m_oFullTransform.TransformPointX(x, y1) >> 0;
var _xT = this.m_oFullTransform.TransformPointX(x, y2) >> 0;
var _y1 = (this.m_oFullTransform.TransformPointY(x, y1) >> 0) + 0.5;
var _y2 = (this.m_oFullTransform.TransformPointY(x, y2) >> 0) - 1.5;
var ctx = this.m_oContext;
if (_x != _xT)
{
// значит какой-то трансформ
var dKoefMMToPx = 1 / Math.max(this.m_oCoordTransform.sx, 0.001);
this.p_width(1000 * dKoefMMToPx);
var w_dot = 2 * dKoefMMToPx;
var w_dist = 1 * dKoefMMToPx;
var w_len_indent = 3;
var _interf = editor.WordControl.m_oDrawingDocument.AutoShapesTrack;
this._s();
_interf.AddLineDash(ctx, x, y1, x, y2, w_dot, w_dist);
_interf.AddLineDash(ctx, x, y1, x + w_len_indent, y1, w_dot, w_dist);
_interf.AddLineDash(ctx, x, y2, x + w_len_indent, y2, w_dot, w_dist);
this.ds();
return;
}
var bIsInt = this.m_bIntegerGrid;
if (!bIsInt)
this.SetIntegerGrid(true);
ctx.lineWidth = 1;
var w_dot = 2;
var w_dist = 1;
var w_len_indent = (3 * this.m_oCoordTransform.sx) >> 0;
this._s();
var y_mem = _y1 - 0.5;
while (true)
{
if ((y_mem + w_dot) > _y2)
break;
ctx.moveTo(_x + 0.5,y_mem);
y_mem+=w_dot;
ctx.lineTo(_x + 0.5,y_mem);
y_mem+=w_dist;
}
var x_max = _x + w_len_indent;
var x_mem = _x;
while (true)
{
if (x_mem > x_max)
break;
ctx.moveTo(x_mem,_y1);
x_mem+=w_dot;
ctx.lineTo(x_mem,_y1);
x_mem+=w_dist;
}
x_mem = _x;
while (true)
{
if (x_mem > x_max)
break;
ctx.moveTo(x_mem,_y2);
x_mem+=w_dot;
ctx.lineTo(x_mem,_y2);
x_mem+=w_dist;
}
this.ds();
if (!bIsInt)
this.SetIntegerGrid(false);
},
DrawLockObjectRect : function(lock_type, x, y, w, h)
{
if (lock_type == c_oAscLockTypes.kLockTypeNone)
return;
if (lock_type == c_oAscLockTypes.kLockTypeMine)
{
this.p_color(22, 156, 0, 255);
//this.p_color(155, 187, 277, 255);
}
else
this.p_color(238, 53, 37, 255);
var ctx = this.m_oContext;
var _m = this.m_oTransform;
if (_m.sx != 1.0 || _m.shx != 0.0 || _m.shy != 0.0 || _m.sy != 1.0)
{
// значит какой-то трансформ
var dKoefMMToPx = 1 / Math.max(this.m_oCoordTransform.sx, 0.001);
this.p_width(1000 * dKoefMMToPx);
var w_dot = 2 * dKoefMMToPx;
var w_dist = 1 * dKoefMMToPx;
var _interf = this.m_oAutoShapesTrack;
var eps = 5 * dKoefMMToPx;
var _x = x - eps;
var _y = y - eps;
var _r = x + w + eps;
var _b = y + h + eps;
this._s();
_interf.AddRectDash(ctx, _x, _y, _r, _y, _x, _b, _r, _b, w_dot, w_dist);
this.ds();
return;
}
var bIsInt = this.m_bIntegerGrid;
if (!bIsInt)
this.SetIntegerGrid(true);
ctx.lineWidth = 1;
var w_dot = 2;
var w_dist = 2;
var eps = 5;
var _x = (this.m_oFullTransform.TransformPointX(x, y) >> 0) - eps + 0.5;
var _y = (this.m_oFullTransform.TransformPointY(x, y) >> 0) - eps + 0.5;
var _r = (this.m_oFullTransform.TransformPointX(x+w, y+h) >> 0) + eps + 0.5;
var _b = (this.m_oFullTransform.TransformPointY(x+w, y+h) >> 0) + eps + 0.5;
this._s();
for (var i = _x; i < _r; i += w_dist)
{
ctx.moveTo(i, _y);
i += w_dot;
if (i > _r)
i = _r;
ctx.lineTo(i, _y);
}
for (var i = _y; i < _b; i += w_dist)
{
ctx.moveTo(_r, i);
i += w_dot;
if (i > _b)
i = _b;
ctx.lineTo(_r, i);
}
for (var i = _r; i > _x; i -= w_dist)
{
ctx.moveTo(i, _b);
i -= w_dot;
if (i < _x)
i = _x;
ctx.lineTo(i, _b);
}
for (var i = _b; i > _y; i -= w_dist)
{
ctx.moveTo(_x, i);
i -= w_dot;
if (i < _y)
i = _y;
ctx.lineTo(_x, i);
}
this.ds();
if (!bIsInt)
this.SetIntegerGrid(false);
},
DrawEmptyTableLine : function(x1,y1,x2,y2)
{
if (!editor.isShowTableEmptyLine)
return;
var _x1 = this.m_oFullTransform.TransformPointX(x1,y1);
var _y1 = this.m_oFullTransform.TransformPointY(x1,y1);
var _x2 = this.m_oFullTransform.TransformPointX(x2,y2);
var _y2 = this.m_oFullTransform.TransformPointY(x2,y2);
_x1 = (_x1 >> 0) + 0.5;
_y1 = (_y1 >> 0) + 0.5;
_x2 = (_x2 >> 0) + 0.5;
_y2 = (_y2 >> 0) + 0.5;
this.p_color(138, 162, 191, 255);
var ctx = this.m_oContext;
if (_x1 != _x2 && _y1 != _y2)
{
// значит какой-то трансформ
var dKoefMMToPx = 1 / Math.max(this.m_oCoordTransform.sx, 0.001);
this.p_width(1000 * dKoefMMToPx);
this._s();
editor.WordControl.m_oDrawingDocument.AutoShapesTrack.AddLineDash(ctx, x1, y1, x2, y2, 2 * dKoefMMToPx, 2 * dKoefMMToPx);
this.ds();
return;
}
ctx.lineWidth = 1;
var bIsInt = this.m_bIntegerGrid;
if (!bIsInt)
this.SetIntegerGrid(true);
if (_x1 == _x2)
{
var _y = Math.min(_y1, _y2) + 0.5;
var _w1 = 2;
var _w2 = 2;
var _wmax = Math.max(_y1, _y2) - 0.5;
this._s();
while (true)
{
if (_y > _wmax)
break;
ctx.moveTo(_x1,_y);
_y+=_w1;
if (_y > _wmax)
{
ctx.lineTo(_x1,_y - _w1 + 1);
}
else
{
ctx.lineTo(_x1,_y);
}
_y+=_w2;
}
this.ds();
}
else if (_y1 == _y2)
{
var _x = Math.min(_x1, _x2) + 0.5;
var _w1 = 2;
var _w2 = 2;
var _wmax = Math.max(_x1, _x2) - 0.5;
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y1);
_x+=_w1;
if (_x > _wmax)
{
ctx.lineTo(_x - _w2 + 1,_y1);
}
else
{
ctx.lineTo(_x,_y1);
}
_x+=_w2;
}
this.ds();
}
else
{
// значит какой-то трансформ
this._s();
editor.WordControl.m_oDrawingDocument.AutoShapesTrack.AddLineDash(ctx, _x1, _y1, _x2, _y2, 2, 2);
this.ds();
}
if (!bIsInt)
this.SetIntegerGrid(false);
},
// smart methods for horizontal / vertical lines
drawHorLine : function(align, y, x, r, penW)
{
if (!this.m_bIntegerGrid)
{
this.p_width(penW * 1000);
this._s();
this._m(x, y);
this._l(r, y);
this.ds();
return;
}
var pen_w = parseInt((this.m_dDpiX * penW / g_dKoef_in_to_mm) + 0.5);
if (0 == pen_w)
pen_w = 1;
var _x = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5 - 0.5;
var _r = (this.m_oFullTransform.TransformPointX(r,y) >> 0) + 0.5 + 0.5;
var ctx = this.m_oContext;
ctx.setTransform(1,0,0,1,0,0);
ctx.lineWidth = pen_w;
switch (align)
{
case 0:
{
// top
var _top = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_x, _top + pen_w / 2 - 0.5);
ctx.lineTo(_r, _top + pen_w / 2 - 0.5);
ctx.stroke();
break;
}
case 1:
{
// center
var _center = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
if (0 == (pen_w % 2))
{
ctx.moveTo(_x, _center - 0.5);
ctx.lineTo(_r, _center - 0.5);
}
else
{
ctx.moveTo(_x, _center);
ctx.lineTo(_r, _center);
}
ctx.stroke();
break;
}
case 2:
{
// bottom
var _bottom = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_x, _bottom - pen_w / 2 + 0.5);
ctx.lineTo(_r, _bottom - pen_w / 2 + 0.5);
ctx.stroke();
break;
}
}
},
drawHorLine2 : function(align, y, x, r, penW)
{
if (!this.m_bIntegerGrid)
{
var _y1 = y - penW / 2;
var _y2 = _y1 + 2 * penW;
this.p_width(penW * 1000);
this._s();
this._m(x, _y1);
this._l(r, _y1);
this.ds();
this._s();
this._m(x, _y2);
this._l(r, _y2);
this.ds();
return;
}
var pen_w = ((this.m_dDpiX * penW / g_dKoef_in_to_mm) + 0.5) >> 0;
if (0 == pen_w)
pen_w = 1;
var _x = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5 - 0.5;
var _r = (this.m_oFullTransform.TransformPointX(r,y) >> 0) + 0.5 + 0.5;
var ctx = this.m_oContext;
ctx.lineWidth = pen_w;
switch (align)
{
case 0:
{
// top
var _top = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
var _pos1 = _top + pen_w / 2 - 0.5 - pen_w;
var _pos2 = _pos1 + pen_w * 2;
ctx.beginPath();
ctx.moveTo(_x, _pos1);
ctx.lineTo(_r, _pos1);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(_x, _pos2);
ctx.lineTo(_r, _pos2);
ctx.stroke();
break;
}
case 1:
{
// center
// TODO:
break;
}
case 2:
{
// bottom
// TODO:
break;
}
}
},
drawVerLine : function(align, x, y, b, penW)
{
if (!this.m_bIntegerGrid)
{
this.p_width(penW * 1000);
this._s();
this._m(x, y);
this._l(x, b);
this.ds();
return;
}
var pen_w = ((this.m_dDpiX * penW / g_dKoef_in_to_mm) + 0.5) >> 0;
if (0 == pen_w)
pen_w = 1;
var _y = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5 - 0.5;
var _b = (this.m_oFullTransform.TransformPointY(x,b) >> 0) + 0.5 + 0.5;
var ctx = this.m_oContext;
ctx.lineWidth = pen_w;
switch (align)
{
case 0:
{
// left
var _left = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_left + pen_w / 2 - 0.5, _y);
ctx.lineTo(_left + pen_w / 2 - 0.5, _b);
ctx.stroke();
break;
}
case 1:
{
// center
var _center = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
ctx.beginPath();
if (0 == (pen_w % 2))
{
ctx.moveTo(_center - 0.5, _y);
ctx.lineTo(_center - 0.5, _b);
}
else
{
ctx.moveTo(_center, _y);
ctx.lineTo(_center, _b);
}
ctx.stroke();
break;
}
case 2:
{
// right
var _right = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_right - pen_w / 2 + 0.5, _y);
ctx.lineTo(_right - pen_w / 2 + 0.5, _b);
ctx.stroke();
break;
}
}
},
// мега крутые функции для таблиц
drawHorLineExt : function(align, y, x, r, penW, leftMW, rightMW)
{
if (!this.m_bIntegerGrid)
{
this.p_width(penW * 1000);
this._s();
this._m(x, y);
this._l(r, y);
this.ds();
return;
}
var pen_w = Math.max(((this.m_dDpiX * penW / g_dKoef_in_to_mm) + 0.5) >> 0, 1);
var _x = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
var _r = (this.m_oFullTransform.TransformPointX(r,y) >> 0) + 0.5;
if (leftMW != 0)
{
var _center = _x;
var pen_mw = Math.max(((this.m_dDpiX * Math.abs(leftMW) * 2 / g_dKoef_in_to_mm) + 0.5) >> 0, 1);
if (leftMW < 0)
{
if ((pen_mw % 2) == 0)
{
_x = _center - (pen_mw / 2);
}
else
{
_x = _center - ((pen_mw / 2) >> 0);
}
}
else
{
if ((pen_mw % 2) == 0)
{
_x = _center + ((pen_mw / 2) - 1.0);
}
else
{
_x = _center + ((pen_mw / 2) >> 0);
}
}
}
if (rightMW != 0)
{
var _center = _r;
var pen_mw = Math.max(((this.m_dDpiX * Math.abs(rightMW) * 2 / g_dKoef_in_to_mm) + 0.5) >> 0, 1);
if (rightMW < 0)
{
if ((pen_mw % 2) == 0)
{
_r = _center - (pen_mw / 2);
}
else
{
_r = _center - ((pen_mw / 2) >> 0);
}
}
else
{
if ((pen_mw % 2) == 0)
{
_r = _center + (pen_mw / 2) - 1.0;
}
else
{
_r = _center + ((pen_mw / 2) >> 0);
}
}
}
var ctx = this.m_oContext;
ctx.lineWidth = pen_w;
_x -= 0.5;
_r += 0.5;
switch (align)
{
case 0:
{
// top
var _top = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_x, _top + pen_w / 2 - 0.5);
ctx.lineTo(_r, _top + pen_w / 2 - 0.5);
ctx.stroke();
break;
}
case 1:
{
// center
var _center = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
if (0 == (pen_w % 2))
{
ctx.moveTo(_x, _center - 0.5);
ctx.lineTo(_r, _center - 0.5);
}
else
{
ctx.moveTo(_x, _center);
ctx.lineTo(_r, _center);
}
ctx.stroke();
break;
}
case 2:
{
// bottom
var _bottom = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_x, _bottom - pen_w / 2 + 0.5);
ctx.lineTo(_r, _bottom - pen_w / 2 + 0.5);
ctx.stroke();
break;
}
}
},
rect : function(x,y,w,h)
{
var ctx = this.m_oContext;
ctx.beginPath();
if (this.m_bIntegerGrid)
{
var _x = (this.m_oFullTransform.TransformPointX(x,y) + 0.5) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(x,y) + 0.5) >> 0;
var _r = (this.m_oFullTransform.TransformPointX(x+w,y) + 0.5) >> 0;
var _b = (this.m_oFullTransform.TransformPointY(x,y+h) + 0.5) >> 0;
ctx.rect(_x, _y, _r - _x, _b - _y);
}
else
{
ctx.rect(x, y, w, h);
}
},
TableRect : function(x,y,w,h)
{
var ctx = this.m_oContext;
if (this.m_bIntegerGrid)
{
var _x = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
var _y = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
var _r = (this.m_oFullTransform.TransformPointX(x+w,y) >> 0) + 0.5;
var _b = (this.m_oFullTransform.TransformPointY(x,y+h) >> 0) + 0.5;
ctx.fillRect(_x - 0.5, _y - 0.5, _r - _x + 1, _b - _y + 1);
}
else
{
ctx.fillRect(x, y, w, h);
}
},
// функции клиппирования
AddClipRect : function(x, y, w, h)
{
//this.ClipManager.AddRect(x, y, w, h);
var __rect = new _rect();
__rect.x = x;
__rect.y = y;
__rect.w = w;
__rect.h = h;
this.GrState.AddClipRect(__rect);
},
RemoveClipRect : function()
{
//this.ClipManager.RemoveRect();
},
AddSmartRect : function(x, y, w, h, pen_w)
{
if (!global_MatrixTransformer.IsIdentity2(this.m_oTransform))
{
this.ds();
return;
}
var bIsSmartAttack = false;
if (!this.m_bIntegerGrid)
{
this.SetIntegerGrid(true);
bIsSmartAttack = true;
}
var _pen_w = (pen_w * this.m_oCoordTransform.sx + 0.5) >> 0;
if (0 >= _pen_w)
_pen_w = 1;
this._s();
if ((_pen_w & 0x01) == 0x01)
{
var _x = (this.m_oFullTransform.TransformPointX(x, y) >> 0) + 0.5;
var _y = (this.m_oFullTransform.TransformPointY(x, y) >> 0) + 0.5;
var _r = (this.m_oFullTransform.TransformPointX(x+w, y+h) >> 0) + 0.5;
var _b = (this.m_oFullTransform.TransformPointY(x+w, y+h) >> 0) + 0.5;
this.m_oContext.rect(_x, _y, _r - _x, _b - _y);
}
else
{
var _x = (this.m_oFullTransform.TransformPointX(x, y) + 0.5) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(x, y) + 0.5) >> 0;
var _r = (this.m_oFullTransform.TransformPointX(x+w, y+h) + 0.5) >> 0;
var _b = (this.m_oFullTransform.TransformPointY(x+w, y+h) + 0.5) >> 0;
this.m_oContext.rect(_x, _y, _r - _x, _b - _y);
}
this.m_oContext.lineWidth = _pen_w;
this.ds();
if (bIsSmartAttack)
{
this.SetIntegerGrid(false);
}
},
SetClip : function(r)
{
var ctx = this.m_oContext;
ctx.save();
ctx.beginPath();
if (!global_MatrixTransformer.IsIdentity(this.m_oTransform))
{
ctx.rect(r.x, r.y, r.w, r.h);
}
else
{
var _x = (this.m_oFullTransform.TransformPointX(r.x,r.y) + 1) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(r.x,r.y) + 1) >> 0;
var _r = (this.m_oFullTransform.TransformPointX(r.x+r.w,r.y) - 1) >> 0;
var _b = (this.m_oFullTransform.TransformPointY(r.x,r.y+r.h) - 1) >> 0;
ctx.rect(_x, _y, _r - _x + 1, _b - _y + 1);
}
this.clip();
ctx.beginPath();
},
RemoveClip : function()
{
this.m_oContext.restore();
this.m_oContext.save();
if (this.m_oContext.globalAlpha != this.globalAlpha)
this.m_oContext.globalAlpha = this.globalAlpha;
},
drawCollaborativeChanges : function(x, y, w, h)
{
this.b_color1( 0, 255, 0, 64 );
this.rect( x, y, w, h );
this.df();
},
drawSearchResult : function(x, y, w, h)
{
this.b_color1( 255, 220, 0, 200 );
this.rect( x, y, w, h );
this.df();
},
drawFlowAnchor : function(x, y)
{
if (!window.g_flow_anchor || !window.g_flow_anchor.asc_complete || (!editor || !editor.ShowParaMarks))
return;
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(1,0,0,1,0,0);
}
var _x = this.m_oFullTransform.TransformPointX(x,y) >> 0;
var _y = this.m_oFullTransform.TransformPointY(x,y) >> 0;
this.m_oContext.drawImage(window.g_flow_anchor, _x, _y);
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
SavePen : function()
{
this.GrState.SavePen();
},
RestorePen : function()
{
this.GrState.RestorePen();
},
SaveBrush : function()
{
this.GrState.SaveBrush();
},
RestoreBrush : function()
{
this.GrState.RestoreBrush();
},
SavePenBrush : function()
{
this.GrState.SavePenBrush();
},
RestorePenBrush : function()
{
this.GrState.RestorePenBrush();
},
SaveGrState : function()
{
this.GrState.SaveGrState();
},
RestoreGrState : function()
{
this.GrState.RestoreGrState();
},
StartClipPath : function()
{
},
EndClipPath : function()
{
this.m_oContext.clip();
},
StartCheckTableDraw : function()
{
if (!this.m_bIntegerGrid && global_MatrixTransformer.IsIdentity2(this.m_oTransform))
{
this.SaveGrState();
this.SetIntegerGrid(true);
return true;
}
return false;
},
EndCheckTableDraw : function(bIsRestore)
{
if (bIsRestore)
this.RestoreGrState();
},
SetTextClipRect : function(_l, _t, _r, _b)
{
this.TextClipRect = {
l : (_l * this.m_oCoordTransform.sx) >> 0,
t : (_t * this.m_oCoordTransform.sy) >> 0,
r : (_r * this.m_oCoordTransform.sx) >> 0,
b : (_b * this.m_oCoordTransform.sy) >> 0
};
}
}; | Excel/model/DrawingObjects/Graphics.js | "use strict";
var g_fontManager2 = null;
function CClipManager()
{
this.clipRects = [];
this.curRect = new _rect();
this.BaseObject = null;
this.AddRect = function(x, y, w, h)
{
var _count = this.clipRects.length;
if (0 == _count)
{
this.curRect.x = x;
this.curRect.y = y;
this.curRect.w = w;
this.curRect.h = h;
var _r = new _rect();
_r.x = x;
_r.y = y;
_r.w = w;
_r.h = h;
this.clipRects[_count] = _r;
this.BaseObject.SetClip(this.curRect);
}
else
{
this.BaseObject.RemoveClip();
var _r = new _rect();
_r.x = x;
_r.y = y;
_r.w = w;
_r.h = h;
this.clipRects[_count] = _r;
this.curRect = this.IntersectRect(this.curRect, _r);
this.BaseObject.SetClip(this.curRect);
}
}
this.RemoveRect = function()
{
var _count = this.clipRects.length;
if (0 != _count)
{
this.clipRects.splice(_count - 1, 1);
--_count;
this.BaseObject.RemoveClip();
if (0 != _count)
{
this.curRect.x = this.clipRects[0].x;
this.curRect.y = this.clipRects[0].y;
this.curRect.w = this.clipRects[0].w;
this.curRect.h = this.clipRects[0].h;
for (var i = 1; i < _count; i++)
this.curRect = this.IntersectRect(this.curRect, this.clipRects[i]);
this.BaseObject.SetClip(this.curRect);
}
}
}
this.IntersectRect = function(r1, r2)
{
var res = new _rect();
res.x = Math.max(r1.x, r2.x);
res.y = Math.max(r1.y, r2.y);
res.w = Math.min(r1.x + r1.w, r2.x + r2.w) - res.x;
res.h = Math.min(r1.y + r1.h, r2.y + r2.h) - res.y;
if (0 > res.w)
res.w = 0;
if (0 > res.h)
res.h = 0;
return res;
}
}
function CPen()
{
this.Color = { R : 255, G : 255, B : 255, A : 255 };
this.Style = 0;
this.LineCap = 0;
this.LineJoin = 0;
this.LineWidth = 1;
}
function CBrush()
{
this.Color1 = { R : 255, G : 255, B : 255, A : 255 };
this.Color2 = { R : 255, G : 255, B : 255, A : 255 };
this.Type = 0;
}
var MATRIX_ORDER_PREPEND = 0;
var MATRIX_ORDER_APPEND = 1;
var bIsChrome = AscBrowser.isChrome;
var bIsSafari = AscBrowser.isSafari;
var bIsIE = AscBrowser.isIE;
var bIsAndroid = AscBrowser.isAndroid;
function deg2rad(deg){
return deg * Math.PI / 180.0;
}
function rad2deg(rad){
return rad * 180.0 / Math.PI;
}
function CMatrix()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
}
CMatrix.prototype =
{
Reset : function(){
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
},
// ���������
Multiply : function(matrix,order){
if (MATRIX_ORDER_PREPEND == order)
{
var m = new CMatrix();
m.sx = matrix.sx;
m.shx = matrix.shx;
m.shy = matrix.shy;
m.sy = matrix.sy;
m.tx = matrix.tx;
m.ty = matrix.ty;
m.Multiply(this, MATRIX_ORDER_APPEND);
this.sx = m.sx;
this.shx = m.shx;
this.shy = m.shy;
this.sy = m.sy;
this.tx = m.tx;
this.ty = m.ty;
}
else
{
var t0 = this.sx * matrix.sx + this.shy * matrix.shx;
var t2 = this.shx * matrix.sx + this.sy * matrix.shx;
var t4 = this.tx * matrix.sx + this.ty * matrix.shx + matrix.tx;
this.shy = this.sx * matrix.shy + this.shy * matrix.sy;
this.sy = this.shx * matrix.shy + this.sy * matrix.sy;
this.ty = this.tx * matrix.shy + this.ty * matrix.sy + matrix.ty;
this.sx = t0;
this.shx = t2;
this.tx = t4;
}
return this;
},
// � ������ ������� ������ ���������� (��� �������� �����������)
Translate : function(x,y,order){
var m = new CMatrix();
m.tx = x;
m.ty = y;
this.Multiply(m,order);
},
Scale : function(x,y,order){
var m = new CMatrix();
m.sx = x;
m.sy = y;
this.Multiply(m,order);
},
Rotate : function(a,order){
var m = new CMatrix();
var rad = deg2rad(a);
m.sx = Math.cos(rad);
m.shx = Math.sin(rad);
m.shy = -Math.sin(rad);
m.sy = Math.cos(rad);
this.Multiply(m,order);
},
RotateAt : function(a,x,y,order){
this.Translate(-x,-y,order);
this.Rotate(a,order);
this.Translate(x,y,order);
},
// determinant
Determinant : function(){
return this.sx * this.sy - this.shy * this.shx;
},
// invert
Invert : function(){
var det = this.Determinant();
if (0.0001 > Math.abs(det))
return;
var d = 1 / det;
var t0 = this.sy * d;
this.sy = this.sx * d;
this.shy = -this.shy * d;
this.shx = -this.shx * d;
var t4 = -this.tx * t0 - this.ty * this.shx;
this.ty = -this.tx * this.shy - this.ty * this.sy;
this.sx = t0;
this.tx = t4;
return this;
},
// transform point
TransformPointX : function(x,y){
return x * this.sx + y * this.shx + this.tx;
},
TransformPointY : function(x,y){
return x * this.shy + y * this.sy + this.ty;
},
// calculate rotate angle
GetRotation : function(){
var x1 = 0.0;
var y1 = 0.0;
var x2 = 1.0;
var y2 = 0.0;
this.TransformPoint(x1, y1);
this.TransformPoint(x2, y2);
var a = Math.atan2(y2-y1,x2-x1);
return rad2deg(a);
},
// ������� ���������
CreateDublicate : function(){
var m = new CMatrix();
m.sx = this.sx;
m.shx = this.shx;
m.shy = this.shy;
m.sy = this.sy;
m.tx = this.tx;
m.ty = this.ty;
return m;
},
IsIdentity : function()
{
if (this.sx == 1.0 &&
this.shx == 0.0 &&
this.shy == 0.0 &&
this.sy == 1.0 &&
this.tx == 0.0 &&
this.ty == 0.0)
{
return true;
}
return false;
},
IsIdentity2 : function()
{
if (this.sx == 1.0 &&
this.shx == 0.0 &&
this.shy == 0.0 &&
this.sy == 1.0)
{
return true;
}
return false;
}
};
function CMatrixL()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
}
CMatrixL.prototype =
{
CreateDublicate : function()
{
var m = new CMatrixL();
m.sx = this.sx;
m.shx = this.shx;
m.shy = this.shy;
m.sy = this.sy;
m.tx = this.tx;
m.ty = this.ty;
return m;
},
Reset : function()
{
this.sx = 1.0;
this.shx = 0.0;
this.shy = 0.0;
this.sy = 1.0;
this.tx = 0.0;
this.ty = 0.0;
},
TransformPointX : function(x,y)
{
return x * this.sx + y * this.shx + this.tx;
},
TransformPointY : function(x,y)
{
return x * this.shy + y * this.sy + this.ty;
}
};
function CGlobalMatrixTransformer()
{
this.TranslateAppend = function(m, _tx, _ty)
{
m.tx += _tx;
m.ty += _ty;
}
this.ScaleAppend = function(m, _sx, _sy)
{
m.sx *= _sx;
m.shx *= _sx;
m.shy *= _sy;
m.sy *= _sy;
m.tx *= _sx;
m.ty *= _sy;
}
this.RotateRadAppend = function(m, _rad)
{
var _sx = Math.cos(_rad);
var _shx = Math.sin(_rad);
var _shy = -Math.sin(_rad);
var _sy = Math.cos(_rad);
var t0 = m.sx * _sx + m.shy * _shx;
var t2 = m.shx * _sx + m.sy * _shx;
var t4 = m.tx * _sx + m.ty * _shx;
m.shy = m.sx * _shy + m.shy * _sy;
m.sy = m.shx * _shy + m.sy * _sy;
m.ty = m.tx * _shy + m.ty * _sy;
m.sx = t0;
m.shx = t2;
m.tx = t4;
}
this.MultiplyAppend = function(m1, m2)
{
var t0 = m1.sx * m2.sx + m1.shy * m2.shx;
var t2 = m1.shx * m2.sx + m1.sy * m2.shx;
var t4 = m1.tx * m2.sx + m1.ty * m2.shx + m2.tx;
m1.shy = m1.sx * m2.shy + m1.shy * m2.sy;
m1.sy = m1.shx * m2.shy + m1.sy * m2.sy;
m1.ty = m1.tx * m2.shy + m1.ty * m2.sy + m2.ty;
m1.sx = t0;
m1.shx = t2;
m1.tx = t4;
}
this.Invert = function(m)
{
var newM = m.CreateDublicate();
var det = newM.sx * newM.sy - newM.shy * newM.shx;
if (0.0001 > Math.abs(det))
return newM;
var d = 1 / det;
var t0 = newM.sy * d;
newM.sy = newM.sx * d;
newM.shy = -newM.shy * d;
newM.shx = -newM.shx * d;
var t4 = -newM.tx * t0 - newM.ty * newM.shx;
newM.ty = -newM.tx * newM.shy - newM.ty * newM.sy;
newM.sx = t0;
newM.tx = t4;
return newM;
}
this.MultiplyAppendInvert = function(m1, m2)
{
var m = this.Invert(m2);
this.MultiplyAppend(m1, m);
}
this.MultiplyPrepend = function(m1, m2)
{
var m = new CMatrixL();
m.sx = m2.sx;
m.shx = m2.shx;
m.shy = m2.shy;
m.sy = m2.sy;
m.tx = m2.tx;
m.ty = m2.ty;
this.MultiplyAppend(m, m1);
m1.sx = m.sx;
m1.shx = m.shx;
m1.shy = m.shy;
m1.sy = m.sy;
m1.tx = m.tx;
m1.ty = m.ty;
}
this.CreateDublicateM = function(matrix)
{
var m = new CMatrixL();
m.sx = matrix.sx;
m.shx = matrix.shx;
m.shy = matrix.shy;
m.sy = matrix.sy;
m.tx = matrix.tx;
m.ty = matrix.ty;
}
this.IsIdentity = function(m)
{
if (m.sx == 1.0 &&
m.shx == 0.0 &&
m.shy == 0.0 &&
m.sy == 1.0 &&
m.tx == 0.0 &&
m.ty == 0.0)
{
return true;
}
return false;
}
this.IsIdentity2 = function(m)
{
if (m.sx == 1.0 &&
m.shx == 0.0 &&
m.shy == 0.0 &&
m.sy == 1.0)
{
return true;
}
return false;
}
}
var global_MatrixTransformer = new CGlobalMatrixTransformer();
function CGraphics()
{
this.m_oContext = null;
this.m_dWidthMM = 0;
this.m_dHeightMM = 0;
this.m_lWidthPix = 0;
this.m_lHeightPix = 0;
this.m_dDpiX = 96.0;
this.m_dDpiY = 96.0;
this.m_bIsBreak = false;
this.textBB_l = 10000;
this.textBB_t = 10000;
this.textBB_r = -10000;
this.textBB_b = -10000;
this.m_oPen = new CPen();
this.m_oBrush = new CBrush();
this.m_oAutoShapesTrack = null;
this.m_oFontManager = null;
this.m_bIsFillTextCanvasColor = 0;
this.m_oCoordTransform = new CMatrixL();
this.m_oBaseTransform = new CMatrixL();
this.m_oTransform = new CMatrixL();
this.m_oFullTransform = new CMatrixL();
this.m_oInvertFullTransform = new CMatrixL();
this.ArrayPoints = null;
this.m_oCurFont = null;
// RFonts
this.m_oTextPr = null;
this.m_oLastFont = new CFontSetup();
this.m_bIntegerGrid = true;
this.ClipManager = new CClipManager();
this.ClipManager.BaseObject = this;
this.TextureFillTransformScaleX = 1;
this.TextureFillTransformScaleY = 1;
this.IsThumbnail = false;
this.GrState = new CGrState();
this.GrState.Parent = this;
this.globalAlpha = 1;
this.TextClipRect = null;
this.IsClipContext = false;
this.ClearMode = false;
this.IsUseFonts2 = false;
this.m_oFontManager2 = null;
this.m_oLastFont2 = null;
this.ClearMode = false;
this.IsRetina = false;
}
CGraphics.prototype =
{
init : function(context,width_px,height_px,width_mm,height_mm)
{
this.m_oContext = context;
this.m_lHeightPix = height_px;
this.m_lWidthPix = width_px;
this.m_dWidthMM = width_mm;
this.m_dHeightMM = height_mm;
this.m_dDpiX = 25.4 * this.m_lWidthPix / this.m_dWidthMM;
this.m_dDpiY = 25.4 * this.m_lHeightPix / this.m_dHeightMM;
this.m_oCoordTransform.sx = this.m_dDpiX / 25.4;
this.m_oCoordTransform.sy = this.m_dDpiY / 25.4;
this.TextureFillTransformScaleX = 1 / this.m_oCoordTransform.sx;
this.TextureFillTransformScaleY = 1 / this.m_oCoordTransform.sy;
if (this.IsThumbnail)
{
this.TextureFillTransformScaleX *= (width_px / (width_mm * g_dKoef_mm_to_pix));
this.TextureFillTransformScaleY *= (height_px / (height_mm * g_dKoef_mm_to_pix))
}
/*
if (true == this.m_oContext.mozImageSmoothingEnabled)
this.m_oContext.mozImageSmoothingEnabled = false;
*/
this.m_oLastFont.Clear();
this.m_oContext.save();
},
EndDraw : function()
{
},
put_GlobalAlpha : function(enable, alpha)
{
if (false === enable)
{
this.globalAlpha = 1;
this.m_oContext.globalAlpha = 1;
}
else
{
this.globalAlpha = alpha;
this.m_oContext.globalAlpha = alpha;
}
},
// pen methods
p_color : function(r,g,b,a)
{
var _c = this.m_oPen.Color;
_c.R = r;
_c.G = g;
_c.B = b;
_c.A = a;
this.m_oContext.strokeStyle = "rgba(" + _c.R + "," + _c.G + "," + _c.B + "," + (_c.A / 255) + ")";
},
p_width : function(w)
{
this.m_oPen.LineWidth = w / 1000;
if (!this.m_bIntegerGrid)
{
if (0 != this.m_oPen.LineWidth)
{
this.m_oContext.lineWidth = this.m_oPen.LineWidth;
}
else
{
var _x1 = this.m_oFullTransform.TransformPointX(0, 0);
var _y1 = this.m_oFullTransform.TransformPointY(0, 0);
var _x2 = this.m_oFullTransform.TransformPointX(1, 1);
var _y2 = this.m_oFullTransform.TransformPointY(1, 1);
var _koef = Math.sqrt(((_x2 - _x1)*(_x2 - _x1) + (_y2 - _y1)*(_y2 - _y1)) / 2);
this.m_oContext.lineWidth = 1 / _koef;
}
}
else
{
if (0 != this.m_oPen.LineWidth)
{
var _m = this.m_oFullTransform;
var x = _m.sx + _m.shx;
var y = _m.sy + _m.shy;
var koef = Math.sqrt((x * x + y * y) / 2);
this.m_oContext.lineWidth = this.m_oPen.LineWidth * koef;
}
else
{
this.m_oContext.lineWidth = 1;
}
}
},
// brush methods
b_color1 : function(r,g,b,a)
{
var _c = this.m_oBrush.Color1;
_c.R = r;
_c.G = g;
_c.B = b;
_c.A = a;
this.m_oContext.fillStyle = "rgba(" + _c.R + "," + _c.G + "," + _c.B + "," + (_c.A / 255) + ")";
this.m_bIsFillTextCanvasColor = 0;
},
b_color2 : function(r,g,b,a)
{
var _c = this.m_oBrush.Color2;
_c.R = r;
_c.G = g;
_c.B = b;
_c.A = a;
},
transform : function(sx,shy,shx,sy,tx,ty)
{
var _t = this.m_oTransform;
_t.sx = sx;
_t.shx = shx;
_t.shy = shy;
_t.sy = sy;
_t.tx = tx;
_t.ty = ty;
this.CalculateFullTransform();
if (false === this.m_bIntegerGrid)
{
var _ft = this.m_oFullTransform;
this.m_oContext.setTransform(_ft.sx,_ft.shy,_ft.shx,_ft.sy,_ft.tx,_ft.ty);
}
if (null != this.m_oFontManager)
{
this.m_oFontManager.SetTextMatrix(_t.sx,_t.shy,_t.shx,_t.sy,_t.tx,_t.ty);
}
},
CalculateFullTransform : function(isInvertNeed)
{
var _ft = this.m_oFullTransform;
var _t = this.m_oTransform;
_ft.sx = _t.sx;
_ft.shx = _t.shx;
_ft.shy = _t.shy;
_ft.sy = _t.sy;
_ft.tx = _t.tx;
_ft.ty = _t.ty;
global_MatrixTransformer.MultiplyAppend(_ft, this.m_oCoordTransform);
var _it = this.m_oInvertFullTransform;
_it.sx = _ft.sx;
_it.shx = _ft.shx;
_it.shy = _ft.shy;
_it.sy = _ft.sy;
_it.tx = _ft.tx;
_it.ty = _ft.ty;
if (false !== isInvertNeed)
{
global_MatrixTransformer.MultiplyAppendInvert(_it, _t);
}
},
// path commands
_s : function()
{
this.m_oContext.beginPath();
},
_e : function()
{
this.m_oContext.beginPath();
},
_z : function()
{
this.m_oContext.closePath();
},
_m : function(x,y)
{
if (false === this.m_bIntegerGrid)
{
this.m_oContext.moveTo(x,y);
if (this.ArrayPoints != null)
this.ArrayPoints[this.ArrayPoints.length] = {x: x, y: y};
}
else
{
var _x = (this.m_oFullTransform.TransformPointX(x,y)) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(x,y)) >> 0;
this.m_oContext.moveTo(_x + 0.5,_y + 0.5);
}
},
_l : function(x,y)
{
if (false === this.m_bIntegerGrid)
{
this.m_oContext.lineTo(x,y);
if (this.ArrayPoints != null)
this.ArrayPoints[this.ArrayPoints.length] = {x: x, y: y};
}
else
{
var _x = (this.m_oFullTransform.TransformPointX(x,y)) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(x,y)) >> 0;
this.m_oContext.lineTo(_x + 0.5,_y + 0.5);
}
},
_c : function(x1,y1,x2,y2,x3,y3)
{
if (false === this.m_bIntegerGrid)
{
this.m_oContext.bezierCurveTo(x1,y1,x2,y2,x3,y3);
if (this.ArrayPoints != null)
{
this.ArrayPoints[this.ArrayPoints.length] = {x: x1, y: y1};
this.ArrayPoints[this.ArrayPoints.length] = {x: x2, y: y2};
this.ArrayPoints[this.ArrayPoints.length] = {x: x3, y: y3};
}
}
else
{
var _x1 = (this.m_oFullTransform.TransformPointX(x1,y1)) >> 0;
var _y1 = (this.m_oFullTransform.TransformPointY(x1,y1)) >> 0;
var _x2 = (this.m_oFullTransform.TransformPointX(x2,y2)) >> 0;
var _y2 = (this.m_oFullTransform.TransformPointY(x2,y2)) >> 0;
var _x3 = (this.m_oFullTransform.TransformPointX(x3,y3)) >> 0;
var _y3 = (this.m_oFullTransform.TransformPointY(x3,y3)) >> 0;
this.m_oContext.bezierCurveTo(_x1 + 0.5,_y1 + 0.5,_x2 + 0.5,_y2 + 0.5,_x3 + 0.5,_y3 + 0.5);
}
},
_c2 : function(x1,y1,x2,y2)
{
if (false === this.m_bIntegerGrid)
{
this.m_oContext.quadraticCurveTo(x1,y1,x2,y2);
if (this.ArrayPoints != null)
{
this.ArrayPoints[this.ArrayPoints.length] = {x: x1, y: y1};
this.ArrayPoints[this.ArrayPoints.length] = {x: x2, y: y2};
}
}
else
{
var _x1 = (this.m_oFullTransform.TransformPointX(x1,y1)) >> 0;
var _y1 = (this.m_oFullTransform.TransformPointY(x1,y1)) >> 0;
var _x2 = (this.m_oFullTransform.TransformPointX(x2,y2)) >> 0;
var _y2 = (this.m_oFullTransform.TransformPointY(x2,y2)) >> 0;
this.m_oContext.quadraticCurveTo(_x1 + 0.5,_y1 + 0.5,_x2 + 0.5,_y2 + 0.5);
}
},
ds : function()
{
this.m_oContext.stroke();
},
df : function()
{
this.m_oContext.fill();
},
// canvas state
save : function()
{
this.m_oContext.save();
},
restore : function()
{
this.m_oContext.restore();
},
clip : function()
{
this.m_oContext.clip();
},
reset : function()
{
this.m_oTransform.Reset();
this.CalculateFullTransform(false);
this.m_oContext.setTransform(this.m_oCoordTransform.sx,0,0,this.m_oCoordTransform.sy,0, 0);
},
transform3 : function(m, isNeedInvert)
{
var _t = this.m_oTransform;
_t.sx = m.sx;
_t.shx = m.shx;
_t.shy = m.shy;
_t.sy = m.sy;
_t.tx = m.tx;
_t.ty = m.ty;
this.CalculateFullTransform(isNeedInvert);
var _ft = this.m_oFullTransform;
this.m_oContext.setTransform(_ft.sx,_ft.shy,_ft.shx,_ft.sy,_ft.tx,_ft.ty);
// теперь трансформ выставляется ТОЛЬКО при загрузке шрифта. Здесь другого быть и не может
/*
if (null != this.m_oFontManager && false !== isNeedInvert)
{
this.m_oFontManager.SetTextMatrix(this.m_oTransform.sx,this.m_oTransform.shy,this.m_oTransform.shx,
this.m_oTransform.sy,this.m_oTransform.tx,this.m_oTransform.ty);
}
*/
},
CheckUseFonts2 : function(_transform)
{
if (!global_MatrixTransformer.IsIdentity2(_transform))
{
if (window.g_fontManager2 == null)
{
window.g_fontManager2 = new CFontManager();
window.g_fontManager2.Initialize(true);
}
this.m_oFontManager2 = window.g_fontManager2;
if (null == this.m_oLastFont2)
this.m_oLastFont2 = new CFontSetup();
this.IsUseFonts2 = true;
}
},
UncheckUseFonts2 : function()
{
this.IsUseFonts2 = false;
},
FreeFont : function()
{
// это чтобы не сбросился кэш при отрисовке следующего шейпа
this.m_oFontManager.m_pFont = null;
},
// images
drawImage2 : function(img,x,y,w,h,alpha,srcRect)
{
var isA = (undefined !== alpha && null != alpha && 255 != alpha);
var _oldGA = 0;
if (isA)
{
_oldGA = this.m_oContext.globalAlpha;
this.m_oContext.globalAlpha = alpha / 255;
}
if (false === this.m_bIntegerGrid)
{
if (!srcRect)
{
// тут нужно проверить, можно ли нарисовать точно. т.е. может картинка ровно такая, какая нужна.
if (!global_MatrixTransformer.IsIdentity2(this.m_oTransform))
{
this.m_oContext.drawImage(img,x,y,w,h);
}
else
{
var xx = this.m_oFullTransform.TransformPointX(x, y);
var yy = this.m_oFullTransform.TransformPointY(x, y);
var rr = this.m_oFullTransform.TransformPointX(x + w, y + h);
var bb = this.m_oFullTransform.TransformPointY(x + w, y + h);
var ww = rr - xx;
var hh = bb - yy;
if (Math.abs(img.width - ww) < 2 && Math.abs(img.height - hh) < 2)
{
// рисуем точно
this.m_oContext.setTransform(1, 0, 0, 1, 0, 0);
this.m_oContext.drawImage(img, xx >> 0, yy >> 0);
var _ft = this.m_oFullTransform;
this.m_oContext.setTransform(_ft.sx,_ft.shy,_ft.shx,_ft.sy,_ft.tx,_ft.ty);
}
else
{
this.m_oContext.drawImage(img,x,y,w,h);
}
}
}
else
{
var _w = img.width;
var _h = img.height;
if (_w > 0 && _h > 0)
{
var __w = w;
var __h = h;
var _delW = Math.max(0, -srcRect.l) + Math.max(0, srcRect.r - 100) + 100;
var _delH = Math.max(0, -srcRect.t) + Math.max(0, srcRect.b - 100) + 100;
var _sx = 0;
if (srcRect.l > 0 && srcRect.l < 100)
_sx = Math.min((_w * srcRect.l / 100) >> 0, _w - 1);
else if (srcRect.l < 0)
{
var _off = ((-srcRect.l / _delW) * __w);
x += _off;
w -= _off;
}
var _sy = 0;
if (srcRect.t > 0 && srcRect.t < 100)
_sy = Math.min((_h * srcRect.t / 100) >> 0, _h - 1);
else if (srcRect.t < 0)
{
var _off = ((-srcRect.t / _delH) * __h);
y += _off;
h -= _off;
}
var _sr = _w;
if (srcRect.r > 0 && srcRect.r < 100)
_sr = Math.max(Math.min((_w * srcRect.r / 100) >> 0, _w - 1), _sx);
else if (srcRect.r > 100)
{
var _off = ((srcRect.r - 100) / _delW) * __w;
w -= _off;
}
var _sb = _h;
if (srcRect.b > 0 && srcRect.b < 100)
_sb = Math.max(Math.min((_h * srcRect.b / 100) >> 0, _h - 1), _sy);
else if (srcRect.b > 100)
{
var _off = ((srcRect.b - 100) / _delH) * __h;
h -= _off;
}
this.m_oContext.drawImage(img,_sx,_sy,_sr-_sx,_sb-_sy,x,y,w,h);
}
else
{
this.m_oContext.drawImage(img,x,y,w,h);
}
}
}
else
{
var _x1 = (this.m_oFullTransform.TransformPointX(x,y)) >> 0;
var _y1 = (this.m_oFullTransform.TransformPointY(x,y)) >> 0;
var _x2 = (this.m_oFullTransform.TransformPointX(x+w,y+h)) >> 0;
var _y2 = (this.m_oFullTransform.TransformPointY(x+w,y+h)) >> 0;
x = _x1;
y = _y1;
w = _x2 - _x1;
h = _y2 - _y1;
if (!srcRect)
{
// тут нужно проверить, можно ли нарисовать точно. т.е. может картинка ровно такая, какая нужна.
if (!global_MatrixTransformer.IsIdentity2(this.m_oTransform))
{
this.m_oContext.drawImage(img,_x1,_y1,w,h);
}
else
{
if (Math.abs(img.width - w) < 2 && Math.abs(img.height - h) < 2)
{
// рисуем точно
this.m_oContext.drawImage(img, x, y);
}
else
{
this.m_oContext.drawImage(img,_x1,_y1,w,h);
}
}
}
else
{
var _w = img.width;
var _h = img.height;
if (_w > 0 && _h > 0)
{
var __w = w;
var __h = h;
var _delW = Math.max(0, -srcRect.l) + Math.max(0, srcRect.r - 100) + 100;
var _delH = Math.max(0, -srcRect.t) + Math.max(0, srcRect.b - 100) + 100;
var _sx = 0;
if (srcRect.l > 0 && srcRect.l < 100)
_sx = Math.min((_w * srcRect.l / 100) >> 0, _w - 1);
else if (srcRect.l < 0)
{
var _off = ((-srcRect.l / _delW) * __w);
x += _off;
w -= _off;
}
var _sy = 0;
if (srcRect.t > 0 && srcRect.t < 100)
_sy = Math.min((_h * srcRect.t / 100) >> 0, _h - 1);
else if (srcRect.t < 0)
{
var _off = ((-srcRect.t / _delH) * __h);
y += _off;
h -= _off;
}
var _sr = _w;
if (srcRect.r > 0 && srcRect.r < 100)
_sr = Math.max(Math.min((_w * srcRect.r / 100) >> 0, _w - 1), _sx);
else if (srcRect.r > 100)
{
var _off = ((srcRect.r - 100) / _delW) * __w;
w -= _off;
}
var _sb = _h;
if (srcRect.b > 0 && srcRect.b < 100)
_sb = Math.max(Math.min((_h * srcRect.b / 100) >> 0, _h - 1), _sy);
else if (srcRect.b > 100)
{
var _off = ((srcRect.b - 100) / _delH) * __h;
h -= _off;
}
this.m_oContext.drawImage(img,_sx,_sy,_sr-_sx,_sb-_sy,x,y,w,h);
}
else
{
this.m_oContext.drawImage(img,x,y,w,h);
}
}
}
if (isA)
{
this.m_oContext.globalAlpha = _oldGA;
}
},
drawImage : function(img,x,y,w,h,alpha,srcRect,nativeImage)
{
if (nativeImage)
{
this.drawImage2(nativeImage,x,y,w,h,alpha,srcRect);
return;
}
var editor = window["Asc"]["editor"];
var _img = editor.ImageLoader.map_image_index[img];
if (_img != undefined && _img.Status == ImageLoadStatus.Loading)
{
// TODO: IMAGE_LOADING
}
else if (_img != undefined && _img.Image != null)
{
this.drawImage2(_img.Image,x,y,w,h,alpha,srcRect);
}
else
{
var _x = x;
var _y = y;
var _r = x+w;
var _b = y+h;
if (this.m_bIntegerGrid)
{
_x = this.m_oFullTransform.TransformPointX(x,y);
_y = this.m_oFullTransform.TransformPointY(x,y);
_r = this.m_oFullTransform.TransformPointX(x+w,y+h);
_b = this.m_oFullTransform.TransformPointY(x+w,y+h);
}
var ctx = this.m_oContext;
var old_p = ctx.lineWidth;
ctx.beginPath();
ctx.moveTo(_x,_y);
ctx.lineTo(_r,_b);
ctx.moveTo(_r,_y);
ctx.lineTo(_x,_b);
ctx.strokeStyle = "#FF0000";
ctx.stroke();
ctx.beginPath();
ctx.moveTo(_x,_y);
ctx.lineTo(_r,_y);
ctx.lineTo(_r,_b);
ctx.lineTo(_x,_b);
ctx.closePath();
ctx.lineWidth = 1;
ctx.strokeStyle = "#000000";
ctx.stroke();
ctx.beginPath();
ctx.lineWidth = old_p;
ctx.strokeStyle = "rgba(" + this.m_oPen.Color.R + "," + this.m_oPen.Color.G + "," +
this.m_oPen.Color.B + "," + (this.m_oPen.Color.A / 255) + ")";
}
},
// text
GetFont : function()
{
return this.m_oCurFont;
},
font : function(font_id,font_size,matrix)
{
window.g_font_infos[window.g_map_font_index[font_id]].LoadFont(editor.FontLoader, this.m_oFontManager, font_size, 0, this.m_dDpiX, this.m_dDpiY, /*matrix*/undefined);
},
SetFont : function(font)
{
if (null == font)
return;
this.m_oCurFont =
{
FontFamily :
{
Index : font.FontFamily.Index,
Name : font.FontFamily.Name
},
FontSize : font.FontSize,
Bold : font.Bold,
Italic : font.Italic
};
if (-1 == font.FontFamily.Index || undefined === font.FontFamily.Index || null == font.FontFamily.Index)
font.FontFamily.Index = window.g_map_font_index[font.FontFamily.Name];
if (font.FontFamily.Index == undefined || font.FontFamily.Index == -1)
return;
var bItalic = true === font.Italic;
var bBold = true === font.Bold;
var oFontStyle = FontStyle.FontStyleRegular;
if ( !bItalic && bBold )
oFontStyle = FontStyle.FontStyleBold;
else if ( bItalic && !bBold )
oFontStyle = FontStyle.FontStyleItalic;
else if ( bItalic && bBold )
oFontStyle = FontStyle.FontStyleBoldItalic;
var _last_font = this.IsUseFonts2 ? this.m_oLastFont2 : this.m_oLastFont;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
_last_font.SetUpIndex = font.FontFamily.Index;
_last_font.SetUpSize = font.FontSize;
_last_font.SetUpStyle = oFontStyle;
window.g_font_infos[font.FontFamily.Index].LoadFont(window.g_font_loader, _font_manager, font.FontSize, oFontStyle, this.m_dDpiX, this.m_dDpiY, this.m_oTransform);
var _mD = _last_font.SetUpMatrix;
var _mS = this.m_oTransform;
_mD.sx = _mS.sx;
_mD.sy = _mS.sy;
_mD.shx = _mS.shx;
_mD.shy = _mS.shy;
_mD.tx = _mS.tx;
_mD.ty = _mS.ty;
//_font_manager.SetTextMatrix(this.m_oTransform.sx,this.m_oTransform.shy,this.m_oTransform.shx,
// this.m_oTransform.sy,this.m_oTransform.tx,this.m_oTransform.ty);
},
SetTextPr : function(textPr, theme)
{
this.m_oTextPr = textPr.Copy();
this.theme = theme;
var FontScheme = theme.themeElements.fontScheme;
this.m_oTextPr.RFonts.Ascii = {Name: FontScheme.checkFont(this.m_oTextPr.RFonts.Ascii.Name), Index: -1};
this.m_oTextPr.RFonts.EastAsia = {Name: FontScheme.checkFont(this.m_oTextPr.RFonts.EastAsia.Name), Index: -1};
this.m_oTextPr.RFonts.HAnsi = {Name: FontScheme.checkFont(this.m_oTextPr.RFonts.HAnsi.Name), Index: -1};
this.m_oTextPr.RFonts.CS = {Name: FontScheme.checkFont(this.m_oTextPr.RFonts.CS.Name), Index: -1};
},
SetFontSlot : function(slot, fontSizeKoef)
{
var _rfonts = this.m_oTextPr.RFonts;
var _lastFont = this.IsUseFonts2 ? this.m_oLastFont2 : this.m_oLastFont;
switch (slot)
{
case fontslot_ASCII:
{
_lastFont.Name = _rfonts.Ascii.Name;
_lastFont.Index = _rfonts.Ascii.Index;
if (_lastFont.Index == -1 || _lastFont.Index === undefined)
{
_lastFont.Index = window.g_map_font_index[_lastFont.Name];
}
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
case fontslot_CS:
{
_lastFont.Name = _rfonts.CS.Name;
_lastFont.Index = _rfonts.CS.Index;
if (_lastFont.Index == -1 || _lastFont.Index === undefined)
{
_lastFont.Index = window.g_map_font_index[_lastFont.Name];
}
_lastFont.Size = this.m_oTextPr.FontSizeCS;
_lastFont.Bold = this.m_oTextPr.BoldCS;
_lastFont.Italic = this.m_oTextPr.ItalicCS;
break;
}
case fontslot_EastAsia:
{
_lastFont.Name = _rfonts.EastAsia.Name;
_lastFont.Index = _rfonts.EastAsia.Index;
if (_lastFont.Index == -1 || _lastFont.Index === undefined)
{
_lastFont.Index = window.g_map_font_index[_lastFont.Name];
}
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
case fontslot_HAnsi:
default:
{
_lastFont.Name = _rfonts.HAnsi.Name;
_lastFont.Index = _rfonts.HAnsi.Index;
if (_lastFont.Index == -1 || _lastFont.Index === undefined)
{
_lastFont.Index = window.g_map_font_index[_lastFont.Name];
}
_lastFont.Size = this.m_oTextPr.FontSize;
_lastFont.Bold = this.m_oTextPr.Bold;
_lastFont.Italic = this.m_oTextPr.Italic;
break;
}
}
if (undefined !== fontSizeKoef)
_lastFont.Size *= fontSizeKoef;
var _style = 0;
if (_lastFont.Italic)
_style += 2;
if (_lastFont.Bold)
_style += 1;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
if (_lastFont.Index != _lastFont.SetUpIndex || _lastFont.Size != _lastFont.SetUpSize || _style != _lastFont.SetUpStyle)
{
_lastFont.SetUpIndex = _lastFont.Index;
_lastFont.SetUpSize = _lastFont.Size;
_lastFont.SetUpStyle = _style;
window.g_font_infos[_lastFont.SetUpIndex].LoadFont(window.g_font_loader, _font_manager, _lastFont.SetUpSize, _lastFont.SetUpStyle, this.m_dDpiX, this.m_dDpiY, this.m_oTransform);
var _mD = _lastFont.SetUpMatrix;
var _mS = this.m_oTransform;
_mD.sx = _mS.sx;
_mD.sy = _mS.sy;
_mD.shx = _mS.shx;
_mD.shy = _mS.shy;
_mD.tx = _mS.tx;
_mD.ty = _mS.ty;
}
else
{
var _mD = _lastFont.SetUpMatrix;
var _mS = this.m_oTransform;
if (_mD.sx != _mS.sx || _mD.sy != _mS.sy || _mD.shx != _mS.shx || _mD.shy != _mS.shy || _mD.tx != _mS.tx || _mD.ty != _mS.ty)
{
_mD.sx = _mS.sx;
_mD.sy = _mS.sy;
_mD.shx = _mS.shx;
_mD.shy = _mS.shy;
_mD.tx = _mS.tx;
_mD.ty = _mS.ty;
_font_manager.SetTextMatrix(_mD.sx,_mD.shy,_mD.shx,_mD.sy,_mD.tx,_mD.ty);
}
}
//_font_manager.SetTextMatrix(this.m_oTransform.sx,this.m_oTransform.shy,this.m_oTransform.shx,
// this.m_oTransform.sy,this.m_oTransform.tx,this.m_oTransform.ty);
},
GetTextPr : function()
{
return this.m_oTextPr;
},
FillText : function(x,y,text)
{
// убыстеренный вариант. здесь везде заточка на то, что приходит одна буква
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString2C(text,_x,_y);
}
catch(err)
{
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(1,0,0,1,0,0);
}
var pGlyph = _font_manager.m_oGlyphString.m_pGlyphsBuffer[0];
if (null == pGlyph)
return;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyph(pGlyph);
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
t : function(text,x,y)
{
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString2(text,_x,_y);
}
catch(err)
{
}
this.m_oContext.setTransform(1,0,0,1,0,0);
while (true)
{
var pGlyph = _font_manager.GetNextChar2();
if (null == pGlyph)
break;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyph(pGlyph);
}
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
FillText2 : function(x,y,text,cropX,cropW)
{
// убыстеренный вариант. здесь везде заточка на то, что приходит одна буква
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString2C(text,_x,_y);
}
catch(err)
{
}
this.m_oContext.setTransform(1,0,0,1,0,0);
var pGlyph = _font_manager.m_oGlyphString.m_pGlyphsBuffer[0];
if (null == pGlyph)
return;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyphC(pGlyph,cropX,cropW);
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
t2 : function(text,x,y,cropX,cropW)
{
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString2(text,_x,_y);
}
catch(err)
{
}
this.m_oContext.setTransform(1,0,0,1,0,0);
while (true)
{
var pGlyph = _font_manager.GetNextChar2();
if (null == pGlyph)
break;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyphC(pGlyph,cropX,cropW);
}
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
FillTextCode : function(x,y,lUnicode)
{
// убыстеренный вариант. здесь везде заточка на то, что приходит одна буква
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString4C(lUnicode,_x,_y);
}
catch(err)
{
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(1,0,0,1,0,0);
}
var pGlyph = _font_manager.m_oGlyphString.m_pGlyphsBuffer[0];
if (null == pGlyph)
return;
if (null != pGlyph.oBitmap)
{
this.private_FillGlyph(pGlyph);
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
tg : function(text,x,y)
{
if (this.m_bIsBreak)
return;
var _x = this.m_oInvertFullTransform.TransformPointX(x,y);
var _y = this.m_oInvertFullTransform.TransformPointY(x,y);
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
try
{
_font_manager.LoadString3C(text,_x,_y);
}
catch(err)
{
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(1,0,0,1,0,0);
}
var pGlyph = _font_manager.m_oGlyphString.m_pGlyphsBuffer[0];
if (null == pGlyph)
return;
if (null != pGlyph.oBitmap)
{
var _a = this.m_oBrush.Color1.A;
if (255 != _a)
this.m_oContext.globalAlpha = _a / 255;
this.private_FillGlyph(pGlyph);
if (255 != _a)
this.m_oContext.globalAlpha = 1.0;
}
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
charspace : function(space)
{
},
// private methods
private_FillGlyph : function(pGlyph)
{
// new scheme
var nW = pGlyph.oBitmap.nWidth;
var nH = pGlyph.oBitmap.nHeight;
if (0 == nW || 0 == nH)
return;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
var nX = (_font_manager.m_oGlyphString.m_fX + pGlyph.fX + pGlyph.oBitmap.nX) >> 0;
var nY = (_font_manager.m_oGlyphString.m_fY + pGlyph.fY - pGlyph.oBitmap.nY) >> 0;
pGlyph.oBitmap.oGlyphData.checkColor(this.m_oBrush.Color1.R,this.m_oBrush.Color1.G,this.m_oBrush.Color1.B,nW,nH);
if (null == this.TextClipRect)
pGlyph.oBitmap.draw(this.m_oContext, nX, nY, this.TextClipRect);
else
pGlyph.oBitmap.drawCropInRect(this.m_oContext, nX, nY, this.TextClipRect);
},
private_FillGlyphC : function(pGlyph,cropX,cropW)
{
// new scheme
var nW = pGlyph.oBitmap.nWidth;
var nH = pGlyph.oBitmap.nHeight;
if (0 == nW || 0 == nH)
return;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
var nX = (_font_manager.m_oGlyphString.m_fX + pGlyph.fX + pGlyph.oBitmap.nX) >> 0;
var nY = (_font_manager.m_oGlyphString.m_fY + pGlyph.fY - pGlyph.oBitmap.nY) >> 0;
var d_koef = this.m_dDpiX / 25.4;
var cX = Math.max((cropX * d_koef) >> 0, 0);
var cW = Math.min((cropW * d_koef) >> 0, nW);
if (cW <= 0)
cW = 1;
pGlyph.oBitmap.oGlyphData.checkColor(this.m_oBrush.Color1.R,this.m_oBrush.Color1.G,this.m_oBrush.Color1.B,nW,nH);
pGlyph.oBitmap.drawCrop(this.m_oContext, nX, nY, cW, nH, cX);
},
private_FillGlyph2 : function(pGlyph)
{
var i = 0;
var j = 0;
var nW = pGlyph.oBitmap.nWidth;
var nH = pGlyph.oBitmap.nHeight;
if (0 == nW || 0 == nH)
return;
var _font_manager = this.IsUseFonts2 ? this.m_oFontManager2 : this.m_oFontManager;
var nX = (_font_manager.m_oGlyphString.m_fX + pGlyph.fX + pGlyph.oBitmap.nX) >> 0;
var nY = (_font_manager.m_oGlyphString.m_fY + pGlyph.fY - pGlyph.oBitmap.nY) >> 0;
var imageData = this.m_oContext.getImageData(nX,nY,nW,nH);
var pPixels = imageData.data;
var _r = this.m_oBrush.Color1.R;
var _g = this.m_oBrush.Color1.G;
var _b = this.m_oBrush.Color1.B;
for (; j < nH; ++j)
{
var indx = 4 * j * nW;
for (i = 0; i < nW; ++i)
{
var weight = pGlyph.oBitmap.pData[j * pGlyph.oBitmap.nWidth + i];
if (255 == weight)
{
pPixels[indx] = _r;
pPixels[indx + 1] = _g;
pPixels[indx + 2] = _b;
pPixels[indx + 3] = 255;
}
else
{
var r = pPixels[indx];
var g = pPixels[indx + 1];
var b = pPixels[indx + 2];
var a = pPixels[indx + 3];
pPixels[indx] = ((_r - r) * weight + (r << 8)) >>> 8;
pPixels[indx + 1] = ((_g - g) * weight + (g << 8)) >>> 8;
pPixels[indx + 2] = ((_b - b) * weight + (b << 8)) >>> 8;
pPixels[indx + 3] = (weight + a) - ((weight * a + 256) >>> 8);
}
indx += 4;
}
}
this.m_oContext.putImageData(imageData,nX,nY);
},
SetIntegerGrid : function(param)
{
if (true == param)
{
this.m_bIntegerGrid = true;
this.m_oContext.setTransform(1,0,0,1,0,0);
}
else
{
this.m_bIntegerGrid = false;
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
GetIntegerGrid : function()
{
return this.m_bIntegerGrid;
},
DrawHeaderEdit : function(yPos, lock_type)
{
var _y = this.m_oFullTransform.TransformPointY(0,yPos);
_y = (_y >> 0) + 0.5;
var _x = 0;
var _wmax = this.m_lWidthPix;
var _w1 = 6;
var _w2 = 3;
var ctx = this.m_oContext;
switch (lock_type)
{
case locktype_None:
case locktype_Mine:
{
this.p_color(155, 187, 277, 255);
ctx.lineWidth = 2;
break;
}
case locktype_Other:
case locktype_Other2:
{
this.p_color(238, 53, 37, 255);
ctx.lineWidth = 1;
_w1 = 2;
_w2 = 1;
break;
}
default:
{
this.p_color(155, 187, 277, 255);
ctx.lineWidth = 2;
_w1 = 2;
_w2 = 1;
}
}
if (true === this.m_bIntegerGrid)
{
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y);
_x+=_w1;
ctx.lineTo(_x,_y);
_x+=_w2;
}
this.ds();
}
else
{
this.SetIntegerGrid(true);
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y);
_x+=_w1;
ctx.lineTo(_x,_y);
_x+=_w2;
}
this.ds();
this.SetIntegerGrid(false);
}
},
DrawFooterEdit : function(yPos, lock_type)
{
var _y = this.m_oFullTransform.TransformPointY(0,yPos);
_y = (_y >> 0) + 0.5;
var _x = 0;
var _w1 = 6;
var _w2 = 3;
var ctx = this.m_oContext;
switch (lock_type)
{
case locktype_None:
case locktype_Mine:
{
this.p_color(155, 187, 277, 255);
ctx.lineWidth = 2;
break;
}
case locktype_Other:
case locktype_Other2:
{
this.p_color(238, 53, 37, 255);
ctx.lineWidth = 1;
_w1 = 2;
_w2 = 1;
break;
}
default:
{
this.p_color(155, 187, 277, 255);
ctx.lineWidth = 2;
_w1 = 2;
_w2 = 1;
}
}
var _wmax = this.m_lWidthPix;
if (true === this.m_bIntegerGrid)
{
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y);
_x+=_w1;
ctx.lineTo(_x,_y);
_x+=_w2;
}
this.ds();
}
else
{
this.SetIntegerGrid(true);
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y);
_x+=_w1;
ctx.lineTo(_x,_y);
_x+=_w2;
}
this.ds();
this.SetIntegerGrid(false);
}
},
DrawLockParagraph : function(lock_type, x, y1, y2)
{
if (lock_type == c_oAscLockTypes.kLockTypeNone || editor.WordControl.m_oDrawingDocument.IsLockObjectsEnable === false || editor.isViewMode)
return;
if (lock_type == c_oAscLockTypes.kLockTypeMine)
{
this.p_color(22, 156, 0, 255);
//this.p_color(155, 187, 277, 255);
}
else
this.p_color(238, 53, 37, 255);
var _x = this.m_oFullTransform.TransformPointX(x, y1) >> 0;
var _xT = this.m_oFullTransform.TransformPointX(x, y2) >> 0;
var _y1 = (this.m_oFullTransform.TransformPointY(x, y1) >> 0) + 0.5;
var _y2 = (this.m_oFullTransform.TransformPointY(x, y2) >> 0) - 1.5;
var ctx = this.m_oContext;
if (_x != _xT)
{
// значит какой-то трансформ
var dKoefMMToPx = 1 / Math.max(this.m_oCoordTransform.sx, 0.001);
this.p_width(1000 * dKoefMMToPx);
var w_dot = 2 * dKoefMMToPx;
var w_dist = 1 * dKoefMMToPx;
var w_len_indent = 3;
var _interf = editor.WordControl.m_oDrawingDocument.AutoShapesTrack;
this._s();
_interf.AddLineDash(ctx, x, y1, x, y2, w_dot, w_dist);
_interf.AddLineDash(ctx, x, y1, x + w_len_indent, y1, w_dot, w_dist);
_interf.AddLineDash(ctx, x, y2, x + w_len_indent, y2, w_dot, w_dist);
this.ds();
return;
}
var bIsInt = this.m_bIntegerGrid;
if (!bIsInt)
this.SetIntegerGrid(true);
ctx.lineWidth = 1;
var w_dot = 2;
var w_dist = 1;
var w_len_indent = (3 * this.m_oCoordTransform.sx) >> 0;
this._s();
var y_mem = _y1 - 0.5;
while (true)
{
if ((y_mem + w_dot) > _y2)
break;
ctx.moveTo(_x + 0.5,y_mem);
y_mem+=w_dot;
ctx.lineTo(_x + 0.5,y_mem);
y_mem+=w_dist;
}
var x_max = _x + w_len_indent;
var x_mem = _x;
while (true)
{
if (x_mem > x_max)
break;
ctx.moveTo(x_mem,_y1);
x_mem+=w_dot;
ctx.lineTo(x_mem,_y1);
x_mem+=w_dist;
}
x_mem = _x;
while (true)
{
if (x_mem > x_max)
break;
ctx.moveTo(x_mem,_y2);
x_mem+=w_dot;
ctx.lineTo(x_mem,_y2);
x_mem+=w_dist;
}
this.ds();
if (!bIsInt)
this.SetIntegerGrid(false);
},
DrawLockObjectRect : function(lock_type, x, y, w, h)
{
if (lock_type == c_oAscLockTypes.kLockTypeNone)
return;
if (lock_type == c_oAscLockTypes.kLockTypeMine)
{
this.p_color(22, 156, 0, 255);
//this.p_color(155, 187, 277, 255);
}
else
this.p_color(238, 53, 37, 255);
var ctx = this.m_oContext;
var _m = this.m_oTransform;
if (_m.sx != 1.0 || _m.shx != 0.0 || _m.shy != 0.0 || _m.sy != 1.0)
{
// значит какой-то трансформ
var dKoefMMToPx = 1 / Math.max(this.m_oCoordTransform.sx, 0.001);
this.p_width(1000 * dKoefMMToPx);
var w_dot = 2 * dKoefMMToPx;
var w_dist = 1 * dKoefMMToPx;
var _interf = this.m_oAutoShapesTrack;
var eps = 5 * dKoefMMToPx;
var _x = x - eps;
var _y = y - eps;
var _r = x + w + eps;
var _b = y + h + eps;
this._s();
_interf.AddRectDash(ctx, _x, _y, _r, _y, _x, _b, _r, _b, w_dot, w_dist);
this.ds();
return;
}
var bIsInt = this.m_bIntegerGrid;
if (!bIsInt)
this.SetIntegerGrid(true);
ctx.lineWidth = 1;
var w_dot = 2;
var w_dist = 2;
var eps = 5;
var _x = (this.m_oFullTransform.TransformPointX(x, y) >> 0) - eps + 0.5;
var _y = (this.m_oFullTransform.TransformPointY(x, y) >> 0) - eps + 0.5;
var _r = (this.m_oFullTransform.TransformPointX(x+w, y+h) >> 0) + eps + 0.5;
var _b = (this.m_oFullTransform.TransformPointY(x+w, y+h) >> 0) + eps + 0.5;
this._s();
for (var i = _x; i < _r; i += w_dist)
{
ctx.moveTo(i, _y);
i += w_dot;
if (i > _r)
i = _r;
ctx.lineTo(i, _y);
}
for (var i = _y; i < _b; i += w_dist)
{
ctx.moveTo(_r, i);
i += w_dot;
if (i > _b)
i = _b;
ctx.lineTo(_r, i);
}
for (var i = _r; i > _x; i -= w_dist)
{
ctx.moveTo(i, _b);
i -= w_dot;
if (i < _x)
i = _x;
ctx.lineTo(i, _b);
}
for (var i = _b; i > _y; i -= w_dist)
{
ctx.moveTo(_x, i);
i -= w_dot;
if (i < _y)
i = _y;
ctx.lineTo(_x, i);
}
this.ds();
if (!bIsInt)
this.SetIntegerGrid(false);
},
DrawEmptyTableLine : function(x1,y1,x2,y2)
{
if (!editor.isShowTableEmptyLine)
return;
var _x1 = this.m_oFullTransform.TransformPointX(x1,y1);
var _y1 = this.m_oFullTransform.TransformPointY(x1,y1);
var _x2 = this.m_oFullTransform.TransformPointX(x2,y2);
var _y2 = this.m_oFullTransform.TransformPointY(x2,y2);
_x1 = (_x1 >> 0) + 0.5;
_y1 = (_y1 >> 0) + 0.5;
_x2 = (_x2 >> 0) + 0.5;
_y2 = (_y2 >> 0) + 0.5;
this.p_color(138, 162, 191, 255);
var ctx = this.m_oContext;
if (_x1 != _x2 && _y1 != _y2)
{
// значит какой-то трансформ
var dKoefMMToPx = 1 / Math.max(this.m_oCoordTransform.sx, 0.001);
this.p_width(1000 * dKoefMMToPx);
this._s();
editor.WordControl.m_oDrawingDocument.AutoShapesTrack.AddLineDash(ctx, x1, y1, x2, y2, 2 * dKoefMMToPx, 2 * dKoefMMToPx);
this.ds();
return;
}
ctx.lineWidth = 1;
var bIsInt = this.m_bIntegerGrid;
if (!bIsInt)
this.SetIntegerGrid(true);
if (_x1 == _x2)
{
var _y = Math.min(_y1, _y2) + 0.5;
var _w1 = 2;
var _w2 = 2;
var _wmax = Math.max(_y1, _y2) - 0.5;
this._s();
while (true)
{
if (_y > _wmax)
break;
ctx.moveTo(_x1,_y);
_y+=_w1;
if (_y > _wmax)
{
ctx.lineTo(_x1,_y - _w1 + 1);
}
else
{
ctx.lineTo(_x1,_y);
}
_y+=_w2;
}
this.ds();
}
else if (_y1 == _y2)
{
var _x = Math.min(_x1, _x2) + 0.5;
var _w1 = 2;
var _w2 = 2;
var _wmax = Math.max(_x1, _x2) - 0.5;
this._s();
while (true)
{
if (_x > _wmax)
break;
ctx.moveTo(_x,_y1);
_x+=_w1;
if (_x > _wmax)
{
ctx.lineTo(_x - _w2 + 1,_y1);
}
else
{
ctx.lineTo(_x,_y1);
}
_x+=_w2;
}
this.ds();
}
else
{
// значит какой-то трансформ
this._s();
editor.WordControl.m_oDrawingDocument.AutoShapesTrack.AddLineDash(ctx, _x1, _y1, _x2, _y2, 2, 2);
this.ds();
}
if (!bIsInt)
this.SetIntegerGrid(false);
},
// smart methods for horizontal / vertical lines
drawHorLine : function(align, y, x, r, penW)
{
if (!this.m_bIntegerGrid)
{
this.p_width(penW * 1000);
this._s();
this._m(x, y);
this._l(r, y);
this.ds();
return;
}
var pen_w = parseInt((this.m_dDpiX * penW / g_dKoef_in_to_mm) + 0.5);
if (0 == pen_w)
pen_w = 1;
var _x = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5 - 0.5;
var _r = (this.m_oFullTransform.TransformPointX(r,y) >> 0) + 0.5 + 0.5;
var ctx = this.m_oContext;
ctx.setTransform(1,0,0,1,0,0);
ctx.lineWidth = pen_w;
switch (align)
{
case 0:
{
// top
var _top = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_x, _top + pen_w / 2 - 0.5);
ctx.lineTo(_r, _top + pen_w / 2 - 0.5);
ctx.stroke();
break;
}
case 1:
{
// center
var _center = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
if (0 == (pen_w % 2))
{
ctx.moveTo(_x, _center - 0.5);
ctx.lineTo(_r, _center - 0.5);
}
else
{
ctx.moveTo(_x, _center);
ctx.lineTo(_r, _center);
}
ctx.stroke();
break;
}
case 2:
{
// bottom
var _bottom = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_x, _bottom - pen_w / 2 + 0.5);
ctx.lineTo(_r, _bottom - pen_w / 2 + 0.5);
ctx.stroke();
break;
}
}
},
drawHorLine2 : function(align, y, x, r, penW)
{
if (!this.m_bIntegerGrid)
{
var _y1 = y - penW / 2;
var _y2 = _y1 + 2 * penW;
this.p_width(penW * 1000);
this._s();
this._m(x, _y1);
this._l(r, _y1);
this.ds();
this._s();
this._m(x, _y2);
this._l(r, _y2);
this.ds();
return;
}
var pen_w = ((this.m_dDpiX * penW / g_dKoef_in_to_mm) + 0.5) >> 0;
if (0 == pen_w)
pen_w = 1;
var _x = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5 - 0.5;
var _r = (this.m_oFullTransform.TransformPointX(r,y) >> 0) + 0.5 + 0.5;
var ctx = this.m_oContext;
ctx.lineWidth = pen_w;
switch (align)
{
case 0:
{
// top
var _top = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
var _pos1 = _top + pen_w / 2 - 0.5 - pen_w;
var _pos2 = _pos1 + pen_w * 2;
ctx.beginPath();
ctx.moveTo(_x, _pos1);
ctx.lineTo(_r, _pos1);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(_x, _pos2);
ctx.lineTo(_r, _pos2);
ctx.stroke();
break;
}
case 1:
{
// center
// TODO:
break;
}
case 2:
{
// bottom
// TODO:
break;
}
}
},
drawVerLine : function(align, x, y, b, penW)
{
if (!this.m_bIntegerGrid)
{
this.p_width(penW * 1000);
this._s();
this._m(x, y);
this._l(x, b);
this.ds();
return;
}
var pen_w = ((this.m_dDpiX * penW / g_dKoef_in_to_mm) + 0.5) >> 0;
if (0 == pen_w)
pen_w = 1;
var _y = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5 - 0.5;
var _b = (this.m_oFullTransform.TransformPointY(x,b) >> 0) + 0.5 + 0.5;
var ctx = this.m_oContext;
ctx.lineWidth = pen_w;
switch (align)
{
case 0:
{
// left
var _left = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_left + pen_w / 2 - 0.5, _y);
ctx.lineTo(_left + pen_w / 2 - 0.5, _b);
ctx.stroke();
break;
}
case 1:
{
// center
var _center = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
ctx.beginPath();
if (0 == (pen_w % 2))
{
ctx.moveTo(_center - 0.5, _y);
ctx.lineTo(_center - 0.5, _b);
}
else
{
ctx.moveTo(_center, _y);
ctx.lineTo(_center, _b);
}
ctx.stroke();
break;
}
case 2:
{
// right
var _right = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_right - pen_w / 2 + 0.5, _y);
ctx.lineTo(_right - pen_w / 2 + 0.5, _b);
ctx.stroke();
break;
}
}
},
// мега крутые функции для таблиц
drawHorLineExt : function(align, y, x, r, penW, leftMW, rightMW)
{
if (!this.m_bIntegerGrid)
{
this.p_width(penW * 1000);
this._s();
this._m(x, y);
this._l(r, y);
this.ds();
return;
}
var pen_w = Math.max(((this.m_dDpiX * penW / g_dKoef_in_to_mm) + 0.5) >> 0, 1);
var _x = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
var _r = (this.m_oFullTransform.TransformPointX(r,y) >> 0) + 0.5;
if (leftMW != 0)
{
var _center = _x;
var pen_mw = Math.max(((this.m_dDpiX * Math.abs(leftMW) * 2 / g_dKoef_in_to_mm) + 0.5) >> 0, 1);
if (leftMW < 0)
{
if ((pen_mw % 2) == 0)
{
_x = _center - (pen_mw / 2);
}
else
{
_x = _center - ((pen_mw / 2) >> 0);
}
}
else
{
if ((pen_mw % 2) == 0)
{
_x = _center + ((pen_mw / 2) - 1.0);
}
else
{
_x = _center + ((pen_mw / 2) >> 0);
}
}
}
if (rightMW != 0)
{
var _center = _r;
var pen_mw = Math.max(((this.m_dDpiX * Math.abs(rightMW) * 2 / g_dKoef_in_to_mm) + 0.5) >> 0, 1);
if (rightMW < 0)
{
if ((pen_mw % 2) == 0)
{
_r = _center - (pen_mw / 2);
}
else
{
_r = _center - ((pen_mw / 2) >> 0);
}
}
else
{
if ((pen_mw % 2) == 0)
{
_r = _center + (pen_mw / 2) - 1.0;
}
else
{
_r = _center + ((pen_mw / 2) >> 0);
}
}
}
var ctx = this.m_oContext;
ctx.lineWidth = pen_w;
_x -= 0.5;
_r += 0.5;
switch (align)
{
case 0:
{
// top
var _top = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_x, _top + pen_w / 2 - 0.5);
ctx.lineTo(_r, _top + pen_w / 2 - 0.5);
ctx.stroke();
break;
}
case 1:
{
// center
var _center = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
if (0 == (pen_w % 2))
{
ctx.moveTo(_x, _center - 0.5);
ctx.lineTo(_r, _center - 0.5);
}
else
{
ctx.moveTo(_x, _center);
ctx.lineTo(_r, _center);
}
ctx.stroke();
break;
}
case 2:
{
// bottom
var _bottom = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
ctx.beginPath();
ctx.moveTo(_x, _bottom - pen_w / 2 + 0.5);
ctx.lineTo(_r, _bottom - pen_w / 2 + 0.5);
ctx.stroke();
break;
}
}
},
rect : function(x,y,w,h)
{
var ctx = this.m_oContext;
ctx.beginPath();
if (this.m_bIntegerGrid)
{
var _x = (this.m_oFullTransform.TransformPointX(x,y) + 0.5) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(x,y) + 0.5) >> 0;
var _r = (this.m_oFullTransform.TransformPointX(x+w,y) + 0.5) >> 0;
var _b = (this.m_oFullTransform.TransformPointY(x,y+h) + 0.5) >> 0;
ctx.rect(_x, _y, _r - _x, _b - _y);
}
else
{
ctx.rect(x, y, w, h);
}
},
TableRect : function(x,y,w,h)
{
var ctx = this.m_oContext;
if (this.m_bIntegerGrid)
{
var _x = (this.m_oFullTransform.TransformPointX(x,y) >> 0) + 0.5;
var _y = (this.m_oFullTransform.TransformPointY(x,y) >> 0) + 0.5;
var _r = (this.m_oFullTransform.TransformPointX(x+w,y) >> 0) + 0.5;
var _b = (this.m_oFullTransform.TransformPointY(x,y+h) >> 0) + 0.5;
ctx.fillRect(_x - 0.5, _y - 0.5, _r - _x + 1, _b - _y + 1);
}
else
{
ctx.fillRect(x, y, w, h);
}
},
// функции клиппирования
AddClipRect : function(x, y, w, h)
{
//this.ClipManager.AddRect(x, y, w, h);
var __rect = new _rect();
__rect.x = x;
__rect.y = y;
__rect.w = w;
__rect.h = h;
this.GrState.AddClipRect(__rect);
},
RemoveClipRect : function()
{
//this.ClipManager.RemoveRect();
},
SetClip : function(r)
{
var ctx = this.m_oContext;
ctx.save();
ctx.beginPath();
if (!global_MatrixTransformer.IsIdentity(this.m_oTransform))
{
ctx.rect(r.x, r.y, r.w, r.h);
}
else
{
var _x = (this.m_oFullTransform.TransformPointX(r.x,r.y) + 1) >> 0;
var _y = (this.m_oFullTransform.TransformPointY(r.x,r.y) + 1) >> 0;
var _r = (this.m_oFullTransform.TransformPointX(r.x+r.w,r.y) - 1) >> 0;
var _b = (this.m_oFullTransform.TransformPointY(r.x,r.y+r.h) - 1) >> 0;
ctx.rect(_x, _y, _r - _x + 1, _b - _y + 1);
}
this.clip();
ctx.beginPath();
},
RemoveClip : function()
{
this.m_oContext.restore();
this.m_oContext.save();
if (this.m_oContext.globalAlpha != this.globalAlpha)
this.m_oContext.globalAlpha = this.globalAlpha;
},
drawCollaborativeChanges : function(x, y, w, h)
{
this.b_color1( 0, 255, 0, 64 );
this.rect( x, y, w, h );
this.df();
},
drawSearchResult : function(x, y, w, h)
{
this.b_color1( 255, 220, 0, 200 );
this.rect( x, y, w, h );
this.df();
},
drawFlowAnchor : function(x, y)
{
if (!window.g_flow_anchor || !window.g_flow_anchor.asc_complete || (!editor || !editor.ShowParaMarks))
return;
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(1,0,0,1,0,0);
}
var _x = this.m_oFullTransform.TransformPointX(x,y) >> 0;
var _y = this.m_oFullTransform.TransformPointY(x,y) >> 0;
this.m_oContext.drawImage(window.g_flow_anchor, _x, _y);
if (false === this.m_bIntegerGrid)
{
this.m_oContext.setTransform(this.m_oFullTransform.sx,this.m_oFullTransform.shy,this.m_oFullTransform.shx,
this.m_oFullTransform.sy,this.m_oFullTransform.tx,this.m_oFullTransform.ty);
}
},
SavePen : function()
{
this.GrState.SavePen();
},
RestorePen : function()
{
this.GrState.RestorePen();
},
SaveBrush : function()
{
this.GrState.SaveBrush();
},
RestoreBrush : function()
{
this.GrState.RestoreBrush();
},
SavePenBrush : function()
{
this.GrState.SavePenBrush();
},
RestorePenBrush : function()
{
this.GrState.RestorePenBrush();
},
SaveGrState : function()
{
this.GrState.SaveGrState();
},
RestoreGrState : function()
{
this.GrState.RestoreGrState();
},
StartClipPath : function()
{
},
EndClipPath : function()
{
this.m_oContext.clip();
},
StartCheckTableDraw : function()
{
if (!this.m_bIntegerGrid && global_MatrixTransformer.IsIdentity2(this.m_oTransform))
{
this.SaveGrState();
this.SetIntegerGrid(true);
return true;
}
return false;
},
EndCheckTableDraw : function(bIsRestore)
{
if (bIsRestore)
this.RestoreGrState();
},
SetTextClipRect : function(_l, _t, _r, _b)
{
this.TextClipRect = {
l : (_l * this.m_oCoordTransform.sx) >> 0,
t : (_t * this.m_oCoordTransform.sy) >> 0,
r : (_r * this.m_oCoordTransform.sx) >> 0,
b : (_b * this.m_oCoordTransform.sy) >> 0
};
}
}; | AddSmartRect in Graphics
git-svn-id: 9db5f3bf534fda1ae49cdb5ebc7e13fb9e7e48c1@57901 954022d7-b5bf-4e40-9824-e11837661b57
| Excel/model/DrawingObjects/Graphics.js | AddSmartRect in Graphics | <ide><path>xcel/model/DrawingObjects/Graphics.js
<ide> //this.ClipManager.RemoveRect();
<ide> },
<ide>
<add> AddSmartRect : function(x, y, w, h, pen_w)
<add> {
<add> if (!global_MatrixTransformer.IsIdentity2(this.m_oTransform))
<add> {
<add> this.ds();
<add> return;
<add> }
<add>
<add> var bIsSmartAttack = false;
<add> if (!this.m_bIntegerGrid)
<add> {
<add> this.SetIntegerGrid(true);
<add> bIsSmartAttack = true;
<add> }
<add>
<add> var _pen_w = (pen_w * this.m_oCoordTransform.sx + 0.5) >> 0;
<add> if (0 >= _pen_w)
<add> _pen_w = 1;
<add>
<add> this._s();
<add>
<add> if ((_pen_w & 0x01) == 0x01)
<add> {
<add> var _x = (this.m_oFullTransform.TransformPointX(x, y) >> 0) + 0.5;
<add> var _y = (this.m_oFullTransform.TransformPointY(x, y) >> 0) + 0.5;
<add> var _r = (this.m_oFullTransform.TransformPointX(x+w, y+h) >> 0) + 0.5;
<add> var _b = (this.m_oFullTransform.TransformPointY(x+w, y+h) >> 0) + 0.5;
<add>
<add> this.m_oContext.rect(_x, _y, _r - _x, _b - _y);
<add> }
<add> else
<add> {
<add> var _x = (this.m_oFullTransform.TransformPointX(x, y) + 0.5) >> 0;
<add> var _y = (this.m_oFullTransform.TransformPointY(x, y) + 0.5) >> 0;
<add> var _r = (this.m_oFullTransform.TransformPointX(x+w, y+h) + 0.5) >> 0;
<add> var _b = (this.m_oFullTransform.TransformPointY(x+w, y+h) + 0.5) >> 0;
<add>
<add> this.m_oContext.rect(_x, _y, _r - _x, _b - _y);
<add> }
<add>
<add> this.m_oContext.lineWidth = _pen_w;
<add> this.ds();
<add>
<add> if (bIsSmartAttack)
<add> {
<add> this.SetIntegerGrid(false);
<add> }
<add> },
<add>
<ide> SetClip : function(r)
<ide> {
<ide> var ctx = this.m_oContext; |
|
JavaScript | agpl-3.0 | 12100f718f9aa5f20a684a470ebef68e7d6d1c1d | 0 | anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,ronaldpereira/WoWAnalyzer,fyruna/WoWAnalyzer,sMteX/WoWAnalyzer,FaideWW/WoWAnalyzer,ronaldpereira/WoWAnalyzer,yajinni/WoWAnalyzer,enragednuke/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,enragednuke/WoWAnalyzer,fyruna/WoWAnalyzer,yajinni/WoWAnalyzer,hasseboulen/WoWAnalyzer,hasseboulen/WoWAnalyzer,enragednuke/WoWAnalyzer,yajinni/WoWAnalyzer,Juko8/WoWAnalyzer,anom0ly/WoWAnalyzer,FaideWW/WoWAnalyzer,FaideWW/WoWAnalyzer,Juko8/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,hasseboulen/WoWAnalyzer,fyruna/WoWAnalyzer,sMteX/WoWAnalyzer,yajinni/WoWAnalyzer,ronaldpereira/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer | import CoreCombatLogParser from 'Parser/Core/CombatLogParser';
import DamageDone from 'Parser/Core/Modules/DamageDone';
// Core
import HealingDone from './Modules/Core/HealingDone';
import DamageTaken from './Modules/Core/DamageTaken';
import HealingReceived from './Modules/Core/HealingReceived';
import Stagger from './Modules/Core/Stagger';
// Spells
import IronSkinBrew from './Modules/Spells/IronSkinBrew';
import BlackoutCombo from './Modules/Spells/BlackoutCombo';
// Features
import Abilities from './Modules/Features/Abilities';
import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';
// Items
import T20_2pc from './Modules/Items/T20_2pc';
import T20_4pc from './Modules/Items/T20_4pc';
class CombatLogParser extends CoreCombatLogParser {
static specModules = {
// Core
healingDone: [HealingDone, { showStatistic: true }],
healingReceived: HealingReceived,
damageTaken: [DamageTaken, { showStatistic: true }],
stagger: Stagger,
damageDone: [DamageDone, { showStatistic: true }],
// Features
alwaysBeCasting: AlwaysBeCasting,
abilities: Abilities,
// Spells
ironSkinBrew: IronSkinBrew,
blackoutCombo: BlackoutCombo,
// Items
t20_2pc: T20_2pc,
t20_4pc: T20_4pc,
};
}
export default CombatLogParser;
| src/Parser/Monk/Brewmaster/CombatLogParser.js | import CoreCombatLogParser from 'Parser/Core/CombatLogParser';
import DamageDone from 'Parser/Core/Modules/DamageDone';
// Core
import HealingDone from './Modules/Core/HealingDone';
import DamageTaken from './Modules/Core/DamageTaken';
import HealingReceived from './Modules/Core/HealingReceived';
import Stagger from './Modules/Core/Stagger';
// Spells
import IronSkinBrew from './Modules/Spells/IronSkinBrew';
import BlackoutCombo from './Modules/Spells/BlackoutCombo';
// Features
import Abilities from './Modules/Features/Abilities';
import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';
// Items
import T20_2pc from './Modules/Items/T20_2pc';
import T20_4pc from './Modules/Items/T20_4pc';
class CombatLogParser extends CoreCombatLogParser {
static specModules = {
// Core
healingDone: [HealingDone, { showStatistic: true }],
healingReceived: HealingReceived,
damageTaken: [DamageTaken, { showStatistic: true }],
stagger: Stagger,
damageDone: [DamageDone, { showStatistic: true }],
// Features
alwaysBeCasting: AlwaysBeCasting,
abilities: Abilities,
// Spells
ironSkinBrew: IronSkinBrew,
blackoutCombo: BlackoutCombo,
// Items
t20_2pc: T20_2pc,
t20_4pc: T20_4pc,
};
}
export default CombatLogParser;
| Reformat Brewmaster CombatLogParser
| src/Parser/Monk/Brewmaster/CombatLogParser.js | Reformat Brewmaster CombatLogParser | <ide><path>rc/Parser/Monk/Brewmaster/CombatLogParser.js
<ide> import CoreCombatLogParser from 'Parser/Core/CombatLogParser';
<ide> import DamageDone from 'Parser/Core/Modules/DamageDone';
<del>
<ide> // Core
<ide> import HealingDone from './Modules/Core/HealingDone';
<ide> import DamageTaken from './Modules/Core/DamageTaken';
<ide> import HealingReceived from './Modules/Core/HealingReceived';
<ide> import Stagger from './Modules/Core/Stagger';
<del>
<ide> // Spells
<ide> import IronSkinBrew from './Modules/Spells/IronSkinBrew';
<ide> import BlackoutCombo from './Modules/Spells/BlackoutCombo';
<del>
<del>
<ide> // Features
<ide> import Abilities from './Modules/Features/Abilities';
<ide> import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';
<del>
<ide> // Items
<ide> import T20_2pc from './Modules/Items/T20_2pc';
<ide> import T20_4pc from './Modules/Items/T20_4pc'; |
|
Java | apache-2.0 | 46ec994177fc53dc2ab48689785a8c0e255dbd09 | 0 | stagemonitor/stagemonitor,stagemonitor/stagemonitor,stagemonitor/stagemonitor,stagemonitor/stagemonitor | package org.stagemonitor.web.tracing;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.InterceptingHttpAccessor;
import org.stagemonitor.core.Stagemonitor;
import org.stagemonitor.core.instrument.StagemonitorByteBuddyTransformer;
import org.stagemonitor.requestmonitor.ExternalHttpRequest;
import org.stagemonitor.requestmonitor.RequestMonitorPlugin;
import org.stagemonitor.requestmonitor.profiler.Profiler;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import io.opentracing.Span;
import io.opentracing.propagation.Format;
import io.opentracing.propagation.TextMap;
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class SpringRestTemplateContextPropagatingTransformer extends StagemonitorByteBuddyTransformer {
@Override
protected ElementMatcher.Junction<TypeDescription> getTypeMatcher() {
return named("org.springframework.http.client.support.InterceptingHttpAccessor");
}
@Override
protected ElementMatcher.Junction<MethodDescription.InDefinedShape> getMethodElementMatcher() {
return isConstructor();
}
@Advice.OnMethodExit(inline = false)
public static void onInterceptingHttpAccessorCreated(@Advice.This Object httpAccessor) {
final RequestMonitorPlugin requestMonitorPlugin = Stagemonitor.getPlugin(RequestMonitorPlugin.class);
((InterceptingHttpAccessor) httpAccessor).getInterceptors().add(new SpringRestTemplateContextPropagatingInterceptor(requestMonitorPlugin));
}
public static class SpringRestTemplateContextPropagatingInterceptor implements ClientHttpRequestInterceptor {
private final RequestMonitorPlugin requestMonitorPlugin;
private SpringRestTemplateContextPropagatingInterceptor(RequestMonitorPlugin requestMonitorPlugin) {
this.requestMonitorPlugin = requestMonitorPlugin;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
final Span span = new ExternalHttpRequest(requestMonitorPlugin.getTracer(), request.getMethod().toString(), request.getURI().toString(), request.getURI().getHost(), request.getURI().getPort()).createSpan();
try {
Profiler.start(request.getMethod().toString() + " " + request.getURI() + " ");
requestMonitorPlugin.getTracer().inject(span.context(), Format.Builtin.HTTP_HEADERS, new SpringHttpRequestInjectAdapter(request));
return execution.execute(request, body);
} finally {
Profiler.stop();
span.finish();
}
}
}
private static class SpringHttpRequestInjectAdapter implements TextMap {
private final HttpRequest httpRequest;
private SpringHttpRequestInjectAdapter(HttpRequest httpRequest) {
this.httpRequest = httpRequest;
}
@Override
public Iterator<Map.Entry<String, String>> iterator() {
throw new UnsupportedOperationException("SpringHttpRequestInjectAdapter should only be used with Tracer.inject()");
}
@Override
public void put(String key, String value) {
httpRequest.getHeaders().add(key, value);
}
}
}
| stagemonitor-web/src/main/java/org/stagemonitor/web/tracing/SpringRestTemplateContextPropagatingTransformer.java | package org.stagemonitor.web.tracing;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.InterceptingHttpAccessor;
import org.stagemonitor.core.Stagemonitor;
import org.stagemonitor.core.instrument.StagemonitorByteBuddyTransformer;
import org.stagemonitor.requestmonitor.ExternalHttpRequest;
import org.stagemonitor.requestmonitor.RequestMonitorPlugin;
import org.stagemonitor.requestmonitor.profiler.Profiler;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import io.opentracing.Span;
import io.opentracing.propagation.Format;
import io.opentracing.propagation.TextMap;
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.named;
public class SpringRestTemplateContextPropagatingTransformer extends StagemonitorByteBuddyTransformer {
@Override
protected ElementMatcher.Junction<TypeDescription> getTypeMatcher() {
return named("org.springframework.http.client.support.InterceptingHttpAccessor");
}
@Override
protected ElementMatcher.Junction<MethodDescription.InDefinedShape> getMethodElementMatcher() {
return isConstructor();
}
@Advice.OnMethodExit(inline = false)
public static void onInterceptingHttpAccessorCreated(@Advice.This InterceptingHttpAccessor httpAccessor) {
final RequestMonitorPlugin requestMonitorPlugin = Stagemonitor.getPlugin(RequestMonitorPlugin.class);
httpAccessor.getInterceptors().add(new SpringRestTemplateContextPropagatingInterceptor(requestMonitorPlugin));
}
public static class SpringRestTemplateContextPropagatingInterceptor implements ClientHttpRequestInterceptor {
private final RequestMonitorPlugin requestMonitorPlugin;
private SpringRestTemplateContextPropagatingInterceptor(RequestMonitorPlugin requestMonitorPlugin) {
this.requestMonitorPlugin = requestMonitorPlugin;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
final Span span = new ExternalHttpRequest(requestMonitorPlugin.getTracer(), request.getMethod().toString(), request.getURI().toString(), request.getURI().getHost(), request.getURI().getPort()).createSpan();
try {
Profiler.start(request.getMethod().toString() + " " + request.getURI() + " ");
requestMonitorPlugin.getTracer().inject(span.context(), Format.Builtin.HTTP_HEADERS, new SpringHttpRequestInjectAdapter(request));
return execution.execute(request, body);
} finally {
Profiler.stop();
span.finish();
}
}
}
private static class SpringHttpRequestInjectAdapter implements TextMap {
private final HttpRequest httpRequest;
private SpringHttpRequestInjectAdapter(HttpRequest httpRequest) {
this.httpRequest = httpRequest;
}
@Override
public Iterator<Map.Entry<String, String>> iterator() {
throw new UnsupportedOperationException("SpringHttpRequestInjectAdapter should only be used with Tracer.inject()");
}
@Override
public void put(String key, String value) {
httpRequest.getHeaders().add(key, value);
}
}
}
| Fix NoClassDefFoundError in SpringRestTemplateContextPropagatingTransformer
see https://github.com/raphw/byte-buddy/issues/290
| stagemonitor-web/src/main/java/org/stagemonitor/web/tracing/SpringRestTemplateContextPropagatingTransformer.java | Fix NoClassDefFoundError in SpringRestTemplateContextPropagatingTransformer | <ide><path>tagemonitor-web/src/main/java/org/stagemonitor/web/tracing/SpringRestTemplateContextPropagatingTransformer.java
<ide> }
<ide>
<ide> @Advice.OnMethodExit(inline = false)
<del> public static void onInterceptingHttpAccessorCreated(@Advice.This InterceptingHttpAccessor httpAccessor) {
<add> public static void onInterceptingHttpAccessorCreated(@Advice.This Object httpAccessor) {
<ide> final RequestMonitorPlugin requestMonitorPlugin = Stagemonitor.getPlugin(RequestMonitorPlugin.class);
<del> httpAccessor.getInterceptors().add(new SpringRestTemplateContextPropagatingInterceptor(requestMonitorPlugin));
<add> ((InterceptingHttpAccessor) httpAccessor).getInterceptors().add(new SpringRestTemplateContextPropagatingInterceptor(requestMonitorPlugin));
<ide> }
<ide>
<ide> public static class SpringRestTemplateContextPropagatingInterceptor implements ClientHttpRequestInterceptor { |
|
Java | apache-2.0 | acfae4606d091e4480534131d70ed557415d6a02 | 0 | SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java | /*
* Copyright 2021, TeamDev. 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
*
* 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.testing.server.blackbox;
import io.spine.client.Client;
import io.spine.core.TenantId;
import io.spine.testing.client.TestActorRequestFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Creates {@link Client}s for a particular {@link BlackBox} instance.
*/
public final class BlackBoxClients {
private final BlackBox blackBox;
private final ClientFactory supplier;
/**
* Creates a new instance of this factory.
*
* @param blackBox
* the instance to connect to
* @param supplier
* supplier of {@code Client} instances
*/
BlackBoxClients(BlackBox blackBox, ClientFactory supplier) {
this.supplier = supplier;
this.blackBox = blackBox;
}
/**
* Creates a new {@code Client} with the specified {@code TenantId}.
*
* <p>This method must be called to connect only to the multi-tenant Bounded Contexts.
*
* @return a new instance of {@code Client}
* @throws IllegalStateException
* if the method is called for a single-tenant Context
*/
public Client create(TenantId tenant) {
checkNotNull(tenant);
Client result = supplier.create(tenant);
return result;
}
/**
* Creates a new {@code Client} with the {@code TenantId} which corresponds to
* the <b>current</b> setting of the target {@code BlackBox}.
*
* @return a new instance of {@code Client}
*/
@SuppressWarnings("TestOnlyProblems") /* `TestActorRequestFactory` is not test-only. */
public Client withMatchingTenant() {
TestActorRequestFactory requests = blackBox.requestFactory();
@Nullable TenantId tenantId = requests.tenantId();
Client result = supplier.create(tenantId);
return result;
}
}
| testutil-server/src/main/java/io/spine/testing/server/blackbox/BlackBoxClients.java | /*
* Copyright 2021, TeamDev. 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
*
* 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.testing.server.blackbox;
import io.spine.client.Client;
import io.spine.core.TenantId;
import io.spine.testing.client.TestActorRequestFactory;
import org.checkerframework.checker.nullness.qual.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Creates {@link Client}s to a particular {@link BlackBox} instance.
*/
public final class BlackBoxClients {
private final BlackBox blackBox;
private final ClientFactory supplier;
/**
* Creates a new instance of this factory.
*
* @param blackBox
* the instance to connect to
* @param supplier
* supplier of {@code Client} instances
*/
BlackBoxClients(BlackBox blackBox, ClientFactory supplier) {
this.supplier = supplier;
this.blackBox = blackBox;
}
/**
* Creates a new {@code Client} with the specified {@code TenantId}.
*
* <p>This method must be called to connect only to the multi-tenant Bounded Contexts.
*
* @return a new instance of {@code Client}
* @throws IllegalStateException
* if the method is called for a single-tenant Context
*/
public Client create(TenantId tenant) {
checkNotNull(tenant);
Client result = supplier.create(tenant);
return result;
}
/**
* Creates a new {@code Client} with the {@code TenantId} which corresponds to
* the <b>current</b> setting of the target {@code BlackBox}.
*
* @return a new instance of {@code Client}
*/
@SuppressWarnings("TestOnlyProblems") /* `TestActorRequestFactory` is not test-only. */
public Client withMatchingTenant() {
TestActorRequestFactory requests = blackBox.requestFactory();
@Nullable TenantId tenantId = requests.tenantId();
Client result = supplier.create(tenantId);
return result;
}
}
| Use a more appropriate preposition.
| testutil-server/src/main/java/io/spine/testing/server/blackbox/BlackBoxClients.java | Use a more appropriate preposition. | <ide><path>estutil-server/src/main/java/io/spine/testing/server/blackbox/BlackBoxClients.java
<ide> import static com.google.common.base.Preconditions.checkNotNull;
<ide>
<ide> /**
<del> * Creates {@link Client}s to a particular {@link BlackBox} instance.
<add> * Creates {@link Client}s for a particular {@link BlackBox} instance.
<ide> */
<ide> public final class BlackBoxClients {
<ide> |
|
Java | apache-2.0 | 1858aa796af991ebfe9919f7ad04019288a80263 | 0 | ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,jerome79/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,jerome79/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,nssales/OG-Platform | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.master.position.impl;
import java.util.List;
import java.util.Map;
import com.opengamma.core.change.AggregatingChangeManager;
import com.opengamma.core.change.ChangeManager;
import com.opengamma.id.ObjectId;
import com.opengamma.id.ObjectIdentifiable;
import com.opengamma.id.UniqueId;
import com.opengamma.id.UniqueIdSchemeDelegator;
import com.opengamma.id.VersionCorrection;
import com.opengamma.master.position.ManageableTrade;
import com.opengamma.master.position.PositionDocument;
import com.opengamma.master.position.PositionHistoryRequest;
import com.opengamma.master.position.PositionHistoryResult;
import com.opengamma.master.position.PositionMaster;
import com.opengamma.master.position.PositionSearchRequest;
import com.opengamma.master.position.PositionSearchResult;
import com.opengamma.util.ArgumentChecker;
/**
* A master of positions that uses the scheme of the unique identifier to determine which
* underlying master should handle the request.
* <p>
* If no scheme-specific handler has been registered, a default is used.
* <p>
* Change events are aggregated from the different masters and presented through a single change manager.
*/
public class DelegatingPositionMaster extends UniqueIdSchemeDelegator<PositionMaster> implements PositionMaster {
/**
* The change manager.
*/
private final ChangeManager _changeManager;
/**
* Creates an instance specifying the default delegate.
*
* @param defaultMaster the master to use when no scheme matches, not null
*/
public DelegatingPositionMaster(PositionMaster defaultMaster) {
super(defaultMaster);
_changeManager = defaultMaster.changeManager();
}
/**
* Creates an instance specifying the default delegate.
*
* @param defaultMaster the master to use when no scheme matches, not null
* @param schemePrefixToMasterMap the map of masters by scheme to switch on, not null
*/
public DelegatingPositionMaster(PositionMaster defaultMaster, Map<String, PositionMaster> schemePrefixToMasterMap) {
super(defaultMaster, schemePrefixToMasterMap);
AggregatingChangeManager changeManager = new AggregatingChangeManager();
// REVIEW jonathan 2012-08-03 -- this assumes that the delegating master lasts for the lifetime of the engine as we
// never detach from the underlying change managers.
changeManager.addChangeManager(defaultMaster.changeManager());
for (PositionMaster master : schemePrefixToMasterMap.values()) {
changeManager.addChangeManager(master.changeManager());
}
_changeManager = changeManager;
}
//-------------------------------------------------------------------------
@Override
public PositionHistoryResult history(PositionHistoryRequest request) {
ArgumentChecker.notNull(request, "request");
return chooseDelegate(request.getObjectId().getScheme()).history(request);
}
@Override
public PositionSearchResult search(PositionSearchRequest request) {
ArgumentChecker.notNull(request, "request");
List<ObjectId> ids = request.getPositionObjectIds();
if (ids == null || ids.isEmpty()) {
return getDefaultDelegate().search(request);
}
return chooseDelegate(ids.get(0).getScheme()).search(request);
}
@Override
public PositionDocument get(UniqueId uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
return chooseDelegate(uniqueId.getScheme()).get(uniqueId);
}
@Override
public PositionDocument get(ObjectIdentifiable objectId, VersionCorrection versionCorrection) {
ArgumentChecker.notNull(objectId, "objectId");
ArgumentChecker.notNull(versionCorrection, "versionCorrection");
return chooseDelegate(objectId.getObjectId().getScheme()).get(objectId, versionCorrection);
}
@Override
public PositionDocument add(PositionDocument document) {
ArgumentChecker.notNull(document, "document");
return getDefaultDelegate().add(document);
}
@Override
public PositionDocument update(PositionDocument document) {
ArgumentChecker.notNull(document, "document");
return chooseDelegate(document.getObjectId().getScheme()).update(document);
}
@Override
public void remove(UniqueId uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
chooseDelegate(uniqueId.getScheme()).remove(uniqueId);
}
@Override
public PositionDocument correct(PositionDocument document) {
ArgumentChecker.notNull(document, "document");
return chooseDelegate(document.getObjectId().getScheme()).correct(document);
}
@Override
public ManageableTrade getTrade(UniqueId uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
return chooseDelegate(uniqueId.getScheme()).getTrade(uniqueId);
}
@Override
public ChangeManager changeManager() {
return _changeManager;
}
}
| projects/OG-Master/src/com/opengamma/master/position/impl/DelegatingPositionMaster.java | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.master.position.impl;
import java.util.List;
import java.util.Map;
import com.opengamma.core.change.AggregatingChangeManager;
import com.opengamma.core.change.ChangeManager;
import com.opengamma.id.*;
import com.opengamma.master.position.*;
/**
* A master of positions that uses the scheme of the unique identifier to determine which
* underlying master should handle the request.
* <p>
* If no scheme-specific handler has been registered, a default is used.
* <p>
* Change events are aggregated from the different masters and presented through a single change manager.
*/
public class DelegatingPositionMaster extends UniqueIdSchemeDelegator<PositionMaster> implements PositionMaster {
/**
* The change manager.
*/
private final ChangeManager _changeManager;
/**
* Creates an instance specifying the default delegate.
*
* @param defaultMaster the master to use when no scheme matches, not null
*/
public DelegatingPositionMaster(PositionMaster defaultMaster) {
super(defaultMaster);
_changeManager = defaultMaster.changeManager();
}
/**
* Creates an instance specifying the default delegate.
*
* @param defaultMaster the master to use when no scheme matches, not null
* @param schemePrefixToMasterMap the map of masters by scheme to switch on, not null
*/
public DelegatingPositionMaster(PositionMaster defaultMaster, Map<String, PositionMaster> schemePrefixToMasterMap) {
super(defaultMaster, schemePrefixToMasterMap);
AggregatingChangeManager changeManager = new AggregatingChangeManager();
// REVIEW jonathan 2011-08-03 -- this assumes that the delegating master lasts for the lifetime of the engine as we
// never detach from the underlying change managers.
changeManager.addChangeManager(defaultMaster.changeManager());
for (PositionMaster master : schemePrefixToMasterMap.values()) {
changeManager.addChangeManager(master.changeManager());
}
_changeManager = changeManager;
}
@Override
public PositionHistoryResult history(PositionHistoryRequest request) {
return chooseDelegate(request.getObjectId().getScheme()).history(request);
}
@Override
public PositionSearchResult search(PositionSearchRequest request) {
List<ObjectId> ids = request.getPositionObjectIds();
if (ids.size() > 0) {
return chooseDelegate(ids.get(0).getScheme()).search(request);
} else {
return new PositionSearchResult();
}
}
@Override
public PositionDocument get(UniqueId uniqueId) {
return chooseDelegate(uniqueId.getScheme()).get(uniqueId);
}
@Override
public PositionDocument get(ObjectIdentifiable objectId, VersionCorrection versionCorrection) {
return chooseDelegate(objectId.getObjectId().getScheme()).get(objectId, versionCorrection);
}
@Override
public PositionDocument add(PositionDocument document) {
throw new UnsupportedOperationException("The delegationg position master is read only");
}
@Override
public PositionDocument update(PositionDocument document) {
throw new UnsupportedOperationException("The delegationg position master is read only");
}
@Override
public void remove(UniqueId uniqueId) {
throw new UnsupportedOperationException("The delegationg position master is read only");
}
@Override
public PositionDocument correct(PositionDocument document) {
throw new UnsupportedOperationException("The delegationg position master is read only");
}
@Override
public ManageableTrade getTrade(UniqueId uniqueId) {
return chooseDelegate(uniqueId.getScheme()).getTrade(uniqueId);
}
@Override
public ChangeManager changeManager() {
return _changeManager;
}
}
| Extend functionality of delegating position master
| projects/OG-Master/src/com/opengamma/master/position/impl/DelegatingPositionMaster.java | Extend functionality of delegating position master | <ide><path>rojects/OG-Master/src/com/opengamma/master/position/impl/DelegatingPositionMaster.java
<ide>
<ide> import com.opengamma.core.change.AggregatingChangeManager;
<ide> import com.opengamma.core.change.ChangeManager;
<del>import com.opengamma.id.*;
<del>import com.opengamma.master.position.*;
<add>import com.opengamma.id.ObjectId;
<add>import com.opengamma.id.ObjectIdentifiable;
<add>import com.opengamma.id.UniqueId;
<add>import com.opengamma.id.UniqueIdSchemeDelegator;
<add>import com.opengamma.id.VersionCorrection;
<add>import com.opengamma.master.position.ManageableTrade;
<add>import com.opengamma.master.position.PositionDocument;
<add>import com.opengamma.master.position.PositionHistoryRequest;
<add>import com.opengamma.master.position.PositionHistoryResult;
<add>import com.opengamma.master.position.PositionMaster;
<add>import com.opengamma.master.position.PositionSearchRequest;
<add>import com.opengamma.master.position.PositionSearchResult;
<add>import com.opengamma.util.ArgumentChecker;
<ide>
<ide> /**
<ide> * A master of positions that uses the scheme of the unique identifier to determine which
<ide> public DelegatingPositionMaster(PositionMaster defaultMaster, Map<String, PositionMaster> schemePrefixToMasterMap) {
<ide> super(defaultMaster, schemePrefixToMasterMap);
<ide> AggregatingChangeManager changeManager = new AggregatingChangeManager();
<del>
<del> // REVIEW jonathan 2011-08-03 -- this assumes that the delegating master lasts for the lifetime of the engine as we
<add>
<add> // REVIEW jonathan 2012-08-03 -- this assumes that the delegating master lasts for the lifetime of the engine as we
<ide> // never detach from the underlying change managers.
<ide> changeManager.addChangeManager(defaultMaster.changeManager());
<ide> for (PositionMaster master : schemePrefixToMasterMap.values()) {
<ide> _changeManager = changeManager;
<ide> }
<ide>
<add> //-------------------------------------------------------------------------
<ide> @Override
<ide> public PositionHistoryResult history(PositionHistoryRequest request) {
<add> ArgumentChecker.notNull(request, "request");
<ide> return chooseDelegate(request.getObjectId().getScheme()).history(request);
<ide> }
<ide>
<ide> @Override
<ide> public PositionSearchResult search(PositionSearchRequest request) {
<add> ArgumentChecker.notNull(request, "request");
<ide> List<ObjectId> ids = request.getPositionObjectIds();
<del> if (ids.size() > 0) {
<del> return chooseDelegate(ids.get(0).getScheme()).search(request);
<del> } else {
<del> return new PositionSearchResult();
<add> if (ids == null || ids.isEmpty()) {
<add> return getDefaultDelegate().search(request);
<ide> }
<add> return chooseDelegate(ids.get(0).getScheme()).search(request);
<ide> }
<ide>
<ide> @Override
<ide> public PositionDocument get(UniqueId uniqueId) {
<add> ArgumentChecker.notNull(uniqueId, "uniqueId");
<ide> return chooseDelegate(uniqueId.getScheme()).get(uniqueId);
<ide> }
<ide>
<ide> @Override
<ide> public PositionDocument get(ObjectIdentifiable objectId, VersionCorrection versionCorrection) {
<add> ArgumentChecker.notNull(objectId, "objectId");
<add> ArgumentChecker.notNull(versionCorrection, "versionCorrection");
<ide> return chooseDelegate(objectId.getObjectId().getScheme()).get(objectId, versionCorrection);
<ide> }
<ide>
<ide> @Override
<ide> public PositionDocument add(PositionDocument document) {
<del> throw new UnsupportedOperationException("The delegationg position master is read only");
<add> ArgumentChecker.notNull(document, "document");
<add> return getDefaultDelegate().add(document);
<ide> }
<ide>
<ide> @Override
<ide> public PositionDocument update(PositionDocument document) {
<del> throw new UnsupportedOperationException("The delegationg position master is read only");
<add> ArgumentChecker.notNull(document, "document");
<add> return chooseDelegate(document.getObjectId().getScheme()).update(document);
<ide> }
<ide>
<ide> @Override
<ide> public void remove(UniqueId uniqueId) {
<del> throw new UnsupportedOperationException("The delegationg position master is read only");
<add> ArgumentChecker.notNull(uniqueId, "uniqueId");
<add> chooseDelegate(uniqueId.getScheme()).remove(uniqueId);
<ide> }
<ide>
<ide> @Override
<ide> public PositionDocument correct(PositionDocument document) {
<del> throw new UnsupportedOperationException("The delegationg position master is read only");
<add> ArgumentChecker.notNull(document, "document");
<add> return chooseDelegate(document.getObjectId().getScheme()).correct(document);
<ide> }
<ide>
<ide> @Override
<ide> public ManageableTrade getTrade(UniqueId uniqueId) {
<add> ArgumentChecker.notNull(uniqueId, "uniqueId");
<ide> return chooseDelegate(uniqueId.getScheme()).getTrade(uniqueId);
<ide> }
<ide> |
|
Java | apache-2.0 | c34ec2457f3ddb655554533fdf804020bf9e82c5 | 0 | javamelody/javamelody,javamelody/javamelody,javamelody/javamelody | /*
* Copyright 2008-2010 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
/**
* Test unitaire de la classe StrutsInterceptor.
* @author Emeric Vernat
*/
public class TestStrutsInterceptor {
/** Check. */
@Before
public void setUp() {
Utils.initialize();
}
/** Test. */
@Test
public void testGetStrutsCounter() {
assertNotNull("getStrutsCounter", MonitoringProxy.getStrutsCounter());
}
/** Test.
* @throws Exception e */
@Test
public void testStruts() throws Exception { // NOPMD
final Counter strutsCounter = MonitoringProxy.getStrutsCounter();
strutsCounter.clear();
final StrutsInterceptor strutsInterceptor = new StrutsInterceptor();
final ActionInvocation invocation = createNiceMock(ActionInvocation.class);
final ActionContext context = new ActionContext(new HashMap<Object, Object>());
context.setName("test.action");
expect(invocation.getInvocationContext()).andReturn(context).anyTimes();
replay(invocation);
strutsCounter.setDisplayed(false);
strutsInterceptor.intercept(invocation);
final String requestsCount = "requestsCount";
assertSame(requestsCount, 0, strutsCounter.getRequestsCount());
strutsCounter.setDisplayed(true);
strutsInterceptor.intercept(invocation);
assertSame(requestsCount, 1, strutsCounter.getRequestsCount());
verify(invocation);
final ActionInvocation invocation2 = createNiceMock(ActionInvocation.class);
final ActionContext context2 = new ActionContext(new HashMap<Object, Object>());
context2.setName("test2.action");
expect(invocation2.getInvocationContext()).andReturn(context2).anyTimes();
expect(invocation2.invoke()).andThrow(new UnknownError("test d'erreur")).anyTimes();
replay(invocation2);
try {
strutsInterceptor.intercept(invocation2);
} catch (final UnknownError e) {
assertNotNull("ok", e);
}
assertSame(requestsCount, 2, strutsCounter.getRequestsCount());
verify(invocation2);
}
}
| javamelody-core/src/test/java/net/bull/javamelody/TestStrutsInterceptor.java | /*
* Copyright 2008-2010 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.util.HashMap;
import org.junit.Before;
import org.junit.Test;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
/**
* Test unitaire de la classe StrutsInterceptor.
* @author Emeric Vernat
*/
public class TestStrutsInterceptor {
/** Check. */
@Before
public void setUp() {
Utils.initialize();
}
/** Test. */
@Test
public void testGetStrutsCounter() {
assertNotNull("getStrutsCounter", MonitoringProxy.getStrutsCounter());
}
/** Test.
* @throws Exception e */
@Test
public void testStruts() throws Exception { // NOPMD
final Counter strutsCounter = MonitoringProxy.getStrutsCounter();
strutsCounter.clear();
final StrutsInterceptor strutsInterceptor = new StrutsInterceptor();
final ActionInvocation invocation = createNiceMock(ActionInvocation.class);
final ActionContext context = new ActionContext(new HashMap<Object, Object>());
context.setName("test.action");
expect(invocation.getInvocationContext()).andReturn(context).anyTimes();
replay(invocation);
strutsCounter.setDisplayed(false);
strutsInterceptor.intercept(invocation);
final String requestsCount = "requestsCount";
assertSame(requestsCount, 0, strutsCounter.getRequestsCount());
strutsCounter.setDisplayed(true);
strutsInterceptor.intercept(invocation);
assertSame(requestsCount, 1, strutsCounter.getRequestsCount());
verify(invocation);
final ActionInvocation invocation2 = createNiceMock(ActionInvocation.class);
final ActionContext context2 = new ActionContext(new HashMap<Object, Object>());
context2.setName("test2.action");
expect(invocation2.getInvocationContext()).andReturn(context2).anyTimes();
expect(invocation2.invoke()).andThrow(new IllegalStateException("test d'erreur"))
.anyTimes();
replay(invocation2);
try {
strutsInterceptor.intercept(invocation2);
} catch (final IllegalStateException e) {
assertNotNull("ok", e);
}
assertSame(requestsCount, 2, strutsCounter.getRequestsCount());
verify(invocation2);
}
}
| compléments tests unitaires | javamelody-core/src/test/java/net/bull/javamelody/TestStrutsInterceptor.java | compléments tests unitaires | <ide><path>avamelody-core/src/test/java/net/bull/javamelody/TestStrutsInterceptor.java
<ide> final ActionContext context2 = new ActionContext(new HashMap<Object, Object>());
<ide> context2.setName("test2.action");
<ide> expect(invocation2.getInvocationContext()).andReturn(context2).anyTimes();
<del> expect(invocation2.invoke()).andThrow(new IllegalStateException("test d'erreur"))
<del> .anyTimes();
<add> expect(invocation2.invoke()).andThrow(new UnknownError("test d'erreur")).anyTimes();
<ide>
<ide> replay(invocation2);
<ide> try {
<ide> strutsInterceptor.intercept(invocation2);
<del> } catch (final IllegalStateException e) {
<add> } catch (final UnknownError e) {
<ide> assertNotNull("ok", e);
<ide> }
<ide> assertSame(requestsCount, 2, strutsCounter.getRequestsCount()); |
|
Java | mit | error: pathspec 'data_structures/Queue/Java/Queue.java' did not match any file(s) known to git
| 2225cfe10947f1c9396fa3694fdeb74ab0e65942 | 1 | felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms | package eda;
import java.util.Arrays;
import java.util.Scanner;
class Queue {
private String[] array;
private int tail;
private static final String FULL = "full";
private static final String EMPTY = "empty";
public Queue(int size) {
this.array = new String[size];
this.tail = -1;
}
public void add(String value) {
if (!isFull()) {
tail++;
array[tail] = value;
} else {
System.out.println(FULL);
}
}
public void remove() {
if (!isEmpty()) {
shift();
tail--;
} else {
System.out.println(EMPTY);
}
}
private void shift() {
for (int i = 1; i <= tail; i++) {
this.array[i - 1] = this.array[i];
}
}
public String print() {
if (isEmpty()) {
return EMPTY;
}
String saida = "";
for (int i = 0; i <= tail; i++) {
saida += array[i] + " ";
}
return saida.trim();
}
public boolean isEmpty() {
return (tail == -1);
}
public boolean isFull() {
return (tail == array.length - 1);
}
public static void main(String[] args) {
Scanner ler = new Scanner(System.in);
int size = ler.nextInt();
// Limpar o buffer
ler.nextLine();
Queue fila = new Queue(size);
String[] op;
do {
op = ler.nextLine().split(" ");
switch (op[0]) {
case "remove":
fila.remove();
break;
case "print":
System.out.println(fila.print());
break;
case "element":
System.out.println(fila.element());
break;
case "end":
break;
case "add":
fila.add(op[1]);
break;
default:
break;
}
} while (!op[0].equals("end"));
}
private String element() {
if (isEmpty())
return EMPTY;
return this.array[0];
}
}
| data_structures/Queue/Java/Queue.java | Queue in java
| data_structures/Queue/Java/Queue.java | Queue in java | <ide><path>ata_structures/Queue/Java/Queue.java
<add>package eda;
<add>
<add>import java.util.Arrays;
<add>import java.util.Scanner;
<add>
<add>class Queue {
<add>
<add> private String[] array;
<add> private int tail;
<add> private static final String FULL = "full";
<add> private static final String EMPTY = "empty";
<add>
<add> public Queue(int size) {
<add> this.array = new String[size];
<add> this.tail = -1;
<add> }
<add>
<add> public void add(String value) {
<add> if (!isFull()) {
<add> tail++;
<add> array[tail] = value;
<add> } else {
<add> System.out.println(FULL);
<add> }
<add> }
<add>
<add> public void remove() {
<add> if (!isEmpty()) {
<add> shift();
<add> tail--;
<add> } else {
<add> System.out.println(EMPTY);
<add> }
<add> }
<add>
<add> private void shift() {
<add> for (int i = 1; i <= tail; i++) {
<add> this.array[i - 1] = this.array[i];
<add> }
<add>
<add> }
<add>
<add> public String print() {
<add> if (isEmpty()) {
<add> return EMPTY;
<add> }
<add> String saida = "";
<add> for (int i = 0; i <= tail; i++) {
<add> saida += array[i] + " ";
<add> }
<add> return saida.trim();
<add>
<add> }
<add>
<add> public boolean isEmpty() {
<add> return (tail == -1);
<add> }
<add>
<add> public boolean isFull() {
<add> return (tail == array.length - 1);
<add> }
<add>
<add> public static void main(String[] args) {
<add>
<add> Scanner ler = new Scanner(System.in);
<add> int size = ler.nextInt();
<add> // Limpar o buffer
<add> ler.nextLine();
<add> Queue fila = new Queue(size);
<add> String[] op;
<add> do {
<add> op = ler.nextLine().split(" ");
<add> switch (op[0]) {
<add> case "remove":
<add> fila.remove();
<add> break;
<add> case "print":
<add> System.out.println(fila.print());
<add> break;
<add> case "element":
<add> System.out.println(fila.element());
<add> break;
<add> case "end":
<add> break;
<add> case "add":
<add> fila.add(op[1]);
<add> break;
<add> default:
<add> break;
<add> }
<add>
<add> } while (!op[0].equals("end"));
<add> }
<add>
<add> private String element() {
<add> if (isEmpty())
<add> return EMPTY;
<add> return this.array[0];
<add> }
<add>
<add>} |
|
Java | epl-1.0 | 7f6a54b2afc43ddd1b9a32cfbd992734a14388d2 | 0 | codenvy/plugin-datasource,codenvy/plugin-datasource | /*
* Copyright 2014 Codenvy, S.A.
*
* 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.codenvy.ide.ext.datasource.client.editdatasource;
import java.util.Set;
import com.codenvy.api.user.shared.dto.Profile;
import com.codenvy.ide.api.notification.Notification;
import com.codenvy.ide.api.notification.Notification.Status;
import com.codenvy.ide.api.notification.Notification.Type;
import com.codenvy.ide.api.notification.NotificationManager;
import com.codenvy.ide.ext.datasource.client.DatasourceManager;
import com.codenvy.ide.ext.datasource.client.events.DatasourceListChangeEvent;
import com.codenvy.ide.ext.datasource.shared.DatabaseConfigurationDTO;
import com.codenvy.ide.util.loging.Log;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.google.web.bindery.event.shared.EventBus;
/**
* The presenter for the datasource edit/delete datasources dialog.
*
* @author "Mickaël Leduque"
*/
public class EditDatasourcesPresenter implements EditDatasourcesView.ActionDelegate {
/** The view component. */
private final EditDatasourcesView view;
/** The component that stores datasources. */
private final DatasourceManager datasourceManager;
/** The datasource list model component. */
private final ListDataProvider<DatabaseConfigurationDTO> dataProvider = new ListDataProvider<>();
/** The selection model for the datasource list widget. */
private final MultiSelectionModel<DatabaseConfigurationDTO> selectionModel;
/** The i18n messages instance. */
private final EditDatasourceMessages messages;
private final NotificationManager notificationManager;
/** the event bus, used to send event "datasources list modified". */
private final EventBus eventBus;
@Inject
public EditDatasourcesPresenter(final EditDatasourcesView view,
final DatasourceManager datasourceManager,
final @Named(DatasourceKeyProvider.NAME) DatasourceKeyProvider keyProvider,
final EditDatasourceMessages messages,
final NotificationManager notificationManager,
final EventBus eventBus) {
this.view = view;
this.datasourceManager = datasourceManager;
this.messages = messages;
this.notificationManager = notificationManager;
this.eventBus = eventBus;
this.view.bindDatasourceModel(dataProvider);
this.view.setDelegate(this);
this.selectionModel = new MultiSelectionModel<>(keyProvider);
this.view.bindSelectionModel(this.selectionModel);
}
/** Show dialog. */
public void showDialog() {
setupDatasourceList();
this.view.showDialog();
}
@Override
public void closeDialog() {
this.view.closeDialog();
}
/** Sets the content of the datasource widget. */
private void setupDatasourceList() {
this.dataProvider.getList().clear();
for (DatabaseConfigurationDTO datasource : this.datasourceManager) {
this.dataProvider.getList().add(datasource);
}
this.dataProvider.flush();
}
@Override
public void deleteSelectedDatasources() {
final Set<DatabaseConfigurationDTO> selection = this.selectionModel.getSelectedSet();
if (selection.isEmpty()) {
Window.alert(this.messages.editOrDeleteNoSelectionMessage());
return;
}
for (final DatabaseConfigurationDTO datasource : selection) {
this.dataProvider.getList().remove(datasource);
this.datasourceManager.remove(datasource);
}
final Notification persistNotification = new Notification("Saving datasources definitions", Status.PROGRESS);
this.notificationManager.showNotification(persistNotification);
try {
this.datasourceManager.persist(new AsyncCallback<Profile>() {
@Override
public void onSuccess(final Profile result) {
Log.info(EditDatasourcesPresenter.class, "Datasource definitions saved.");
persistNotification.setMessage("Datasource definitions saved");
persistNotification.setStatus(Notification.Status.FINISHED);
}
@Override
public void onFailure(final Throwable e) {
Log.error(EditDatasourcesPresenter.class, "Exception when persisting datasources: " + e.getMessage());
GWT.log("Full exception :", e);
notificationManager.showNotification(new Notification("Failed to persist datasources", Type.ERROR));
}
});
} catch (final Exception e) {
Log.error(EditDatasourcesPresenter.class, "Exception when persisting datasources: " + e.getMessage());
notificationManager.showNotification(new Notification("Failed to persist datasources", Type.ERROR));
}
// reset datasource model
setupDatasourceList();
// inform the world about the datasource list modification
this.eventBus.fireEvent(new DatasourceListChangeEvent());
}
@Override
public void editSelectedDatasource() {
final Set<DatabaseConfigurationDTO> selection = this.selectionModel.getSelectedSet();
if (selection.isEmpty()) {
Window.alert(this.messages.editOrDeleteNoSelectionMessage());
return;
}
if (selection.size() > 1) {
Window.alert(this.messages.editMultipleSelectionMessage());
return;
}
}
}
| codenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/editdatasource/EditDatasourcesPresenter.java | /*
* Copyright 2014 Codenvy, S.A.
*
* 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.codenvy.ide.ext.datasource.client.editdatasource;
import java.util.Set;
import com.codenvy.ide.ext.datasource.client.DatasourceManager;
import com.codenvy.ide.ext.datasource.shared.DatabaseConfigurationDTO;
import com.google.gwt.user.client.Window;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.inject.Inject;
import com.google.inject.name.Named;
/**
* The presenter for the datasource edit/delete datasources dialog.
*
* @author "Mickaël Leduque"
*/
public class EditDatasourcesPresenter implements EditDatasourcesView.ActionDelegate {
/** The view component. */
private final EditDatasourcesView view;
/** The component that stores datasources. */
private final DatasourceManager datasourceManager;
/** The datasource list model component. */
private final ListDataProvider<DatabaseConfigurationDTO> dataProvider = new ListDataProvider<>();
/** The selection model for the datasource list widget. */
private final MultiSelectionModel<DatabaseConfigurationDTO> selectionModel;
/** The i18n messages instance. */
private final EditDatasourceMessages messages;
@Inject
public EditDatasourcesPresenter(final EditDatasourcesView view,
final DatasourceManager datasourceManager,
final @Named(DatasourceKeyProvider.NAME) DatasourceKeyProvider keyProvider,
EditDatasourceMessages messages) {
this.view = view;
this.datasourceManager = datasourceManager;
this.messages = messages;
this.view.bindDatasourceModel(dataProvider);
this.view.setDelegate(this);
this.selectionModel = new MultiSelectionModel<>(keyProvider);
this.view.bindSelectionModel(this.selectionModel);
}
/** Show dialog. */
public void showDialog() {
setupDatasourceList();
this.view.showDialog();
}
@Override
public void closeDialog() {
this.view.closeDialog();
}
/** Sets the content of the datasource widget. */
private void setupDatasourceList() {
this.dataProvider.getList().clear();
for (DatabaseConfigurationDTO datasource : this.datasourceManager) {
this.dataProvider.getList().add(datasource);
}
this.dataProvider.flush();
}
@Override
public void deleteSelectedDatasources() {
final Set<DatabaseConfigurationDTO> selection = this.selectionModel.getSelectedSet();
if (selection.isEmpty()) {
Window.alert(this.messages.editOrDeleteNoSelectionMessage());
return;
}
for (final DatabaseConfigurationDTO datasource : selection) {
this.dataProvider.getList().remove(datasource);
this.datasourceManager.remove(datasource);
}
this.dataProvider.flush();
}
@Override
public void editSelectedDatasource() {
final Set<DatabaseConfigurationDTO> selection = this.selectionModel.getSelectedSet();
if (selection.isEmpty()) {
Window.alert(this.messages.editOrDeleteNoSelectionMessage());
return;
}
if (selection.size() > 1) {
Window.alert(this.messages.editMultipleSelectionMessage());
return;
}
}
}
| Persist datasource list after datasource delete - #21
| codenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/editdatasource/EditDatasourcesPresenter.java | Persist datasource list after datasource delete - #21 | <ide><path>odenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/editdatasource/EditDatasourcesPresenter.java
<ide>
<ide> import java.util.Set;
<ide>
<add>import com.codenvy.api.user.shared.dto.Profile;
<add>import com.codenvy.ide.api.notification.Notification;
<add>import com.codenvy.ide.api.notification.Notification.Status;
<add>import com.codenvy.ide.api.notification.Notification.Type;
<add>import com.codenvy.ide.api.notification.NotificationManager;
<ide> import com.codenvy.ide.ext.datasource.client.DatasourceManager;
<add>import com.codenvy.ide.ext.datasource.client.events.DatasourceListChangeEvent;
<ide> import com.codenvy.ide.ext.datasource.shared.DatabaseConfigurationDTO;
<add>import com.codenvy.ide.util.loging.Log;
<add>import com.google.gwt.core.shared.GWT;
<ide> import com.google.gwt.user.client.Window;
<add>import com.google.gwt.user.client.rpc.AsyncCallback;
<ide> import com.google.gwt.view.client.ListDataProvider;
<ide> import com.google.gwt.view.client.MultiSelectionModel;
<ide> import com.google.inject.Inject;
<ide> import com.google.inject.name.Named;
<add>import com.google.web.bindery.event.shared.EventBus;
<ide>
<ide> /**
<ide> * The presenter for the datasource edit/delete datasources dialog.
<ide> /** The i18n messages instance. */
<ide> private final EditDatasourceMessages messages;
<ide>
<add> private final NotificationManager notificationManager;
<add>
<add> /** the event bus, used to send event "datasources list modified". */
<add> private final EventBus eventBus;
<add>
<ide> @Inject
<ide> public EditDatasourcesPresenter(final EditDatasourcesView view,
<ide> final DatasourceManager datasourceManager,
<ide> final @Named(DatasourceKeyProvider.NAME) DatasourceKeyProvider keyProvider,
<del> EditDatasourceMessages messages) {
<add> final EditDatasourceMessages messages,
<add> final NotificationManager notificationManager,
<add> final EventBus eventBus) {
<ide> this.view = view;
<ide> this.datasourceManager = datasourceManager;
<ide> this.messages = messages;
<add> this.notificationManager = notificationManager;
<add> this.eventBus = eventBus;
<ide> this.view.bindDatasourceModel(dataProvider);
<ide> this.view.setDelegate(this);
<ide> this.selectionModel = new MultiSelectionModel<>(keyProvider);
<ide> this.dataProvider.getList().remove(datasource);
<ide> this.datasourceManager.remove(datasource);
<ide> }
<del> this.dataProvider.flush();
<add> final Notification persistNotification = new Notification("Saving datasources definitions", Status.PROGRESS);
<add> this.notificationManager.showNotification(persistNotification);
<add> try {
<add> this.datasourceManager.persist(new AsyncCallback<Profile>() {
<add>
<add> @Override
<add> public void onSuccess(final Profile result) {
<add> Log.info(EditDatasourcesPresenter.class, "Datasource definitions saved.");
<add> persistNotification.setMessage("Datasource definitions saved");
<add> persistNotification.setStatus(Notification.Status.FINISHED);
<add>
<add> }
<add>
<add> @Override
<add> public void onFailure(final Throwable e) {
<add> Log.error(EditDatasourcesPresenter.class, "Exception when persisting datasources: " + e.getMessage());
<add> GWT.log("Full exception :", e);
<add> notificationManager.showNotification(new Notification("Failed to persist datasources", Type.ERROR));
<add>
<add> }
<add> });
<add> } catch (final Exception e) {
<add> Log.error(EditDatasourcesPresenter.class, "Exception when persisting datasources: " + e.getMessage());
<add> notificationManager.showNotification(new Notification("Failed to persist datasources", Type.ERROR));
<add> }
<add>
<add> // reset datasource model
<add> setupDatasourceList();
<add> // inform the world about the datasource list modification
<add> this.eventBus.fireEvent(new DatasourceListChangeEvent());
<ide> }
<ide>
<ide> @Override
<ide> Window.alert(this.messages.editMultipleSelectionMessage());
<ide> return;
<ide> }
<add>
<ide> }
<ide> } |
|
Java | mit | e52b0eb117551663bf5dbeec0888ab33ab542bd9 | 0 | pugnusferreus/batchjhaml | package com.progriff.jhaml.test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Test;
import com.progriff.jhaml.BatchJHaml;
import junit.framework.TestCase;
public class BatchJHamlTest extends TestCase {
private BatchJHaml batchJHaml;
private final static String CURRENT_PATH = System.getProperty("user.dir");
private final static String SEPERATOR =
System.getProperty("file.separator");
private String hamlPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "hamlTest";
private String hamlLayoutPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "hamlTest" + SEPERATOR + "layouts";
private String outputPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "outputTest";
@Before
public void setUp() {
batchJHaml = new BatchJHaml(hamlPath,hamlLayoutPath,outputPath,"jsp");
}
@Test
public void testGetDefaultLayout() {
batchJHaml.populateLayouts();
assertNotNull(batchJHaml.getLayouts().get("application.haml"));
}
@Test
public void testGetInvalidLayout() {
batchJHaml.populateLayouts();
assertNull(batchJHaml.getLayouts().get("test.haml"));
}
@Test
public void testGetFolderWithNoLayout() {
batchJHaml.setHamlLayoutPath(outputPath);
batchJHaml.populateLayouts();
assertTrue(batchJHaml.getLayouts().size() < 1);
batchJHaml.setHamlPath(hamlLayoutPath);
}
@Test
public void testGetInvalidLayoutFolder() {
try {
batchJHaml.setHamlLayoutPath("sdfsdf");
batchJHaml.populateLayouts();
assertTrue(false);
}
catch(Exception e) {
assertTrue(true);
} finally {
batchJHaml.setHamlLayoutPath(hamlLayoutPath);
}
}
@Test
public void testGetContentOutput() throws IOException {
File hamlFile = new File(hamlPath + SEPERATOR + "test.haml");
assertFalse(StringUtils.isBlank(batchJHaml.getHamlOutput(hamlFile)));
assertFalse(StringUtils.contains(batchJHaml.getHamlOutput(hamlFile),"<html>"));
}
}
| src/com/progriff/jhaml/test/BatchJHamlTest.java | package com.progriff.jhaml.test;
import org.junit.Before;
import org.junit.Test;
import com.progriff.jhaml.BatchJHaml;
import junit.framework.TestCase;
public class BatchJHamlTest extends TestCase {
private BatchJHaml batchJHaml;
private final static String CURRENT_PATH = System.getProperty("user.dir");
private final static String SEPERATOR =
System.getProperty("file.separator");
@Before
public void setUp() {
String hamlPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "hamlTest";
String outputPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "outputTest";
batchJHaml = new BatchJHaml(hamlPath,outputPath,"jsp");
}
@Test
public void testGetDefaultLayout() {
batchJHaml.populateLayouts();
assertNotNull(batchJHaml.getLayouts().get("application.haml"));
}
@Test
public void testGetInvalidLayout() {
batchJHaml.populateLayouts();
assertNull(batchJHaml.getLayouts().get("test.haml"));
}
}
| more test
| src/com/progriff/jhaml/test/BatchJHamlTest.java | more test | <ide><path>rc/com/progriff/jhaml/test/BatchJHamlTest.java
<ide> package com.progriff.jhaml.test;
<ide>
<add>import java.io.File;
<add>import java.io.IOException;
<add>
<add>import org.apache.commons.lang.StringUtils;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<ide> private final static String SEPERATOR =
<ide> System.getProperty("file.separator");
<ide>
<add> private String hamlPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "hamlTest";
<add> private String hamlLayoutPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "hamlTest" + SEPERATOR + "layouts";
<add> private String outputPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "outputTest";
<add>
<ide> @Before
<ide> public void setUp() {
<del> String hamlPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "hamlTest";
<del> String outputPath = CURRENT_PATH + SEPERATOR + "unitTest" + SEPERATOR + "outputTest";
<del> batchJHaml = new BatchJHaml(hamlPath,outputPath,"jsp");
<add> batchJHaml = new BatchJHaml(hamlPath,hamlLayoutPath,outputPath,"jsp");
<ide> }
<ide>
<ide> @Test
<ide> batchJHaml.populateLayouts();
<ide> assertNull(batchJHaml.getLayouts().get("test.haml"));
<ide> }
<add>
<add> @Test
<add> public void testGetFolderWithNoLayout() {
<add> batchJHaml.setHamlLayoutPath(outputPath);
<add> batchJHaml.populateLayouts();
<add> assertTrue(batchJHaml.getLayouts().size() < 1);
<add> batchJHaml.setHamlPath(hamlLayoutPath);
<add> }
<add>
<add> @Test
<add> public void testGetInvalidLayoutFolder() {
<add> try {
<add> batchJHaml.setHamlLayoutPath("sdfsdf");
<add> batchJHaml.populateLayouts();
<add> assertTrue(false);
<add> }
<add> catch(Exception e) {
<add> assertTrue(true);
<add> } finally {
<add> batchJHaml.setHamlLayoutPath(hamlLayoutPath);
<add> }
<add>
<add> }
<add>
<add> @Test
<add> public void testGetContentOutput() throws IOException {
<add> File hamlFile = new File(hamlPath + SEPERATOR + "test.haml");
<add> assertFalse(StringUtils.isBlank(batchJHaml.getHamlOutput(hamlFile)));
<add> assertFalse(StringUtils.contains(batchJHaml.getHamlOutput(hamlFile),"<html>"));
<add> }
<ide> } |
|
JavaScript | apache-2.0 | 5a59deede70f26f0ddaf235072730943c5178745 | 0 | chamindias/carbon-apimgt,Rajith90/carbon-apimgt,isharac/carbon-apimgt,jaadds/carbon-apimgt,jaadds/carbon-apimgt,Rajith90/carbon-apimgt,ruks/carbon-apimgt,uvindra/carbon-apimgt,nuwand/carbon-apimgt,pubudu538/carbon-apimgt,chamilaadhi/carbon-apimgt,chamilaadhi/carbon-apimgt,bhathiya/carbon-apimgt,chamilaadhi/carbon-apimgt,uvindra/carbon-apimgt,ruks/carbon-apimgt,harsha89/carbon-apimgt,wso2/carbon-apimgt,chamindias/carbon-apimgt,pubudu538/carbon-apimgt,harsha89/carbon-apimgt,wso2/carbon-apimgt,Rajith90/carbon-apimgt,tharindu1st/carbon-apimgt,prasa7/carbon-apimgt,prasa7/carbon-apimgt,uvindra/carbon-apimgt,nuwand/carbon-apimgt,malinthaprasan/carbon-apimgt,tharindu1st/carbon-apimgt,ruks/carbon-apimgt,nuwand/carbon-apimgt,praminda/carbon-apimgt,tharikaGitHub/carbon-apimgt,praminda/carbon-apimgt,fazlan-nazeem/carbon-apimgt,isharac/carbon-apimgt,praminda/carbon-apimgt,chamindias/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamilaadhi/carbon-apimgt,bhathiya/carbon-apimgt,pubudu538/carbon-apimgt,fazlan-nazeem/carbon-apimgt,uvindra/carbon-apimgt,tharikaGitHub/carbon-apimgt,Rajith90/carbon-apimgt,isharac/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,harsha89/carbon-apimgt,tharindu1st/carbon-apimgt,fazlan-nazeem/carbon-apimgt,bhathiya/carbon-apimgt,tharikaGitHub/carbon-apimgt,malinthaprasan/carbon-apimgt,jaadds/carbon-apimgt,harsha89/carbon-apimgt,wso2/carbon-apimgt,bhathiya/carbon-apimgt,isharac/carbon-apimgt,prasa7/carbon-apimgt,jaadds/carbon-apimgt,tharikaGitHub/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,nuwand/carbon-apimgt,fazlan-nazeem/carbon-apimgt,chamindias/carbon-apimgt,malinthaprasan/carbon-apimgt,pubudu538/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,tharindu1st/carbon-apimgt,wso2/carbon-apimgt,malinthaprasan/carbon-apimgt,prasa7/carbon-apimgt | var currentLocation;
var currentLocation = "allAPIs";
var statsEnabled = isDataPublishingEnabled();
var apiNameVersionMap = {};
var mediationName;
var apiName;
var version;
var comparedVersion = {};
var versionComparison = false;
var d = new Date();
var currentDay = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(),d.getSeconds());
var to = new Date();
var from = new Date(to.getTime() - 1000 * 60 * 60 * 24);
var depth ="HOUR";
$( document ).ready(function() {
populateAPIList();
$("#apiSelect").change(function (e) {
apiName = this.value;
populateVersionList(apiName,false);
});
$("#versionSelect").change(function (e) {
version = this.value;
comparedVersion[version] = version;
if (versionComparison) {
populateVersionList(apiName,true);
}else{
renderGraph(from,to,depth);
}
});
$("#apiFilter").change(function (e) {
currentLocation = this.value;
populateAPIList();
});
$("#mediationType").change(function (e) {
mediationName = this.value;
versionComparison = true;
renderCompareGraph(from,to,depth,encodeURIComponent(mediationName));
});
$("#compareVersion").change(function (e) {
var tempArray = {};
var tempVersion = $('#compareVersion option:selected');
$(tempVersion).each(function(index, tempVersion){
tempArray[$(this).val()] = $(this).val();
});
tempArray[version] = version;
comparedVersion = tempArray;
$('#mediationType').trigger('change');
});
$('#today-btn').on('click', function () {
from = currentDay - 86400000;
to = currentDay;
renderGraph(from,to,"HOUR");
versionComparison = false;
depth = "HOUR";
btnActiveToggle(this);
});
$('#hour-btn').on('click', function () {
from = currentDay - 3600000;
to = currentDay;
depth = "MINUTES";
versionComparison = false;
renderGraph(from,to,depth);
btnActiveToggle(this);
});
$('#clear-btn').on('click', function () {
versionComparison = false;
renderGraph(from,to,depth);
$('#compare-selection').css("display", "none");
$('#compare-version-btn').css("display", "inline");
$('#clear-btn-wrapper').css("display", "none");
});
$('#week-btn').on('click', function () {
from = currentDay - 604800000;
to = currentDay;
depth = "DAY";
versionComparison = false;
renderGraph(from,to,depth);
btnActiveToggle(this);
});
$('#month-btn').on('click', function () {
from = currentDay - (604800000 * 4);
to = currentDay;
depth = "DAY";
versionComparison = false;
renderGraph(from,to,depth);
btnActiveToggle(this);
});
$('#date-range').click(function () {
$(this).removeClass('active');
});
$('#compare-btn').on('click', function () {
populateVersionList(apiName,true);
$('#compare-selection').css("display", "inline");
$('#compare-version-btn').css("display", "none");
$('#clear-btn-wrapper').css("display", "inline");
});
//date picker
$('#date-range').daterangepicker({
timePicker: false,
timePickerIncrement: 30,
format: 'YYYY-MM-DD h:mm',
opens: 'left'
});
$('#date-range').on('apply.daterangepicker', function (ev, picker) {
btnActiveToggle(this);
from = picker.startDate;
to = picker.endDate;
var fromStr = convertDate(from).split(" ");
var toStr = convertDate(to).split(" ");
var dateStr = fromStr[0] + " <b>to</b> " + toStr[0];
$("#date-range span").html(dateStr);
if ((to-from)>(3600000*24*2)) {
depth = "DAY";
renderGraph(from, to,depth);
}else{
depth = "HOUR";
renderGraph(from, to,depth);
}
});
});
var populateAPIList = function(){
jagg.post("/site/blocks/stats/ajax/stats.jag", { action : "getAPIList" ,currentLocation:currentLocation},
function (json) {
if (!json.error) {
apiNameVersionMap = json.apiNameVersionMap;
var i=0;
var apis= '';
for (var name in apiNameVersionMap) {
if (i==0) {
apis+='<option selected="selected" value='+name+'>' + name + '</option>';
}else{
apis+='<option value='+name+'>' + name+ '</option>';
}
i++;
}
$('#apiSelect')
.empty()
.append(apis)
.selectpicker('refresh')
.trigger('change');
}
else {
if (json.message == "AuthenticateError") {
jagg.showLogin();
}
}
});
};
var populateVersionList = function(apiName,compare){
var i=0;
if (compare) {
$('#compareVersion').multiselect();
$('#compareVersion option').each(function(index, option) {
$(option).remove();
});
for (var ver in apiNameVersionMap[apiName]) {
var tempVersion = apiNameVersionMap[apiName][ver];
if (tempVersion != $('#versionSelect option:selected').val()) {
if (i==0) {
$('#compareVersion').append('<option selected="selected" value'+tempVersion+'>' + tempVersion + '</option>');
}else{
$('#compareVersion').append('<option value='+tempVersion+'>' + tempVersion+ '</option>');
}
i++;
}
}
$('#compareVersion').multiselect('rebuild');
$('#compareVersion').trigger('change');
}else{
var selectVersions = '';
for (var version in apiNameVersionMap[apiName]) {
var tempVersion = apiNameVersionMap[apiName][version];
if (i==0) {
selectVersions += '<option selected="selected" value='+tempVersion+'>' + tempVersion + '</option>';
}else{
selectVersions += '<option value='+tempVersion+'>' + tempVersion+ '</option>';
}
i++;
}
if (versionComparison){
if (apiNameVersionMap[apiName].length == 1) {
$('#clear-btn').trigger('click');
}
}
$('#versionSelect')
.empty()
.append(selectVersions)
.selectpicker('refresh')
.trigger('change');
}
};
var populateMediations = function(data){
var i=0;
var mediations = '';
for (var mediationName in data) {
if (i==0) {
mediations +='<option selected="selected" value'+mediationName+'>' + mediationName + '</option>';
}else{
mediations +='<option value='+encodeURIComponent(mediationName)+'>' + mediationName+ '</option>';
}
i++;
}
$('#mediationType')
.empty()
.append(mediations)
.selectpicker('refresh');
};
function renderGraph(fromDate,toDate,drillDown){
var toDateString = convertTimeString(toDate);
var fromDateString = convertTimeString(fromDate);
getDateTime(toDate,fromDate);
if (statsEnabled) {
jagg.post("/site/blocks/stats/api-latencytime/ajax/stats.jag", { action : "getExecutionTimeOfAPI" , apiName : apiName , apiVersion : version , fromDate : fromDateString , toDate : toDateString,drilldown:drillDown},
function (json) {
if (!json.error) {
var data1 = {};
if (json.usage && json.usage.length > 0) {
$('#apiLatencyTimeNote').removeClass('hide');
for (var usage1 in json.usage ) {
if (json.usage[usage1].values) {
var apiResponseTimeData = (data1["Total Time"]) ? data1["Total Time"] : [];
var backendLatencyData = (data1["BackEnd"]) ? data1["BackEnd"] : [];
var otherLatencyData = (data1["Other"]) ? data1["Other"] : [];
var requestMediationLatencyData = (data1["Request Mediation"]) ? data1["Request Mediation"] : [];
var responseMediationLatencyData = (data1["Response Mediation"]) ? data1["Response Mediation"] : [];
var securityLatencyData = (data1["Authentication"]) ? data1["Authentication"] : [];
var throttlingLatencyData = (data1["Throttling"]) ? data1["Throttling"] : [];
var d = new Date(json.usage[usage1].values.year, (json.usage[usage1].values.month - 1), json.usage[usage1].values.day, json.usage[usage1].values.hour, json.usage[usage1].values.minutes, json.usage[usage1].values.seconds, "00");
apiResponseTimeData.push({x: d, y: json.usage[usage1].values.apiResponseTime});
backendLatencyData.push({x: d, y: json.usage[usage1].values.backendLatency});
otherLatencyData.push({x: d, y: json.usage[usage1].values.otherLatency});
requestMediationLatencyData.push({
x: d,
y: json.usage[usage1].values.requestMediationLatency
});
responseMediationLatencyData.push({
x: d,
y: json.usage[usage1].values.responseMediationLatency
});
securityLatencyData.push({x: d, y: json.usage[usage1].values.securityLatency});
throttlingLatencyData.push({x: d, y: json.usage[usage1].values.throttlingLatency});
data1["Total Time"] = apiResponseTimeData;
data1["BackEnd"] = backendLatencyData;
data1["Other"] = otherLatencyData;
data1["Request Mediation"] = requestMediationLatencyData;
data1["Response Mediation"] = responseMediationLatencyData;
data1["Authentication"] = securityLatencyData;
data1["Throttling"] = throttlingLatencyData;
}
}
populateMediations(data1);
drawGraphInArea(data1,drillDown);
}
else if (json.usage && json.usage.length == 0 && statsEnabled) {
$('#noData').html('');
$('#noData').append('<div class="center-wrapper"><div class="col-sm-4"/><div class="col-sm-4 message message-info"><h4><i class="icon fw fw-info" title="No Data Available"></i>'+i18n.t("No Data Available")+'</h4>'+ "<p> " + i18n.t('Generate some traffic to see statistics') + "</p>" +'</div></div>');
$('#chartContainer').hide();
$('#apiLatencyTimeNote').addClass('hide');
}
else{
$('.stat-page').html("");
$('#apiLatencyTimeNote').addClass('hide');
showEnableAnalyticsMsg();
}
}
else {
if (json.message == "AuthenticateError") {
jagg.showLogin();
} else {
jagg.message({content: json.message, type: "error"});
}
}
}, "json");
}else{
$('.stat-page').html("");
showEnableAnalyticsMsg();
}
}
function renderCompareGraph(fromDate,toDate,drillDown,mediationName){
var toDateString = convertTimeString(toDate);
var fromDateString = convertTimeString(fromDate);
getDateTime(toDate,fromDate);
jagg.post("/site/blocks/stats/api-latencytime/ajax/stats.jag", { action : "getComparisonData" , apiName : apiName , fromDate : fromDateString , toDate : toDateString,drilldown:drillDown,versionArray:JSON.stringify(comparedVersion),mediationName:decodeURIComponent(mediationName)},
function (json) {
if (!json.error) {
drawGraphInArea(json.usage,drillDown);
}
}, "json");
}
function drawGraphInArea(rdata,drilldown){
$('#chartContainer').show();
$('#chartContainer').empty();
$('#noData').empty();
$('#temploadinglatencytTime').empty();
var renderdata = [];
var dateFormat;
var xAxisLabel;
if (drilldown == "DAY") {
dateFormat = '%d/%m';
xAxisLabel = 'Time (Days)';
}else if (drilldown == "HOUR") {
dateFormat = '%d/%m %H';
xAxisLabel = 'Time (Hours)';
}else if (drilldown == "MINUTES") {
dateFormat = '%d/%m %H:%M';
xAxisLabel = 'Time (Minutes)';
}else if (drilldown == "SECONDS") {
dateFormat = '%d/%m %H:%M:%S';
xAxisLabel = 'Time (Seconds)';
}
for(var legand in rdata){
renderdata.push({values: rdata[legand],key: legand});
}
nv.addGraph(function() {
var chart = nv.models.lineChart()
.margin({left: 100, bottom: 100})
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
chart.xAxis.axisLabel(xAxisLabel).rotateLabels(-45)
.tickFormat(function (d) {
return d3.time.format(dateFormat)(new Date(d))});
chart.yAxis //Chart y-axis settings
.axisLabel('Execution Time (ms)')
.tickFormat(d3.format(',r'));
d3.select('#latencytTime svg') //Select the <svg> element you want to render the chart in.
.datum(renderdata) //Populate the <svg> element with chart data...
.call(chart); //Finally, render the chart!
//Update the chart when window resizes.
nv.utils.windowResize(function() { chart.update() });
d3.selectAll(".nv-point").on("click", function (e) {
var date = new Date(e.x);
if (depth == "DAY"){
from = new Date(e.x).setDate(date.getDate()-1);
to = new Date(e.x).setDate(date.getDate()+1);
depth = "HOUR";
}else if (depth == "HOUR"){
from = new Date(e.x).setHours(date.getHours()-1);
to = new Date(e.x).setHours(date.getHours()+1);
depth = "MINUTES";
}else if (depth == "MINUTES"){
from = new Date(e.x).setMinutes(date.getMinutes()-1);
to = new Date(e.x).setMinutes(date.getMinutes()+1);
depth = "SECONDS";
}else if (depth == "SECONDS"){
depth = "HOUR";
from = new Date(e.x).setHours(date.getHours()-1);
to = new Date(e.x).setHours(date.getHours()+1);
}
if (versionComparison) {
renderCompareGraph(from,to,depth,encodeURIComponent(mediationName));
}else{
renderGraph(from,to,depth);
}
});
});
$('#chartContainer').append($('<div id="latencytTime"><svg style="height:600px;"></svg></div>'));
$('#latencytTime svg').show();
}
function getDateTime(currentDay,fromDay){
toStr = convertTimeString(currentDay);
fromStr = convertTimeString(fromDay);
var toDate = toStr.split(" ");
var fromDate = fromStr.split(" ");
var dateStr= fromDate[0] + "<b>to</b> " + toDate[0];
$("#date-range span").html(dateStr);
$('#date-range').data('daterangepicker').setStartDate(from);
$('#date-range').data('daterangepicker').setEndDate(to);
} | features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/site/themes/wso2/templates/stats/api-latencytime/js/stats.js | var currentLocation;
var currentLocation = "allAPIs";
var statsEnabled = isDataPublishingEnabled();
var apiNameVersionMap = {};
var mediationName;
var apiName;
var version;
var comparedVersion = {};
var versionComparison = false;
var d = new Date();
var currentDay = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(),d.getSeconds());
var to = new Date();
var from = new Date(to.getTime() - 1000 * 60 * 60 * 24);
var depth ="HOUR";
$( document ).ready(function() {
populateAPIList();
$("#apiSelect").change(function (e) {
apiName = this.value;
populateVersionList(apiName,false);
});
$("#versionSelect").change(function (e) {
version = this.value;
comparedVersion[version] = version;
if (versionComparison) {
populateVersionList(apiName,true);
}else{
renderGraph(from,to,depth);
}
});
$("#apiFilter").change(function (e) {
currentLocation = this.value;
populateAPIList();
});
$("#mediationType").change(function (e) {
mediationName = this.value;
versionComparison = true;
renderCompareGraph(from,to,depth,encodeURIComponent(mediationName));
});
$("#compareVersion").change(function (e) {
var tempArray = {};
var tempVersion = $('#compareVersion option:selected');
$(tempVersion).each(function(index, tempVersion){
tempArray[$(this).val()] = $(this).val();
});
tempArray[version] = version;
comparedVersion = tempArray;
$('#mediationType').trigger('change');
});
$('#today-btn').on('click', function () {
from = currentDay - 86400000;
to = currentDay;
renderGraph(from,to,"HOUR");
versionComparison = false;
depth = "HOUR";
btnActiveToggle(this);
});
$('#hour-btn').on('click', function () {
from = currentDay - 3600000;
to = currentDay;
depth = "MINUTES";
versionComparison = false;
renderGraph(from,to,depth);
btnActiveToggle(this);
});
$('#clear-btn').on('click', function () {
versionComparison = false;
renderGraph(from,to,depth);
$('#compare-selection').css("display", "none");
$('#compare-version-btn').css("display", "inline");
$('#clear-btn-wrapper').css("display", "none");
});
$('#week-btn').on('click', function () {
from = currentDay - 604800000;
to = currentDay;
depth = "DAY";
versionComparison = false;
renderGraph(from,to,depth);
btnActiveToggle(this);
});
$('#month-btn').on('click', function () {
from = currentDay - (604800000 * 4);
to = currentDay;
depth = "DAY";
versionComparison = false;
renderGraph(from,to,depth);
btnActiveToggle(this);
});
$('#date-range').click(function () {
$(this).removeClass('active');
});
$('#compare-btn').on('click', function () {
populateVersionList(apiName,true);
$('#compare-selection').css("display", "inline");
$('#compare-version-btn').css("display", "none");
$('#clear-btn-wrapper').css("display", "inline");
});
//date picker
$('#date-range').daterangepicker({
timePicker: false,
timePickerIncrement: 30,
format: 'YYYY-MM-DD h:mm',
opens: 'left'
});
$('#date-range').on('apply.daterangepicker', function (ev, picker) {
btnActiveToggle(this);
from = picker.startDate;
to = picker.endDate;
var fromStr = convertDate(from).split(" ");
var toStr = convertDate(to).split(" ");
var dateStr = fromStr[0] + " <b>to</b> " + toStr[0];
$("#date-range span").html(dateStr);
if ((to-from)>(3600000*24*2)) {
depth = "DAY";
renderGraph(from, to,depth);
}else{
depth = "HOUR";
renderGraph(from, to,depth);
}
});
});
var populateAPIList = function(){
jagg.post("/site/blocks/stats/ajax/stats.jag", { action : "getAPIList" ,currentLocation:currentLocation},
function (json) {
if (!json.error) {
apiNameVersionMap = json.apiNameVersionMap;
var i=0;
var apis= '';
for (var name in apiNameVersionMap) {
if (i==0) {
apis+='<option selected="selected" value='+name+'>' + name + '</option>';
}else{
apis+='<option value='+name+'>' + name+ '</option>';
}
i++;
}
$('#apiSelect')
.empty()
.append(apis)
.selectpicker('refresh')
.trigger('change');
}
else {
if (json.message == "AuthenticateError") {
jagg.showLogin();
}
}
});
};
var populateVersionList = function(apiName,compare){
var i=0;
if (compare) {
$('#compareVersion').multiselect();
$('#compareVersion option').each(function(index, option) {
$(option).remove();
});
for (var ver in apiNameVersionMap[apiName]) {
var tempVersion = apiNameVersionMap[apiName][ver];
if (tempVersion != $('#versionSelect option:selected').val()) {
if (i==0) {
$('#compareVersion').append('<option selected="selected" value'+tempVersion+'>' + tempVersion + '</option>');
}else{
$('#compareVersion').append('<option value='+tempVersion+'>' + tempVersion+ '</option>');
}
i++;
}
}
$('#compareVersion').multiselect('rebuild');
$('#compareVersion').trigger('change');
}else{
var selectVersions = '';
for (var version in apiNameVersionMap[apiName]) {
var tempVersion = apiNameVersionMap[apiName][version];
if (i==0) {
selectVersions += '<option selected="selected" value='+tempVersion+'>' + tempVersion + '</option>';
}else{
selectVersions += '<option value='+tempVersion+'>' + tempVersion+ '</option>';
}
i++;
}
if (versionComparison){
if (apiNameVersionMap[apiName].length == 1) {
$('#clear-btn').trigger('click');
}
}
$('#versionSelect')
.empty()
.append(selectVersions)
.selectpicker('refresh')
.trigger('change');
}
};
var populateMediations = function(data){
var i=0;
var mediations = '';
for (var mediationName in data) {
if (i==0) {
mediations +='<option selected="selected" value'+mediationName+'>' + mediationName + '</option>';
}else{
mediations +='<option value='+encodeURIComponent(mediationName)+'>' + mediationName+ '</option>';
}
i++;
}
$('#mediationType')
.empty()
.append(mediations)
.selectpicker('refresh');
};
function renderGraph(fromDate,toDate,drillDown){
var toDateString = convertTimeString(toDate);
var fromDateString = convertTimeString(fromDate);
getDateTime(toDate,fromDate);
if (statsEnabled) {
jagg.post("/site/blocks/stats/api-latencytime/ajax/stats.jag", { action : "getExecutionTimeOfAPI" , apiName : apiName , apiVersion : version , fromDate : fromDateString , toDate : toDateString,drilldown:drillDown},
function (json) {
if (!json.error) {
var data1 = {};
if (json.usage && json.usage.length > 0) {
$('#apiLatencyTimeNote').removeClass('hide');
for(var usage1 in json.usage ){
var apiResponseTimeData = (data1["Total Time"]) ? data1["Total Time"] : [];
var backendLatencyData = (data1["BackEnd"])? data1["BackEnd"] : [] ;
var otherLatencyData = (data1["Other"]) ? data1["Other"] :[];
var requestMediationLatencyData = (data1["Request Mediation"]) ? data1["Request Mediation"] :[];
var responseMediationLatencyData = (data1["Response Mediation"]) ? data1["Response Mediation"] : [];
var securityLatencyData = (data1["Authentication"]) ? data1["Authentication"] : [];
var throttlingLatencyData = (data1["Throttling"])? data1["Throttling"] : [];
var d = new Date(json.usage[usage1].values.year, (json.usage[usage1].values.month -1), json.usage[usage1].values.day, json.usage[usage1].values.hour,json.usage[usage1].values.minutes,json.usage[usage1].values.seconds,"00");
apiResponseTimeData.push({x:d,y:json.usage[usage1].values.apiResponseTime});
backendLatencyData.push({x:d,y:json.usage[usage1].values.backendLatency});
otherLatencyData.push({x:d,y:json.usage[usage1].values.otherLatency});
requestMediationLatencyData.push({x:d,y:json.usage[usage1].values.requestMediationLatency});
responseMediationLatencyData.push({x:d,y:json.usage[usage1].values.responseMediationLatency});
securityLatencyData.push({x:d,y:json.usage[usage1].values.securityLatency});
throttlingLatencyData.push({x:d,y:json.usage[usage1].values.throttlingLatency});
data1["Total Time"] = apiResponseTimeData;
data1["BackEnd"] = backendLatencyData;
data1["Other"] = otherLatencyData;
data1["Request Mediation"] = requestMediationLatencyData;
data1["Response Mediation"] = responseMediationLatencyData;
data1["Authentication"] = securityLatencyData;
data1["Throttling"] = throttlingLatencyData;
}
populateMediations(data1);
drawGraphInArea(data1,drillDown);
}
else if (json.usage && json.usage.length == 0 && statsEnabled) {
$('#noData').html('');
$('#noData').append('<div class="center-wrapper"><div class="col-sm-4"/><div class="col-sm-4 message message-info"><h4><i class="icon fw fw-info" title="No Data Available"></i>'+i18n.t("No Data Available")+'</h4>'+ "<p> " + i18n.t('Generate some traffic to see statistics') + "</p>" +'</div></div>');
$('#chartContainer').hide();
$('#apiLatencyTimeNote').addClass('hide');
}
else{
$('.stat-page').html("");
$('#apiLatencyTimeNote').addClass('hide');
showEnableAnalyticsMsg();
}
}
else {
if (json.message == "AuthenticateError") {
jagg.showLogin();
} else {
jagg.message({content: json.message, type: "error"});
}
}
}, "json");
}else{
$('.stat-page').html("");
showEnableAnalyticsMsg();
}
}
function renderCompareGraph(fromDate,toDate,drillDown,mediationName){
var toDateString = convertTimeString(toDate);
var fromDateString = convertTimeString(fromDate);
getDateTime(toDate,fromDate);
jagg.post("/site/blocks/stats/api-latencytime/ajax/stats.jag", { action : "getComparisonData" , apiName : apiName , fromDate : fromDateString , toDate : toDateString,drilldown:drillDown,versionArray:JSON.stringify(comparedVersion),mediationName:decodeURIComponent(mediationName)},
function (json) {
if (!json.error) {
drawGraphInArea(json.usage,drillDown);
}
}, "json");
}
function drawGraphInArea(rdata,drilldown){
$('#chartContainer').show();
$('#chartContainer').empty();
$('#noData').empty();
$('#temploadinglatencytTime').empty();
var renderdata = [];
var dateFormat;
var xAxisLabel;
if (drilldown == "DAY") {
dateFormat = '%d/%m';
xAxisLabel = 'Time (Days)';
}else if (drilldown == "HOUR") {
dateFormat = '%d/%m %H';
xAxisLabel = 'Time (Hours)';
}else if (drilldown == "MINUTES") {
dateFormat = '%d/%m %H:%M';
xAxisLabel = 'Time (Minutes)';
}else if (drilldown == "SECONDS") {
dateFormat = '%d/%m %H:%M:%S';
xAxisLabel = 'Time (Seconds)';
}
for(var legand in rdata){
renderdata.push({values: rdata[legand],key: legand});
}
nv.addGraph(function() {
var chart = nv.models.lineChart()
.margin({left: 100, bottom: 100})
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
chart.xAxis.axisLabel(xAxisLabel).rotateLabels(-45)
.tickFormat(function (d) {
return d3.time.format(dateFormat)(new Date(d))});
chart.yAxis //Chart y-axis settings
.axisLabel('Execution Time (ms)')
.tickFormat(d3.format(',r'));
d3.select('#latencytTime svg') //Select the <svg> element you want to render the chart in.
.datum(renderdata) //Populate the <svg> element with chart data...
.call(chart); //Finally, render the chart!
//Update the chart when window resizes.
nv.utils.windowResize(function() { chart.update() });
d3.selectAll(".nv-point").on("click", function (e) {
var date = new Date(e.x);
if (depth == "DAY"){
from = new Date(e.x).setDate(date.getDate()-1);
to = new Date(e.x).setDate(date.getDate()+1);
depth = "HOUR";
}else if (depth == "HOUR"){
from = new Date(e.x).setHours(date.getHours()-1);
to = new Date(e.x).setHours(date.getHours()+1);
depth = "MINUTES";
}else if (depth == "MINUTES"){
from = new Date(e.x).setMinutes(date.getMinutes()-1);
to = new Date(e.x).setMinutes(date.getMinutes()+1);
depth = "SECONDS";
}else if (depth == "SECONDS"){
depth = "HOUR";
from = new Date(e.x).setHours(date.getHours()-1);
to = new Date(e.x).setHours(date.getHours()+1);
}
if (versionComparison) {
renderCompareGraph(from,to,depth,encodeURIComponent(mediationName));
}else{
renderGraph(from,to,depth);
}
});
});
$('#chartContainer').append($('<div id="latencytTime"><svg style="height:600px;"></svg></div>'));
$('#latencytTime svg').show();
}
function getDateTime(currentDay,fromDay){
toStr = convertTimeString(currentDay);
fromStr = convertTimeString(fromDay);
var toDate = toStr.split(" ");
var fromDate = fromStr.split(" ");
var dateStr= fromDate[0] + "<b>to</b> " + toDate[0];
$("#date-range span").html(dateStr);
$('#date-range').data('daterangepicker').setStartDate(from);
$('#date-range').data('daterangepicker').setEndDate(to);
} | Added fix for issue#3492
| features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/site/themes/wso2/templates/stats/api-latencytime/js/stats.js | Added fix for issue#3492 | <ide><path>eatures/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/site/themes/wso2/templates/stats/api-latencytime/js/stats.js
<ide> var data1 = {};
<ide> if (json.usage && json.usage.length > 0) {
<ide> $('#apiLatencyTimeNote').removeClass('hide');
<del> for(var usage1 in json.usage ){
<del> var apiResponseTimeData = (data1["Total Time"]) ? data1["Total Time"] : [];
<del> var backendLatencyData = (data1["BackEnd"])? data1["BackEnd"] : [] ;
<del> var otherLatencyData = (data1["Other"]) ? data1["Other"] :[];
<del> var requestMediationLatencyData = (data1["Request Mediation"]) ? data1["Request Mediation"] :[];
<del> var responseMediationLatencyData = (data1["Response Mediation"]) ? data1["Response Mediation"] : [];
<del> var securityLatencyData = (data1["Authentication"]) ? data1["Authentication"] : [];
<del> var throttlingLatencyData = (data1["Throttling"])? data1["Throttling"] : [];
<del> var d = new Date(json.usage[usage1].values.year, (json.usage[usage1].values.month -1), json.usage[usage1].values.day, json.usage[usage1].values.hour,json.usage[usage1].values.minutes,json.usage[usage1].values.seconds,"00");
<del> apiResponseTimeData.push({x:d,y:json.usage[usage1].values.apiResponseTime});
<del> backendLatencyData.push({x:d,y:json.usage[usage1].values.backendLatency});
<del> otherLatencyData.push({x:d,y:json.usage[usage1].values.otherLatency});
<del> requestMediationLatencyData.push({x:d,y:json.usage[usage1].values.requestMediationLatency});
<del> responseMediationLatencyData.push({x:d,y:json.usage[usage1].values.responseMediationLatency});
<del> securityLatencyData.push({x:d,y:json.usage[usage1].values.securityLatency});
<del> throttlingLatencyData.push({x:d,y:json.usage[usage1].values.throttlingLatency});
<del> data1["Total Time"] = apiResponseTimeData;
<del> data1["BackEnd"] = backendLatencyData;
<del> data1["Other"] = otherLatencyData;
<del> data1["Request Mediation"] = requestMediationLatencyData;
<del> data1["Response Mediation"] = responseMediationLatencyData;
<del> data1["Authentication"] = securityLatencyData;
<del> data1["Throttling"] = throttlingLatencyData;
<add> for (var usage1 in json.usage ) {
<add> if (json.usage[usage1].values) {
<add> var apiResponseTimeData = (data1["Total Time"]) ? data1["Total Time"] : [];
<add> var backendLatencyData = (data1["BackEnd"]) ? data1["BackEnd"] : [];
<add> var otherLatencyData = (data1["Other"]) ? data1["Other"] : [];
<add> var requestMediationLatencyData = (data1["Request Mediation"]) ? data1["Request Mediation"] : [];
<add> var responseMediationLatencyData = (data1["Response Mediation"]) ? data1["Response Mediation"] : [];
<add> var securityLatencyData = (data1["Authentication"]) ? data1["Authentication"] : [];
<add> var throttlingLatencyData = (data1["Throttling"]) ? data1["Throttling"] : [];
<add> var d = new Date(json.usage[usage1].values.year, (json.usage[usage1].values.month - 1), json.usage[usage1].values.day, json.usage[usage1].values.hour, json.usage[usage1].values.minutes, json.usage[usage1].values.seconds, "00");
<add> apiResponseTimeData.push({x: d, y: json.usage[usage1].values.apiResponseTime});
<add> backendLatencyData.push({x: d, y: json.usage[usage1].values.backendLatency});
<add> otherLatencyData.push({x: d, y: json.usage[usage1].values.otherLatency});
<add> requestMediationLatencyData.push({
<add> x: d,
<add> y: json.usage[usage1].values.requestMediationLatency
<add> });
<add> responseMediationLatencyData.push({
<add> x: d,
<add> y: json.usage[usage1].values.responseMediationLatency
<add> });
<add> securityLatencyData.push({x: d, y: json.usage[usage1].values.securityLatency});
<add> throttlingLatencyData.push({x: d, y: json.usage[usage1].values.throttlingLatency});
<add> data1["Total Time"] = apiResponseTimeData;
<add> data1["BackEnd"] = backendLatencyData;
<add> data1["Other"] = otherLatencyData;
<add> data1["Request Mediation"] = requestMediationLatencyData;
<add> data1["Response Mediation"] = responseMediationLatencyData;
<add> data1["Authentication"] = securityLatencyData;
<add> data1["Throttling"] = throttlingLatencyData;
<add> }
<ide> }
<ide> populateMediations(data1);
<ide> drawGraphInArea(data1,drillDown); |
|
Java | epl-1.0 | 0814c115aa0e72b9434b4258da4092504db1fa65 | 0 | hyPiRion/inlein,hyPiRion/inlein | package inlein.client;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.net.*;
/**
* Static class with a lot of utility functions.
*/
public final class Utils {
public static void downloadFile(String url, Path p) throws Exception {
Path tmp = Files.createTempFile(p.toFile().getName(), ".jar");
System.err.println("Downloading " + url + "...");
try (ReadableByteChannel src = Channels.newChannel((new URL(url)).openStream());
FileChannel dst = new FileOutputStream(tmp.toFile()).getChannel()) {
final ByteBuffer buf = ByteBuffer.allocateDirect(32 * 1024 * 1024);
while(src.read(buf) != -1) {
buf.flip();
dst.write(buf);
buf.compact();
}
buf.flip();
while(buf.hasRemaining()) {
dst.write(buf);
}
}
p.toFile().getCanonicalFile().getParentFile().mkdirs();
Files.move(tmp, p, StandardCopyOption.REPLACE_EXISTING);
}
/**
* Returns the home directory to inlein.
*/
public static String inleinHome() {
String res = System.getenv("INLEIN_HOME");
if (res == null) {
res = new File(System.getProperty("user.home"), ".inlein").getAbsolutePath();
}
return res;
}
/**
* Returns the inlein server's port. If the value returned is
* <code>null</code>, then the server is not running.
*/
public static Integer inleinPort() throws IOException {
Path p = Paths.get(inleinHome(), "port");
if (!p.toFile().exists()) {
return null;
}
byte[] stringPort = Files.readAllBytes(p);
return Integer.parseInt(new String(stringPort));
}
}
| client/src/inlein/client/Utils.java | package inlein.client;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.net.*;
/**
* Static class with a lot of utility functions.
*/
public final class Utils {
public static void downloadFile(String url, Path p) throws Exception {
Path tmp = Files.createTempFile(p.toFile().getName(), ".jar");
System.err.println("Downloading " + url + "...");
try (ReadableByteChannel src = Channels.newChannel((new URL(url)).openStream());
FileChannel dst = new FileOutputStream(tmp.toFile()).getChannel()) {
final ByteBuffer buf = ByteBuffer.allocateDirect(32 * 1024 * 1024);
while(src.read(buf) != -1) {
buf.flip();
dst.write(buf);
buf.compact();
}
buf.flip();
while(buf.hasRemaining()) {
dst.write(buf);
}
}
p.toFile().getCanonicalFile().getParentFile().mkdirs();
Files.move(tmp, p, StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
}
/**
* Returns the home directory to inlein.
*/
public static String inleinHome() {
String res = System.getenv("INLEIN_HOME");
if (res == null) {
res = new File(System.getProperty("user.home"), ".inlein").getAbsolutePath();
}
return res;
}
/**
* Returns the inlein server's port. If the value returned is
* <code>null</code>, then the server is not running.
*/
public static Integer inleinPort() throws IOException {
Path p = Paths.get(inleinHome(), "port");
if (!p.toFile().exists()) {
return null;
}
byte[] stringPort = Files.readAllBytes(p);
return Integer.parseInt(new String(stringPort));
}
}
| Don't insist on atomic move
Fixes #5
| client/src/inlein/client/Utils.java | Don't insist on atomic move | <ide><path>lient/src/inlein/client/Utils.java
<ide> }
<ide> }
<ide> p.toFile().getCanonicalFile().getParentFile().mkdirs();
<del> Files.move(tmp, p, StandardCopyOption.ATOMIC_MOVE,
<del> StandardCopyOption.REPLACE_EXISTING);
<add> Files.move(tmp, p, StandardCopyOption.REPLACE_EXISTING);
<ide> }
<ide>
<ide> /** |
|
Java | bsd-2-clause | 80c150c8e9dd52192b8db4c63c06304ada63989b | 0 | runelite/runelite,runelite/runelite,runelite/runelite | /*
* Copyright (c) 2016-2017, Adam <[email protected]>
* Copyright (c) 2018, Tomas Slusny <[email protected]>
* Copyright (c) 2019 Abex
* 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.
*
* 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 net.runelite.client.rs;
import com.google.archivepatcher.applier.FileByFileV1DeltaApplier;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingOutputStream;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import java.applet.Applet;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.StandardOpenOption;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.function.Supplier;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import javax.annotation.Nonnull;
import javax.swing.SwingUtilities;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.client.RuneLite;
import net.runelite.client.RuneLiteProperties;
import net.runelite.client.RuntimeConfig;
import net.runelite.client.RuntimeConfigLoader;
import static net.runelite.client.rs.ClientUpdateCheckMode.AUTO;
import static net.runelite.client.rs.ClientUpdateCheckMode.NONE;
import static net.runelite.client.rs.ClientUpdateCheckMode.VANILLA;
import net.runelite.client.ui.FatalErrorDialog;
import net.runelite.client.ui.SplashScreen;
import net.runelite.client.util.CountingInputStream;
import net.runelite.client.util.VerificationException;
import net.runelite.http.api.worlds.World;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@Slf4j
@SuppressWarnings({"deprecation", "removal"})
public class ClientLoader implements Supplier<Applet>
{
private static final int NUM_ATTEMPTS = 6;
private static File LOCK_FILE = new File(RuneLite.CACHE_DIR, "cache.lock");
private static File VANILLA_CACHE = new File(RuneLite.CACHE_DIR, "vanilla.cache");
private static File PATCHED_CACHE = new File(RuneLite.CACHE_DIR, "patched.cache");
private final OkHttpClient okHttpClient;
private final ClientConfigLoader clientConfigLoader;
private ClientUpdateCheckMode updateCheckMode;
private final WorldSupplier worldSupplier;
private final RuntimeConfigLoader runtimeConfigLoader;
private final String javConfigUrl;
private Object client;
public ClientLoader(OkHttpClient okHttpClient, ClientUpdateCheckMode updateCheckMode, RuntimeConfigLoader runtimeConfigLoader, String javConfigUrl)
{
this.okHttpClient = okHttpClient;
this.clientConfigLoader = new ClientConfigLoader(okHttpClient);
this.updateCheckMode = updateCheckMode;
this.worldSupplier = new WorldSupplier(okHttpClient);
this.runtimeConfigLoader = runtimeConfigLoader;
this.javConfigUrl = javConfigUrl;
}
@Override
public synchronized Applet get()
{
if (client == null)
{
client = doLoad();
}
if (client instanceof Throwable)
{
throw new RuntimeException((Throwable) client);
}
return (Applet) client;
}
private Object doLoad()
{
if (updateCheckMode == NONE)
{
return null;
}
try
{
SplashScreen.stage(0, null, "Fetching applet viewer config");
RSConfig config = downloadConfig();
SplashScreen.stage(.05, null, "Waiting for other clients to start");
LOCK_FILE.getParentFile().mkdirs();
ClassLoader classLoader;
try (FileChannel lockfile = FileChannel.open(LOCK_FILE.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
FileLock flock = lockfile.lock())
{
SplashScreen.stage(.05, null, "Downloading Old School RuneScape");
try
{
updateVanilla(config);
}
catch (IOException ex)
{
// try again with the fallback config and gamepack
if (javConfigUrl.equals(RuneLiteProperties.getJavConfig()) && !config.isFallback())
{
log.warn("Unable to download game client, attempting to use fallback config", ex);
config = downloadFallbackConfig();
updateVanilla(config);
}
else
{
throw ex;
}
}
if (updateCheckMode == AUTO)
{
SplashScreen.stage(.35, null, "Patching");
applyPatch();
}
SplashScreen.stage(.40, null, "Loading client");
File jarFile = updateCheckMode == AUTO ? PATCHED_CACHE : VANILLA_CACHE;
// create the classloader for the jar while we hold the lock, and eagerly load and link all classes
// in the jar. Otherwise the jar can change on disk and can break future classloads.
classLoader = createJarClassLoader(jarFile);
}
SplashScreen.stage(.465, "Starting", "Starting Old School RuneScape");
Applet rs = loadClient(config, classLoader);
SplashScreen.stage(.5, null, "Starting core classes");
return rs;
}
catch (OutageException e)
{
return e;
}
catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException
| VerificationException | SecurityException e)
{
log.error("Error loading RS!", e);
if (!checkOutages())
{
SwingUtilities.invokeLater(() -> FatalErrorDialog.showNetErrorWindow("loading the client", e));
}
return e;
}
}
private RSConfig downloadConfig() throws IOException
{
HttpUrl url = HttpUrl.get(javConfigUrl);
IOException err = null;
for (int attempt = 0; attempt < NUM_ATTEMPTS; attempt++)
{
try
{
RSConfig config = clientConfigLoader.fetch(url);
if (Strings.isNullOrEmpty(config.getCodeBase()) || Strings.isNullOrEmpty(config.getInitialJar()) || Strings.isNullOrEmpty(config.getInitialClass()))
{
throw new IOException("Invalid or missing jav_config");
}
return config;
}
catch (IOException e)
{
log.info("Failed to get jav_config from host \"{}\" ({})", url.host(), e.getMessage());
if (checkOutages())
{
throw new OutageException(e);
}
if (!javConfigUrl.equals(RuneLiteProperties.getJavConfig()))
{
throw e;
}
String host = worldSupplier.get().getAddress();
url = url.newBuilder().host(host).build();
err = e;
}
}
log.info("Falling back to backup client config");
try
{
return downloadFallbackConfig();
}
catch (IOException ex)
{
log.debug("error downloading backup config", ex);
throw err; // use error from Jagex's servers
}
}
@Nonnull
private RSConfig downloadFallbackConfig() throws IOException
{
RSConfig backupConfig = clientConfigLoader.fetch(HttpUrl.get(RuneLiteProperties.getJavConfigBackup()));
if (Strings.isNullOrEmpty(backupConfig.getCodeBase()) || Strings.isNullOrEmpty(backupConfig.getInitialJar()) || Strings.isNullOrEmpty(backupConfig.getInitialClass()))
{
throw new IOException("Invalid or missing jav_config");
}
if (Strings.isNullOrEmpty(backupConfig.getRuneLiteGamepack()) || Strings.isNullOrEmpty(backupConfig.getRuneLiteWorldParam()))
{
throw new IOException("Backup config does not have RuneLite gamepack url");
}
// Randomize the codebase
World world = worldSupplier.get();
backupConfig.setCodebase("http://" + world.getAddress() + "/");
// Update the world applet parameter
Map<String, String> appletProperties = backupConfig.getAppletProperties();
appletProperties.put(backupConfig.getRuneLiteWorldParam(), Integer.toString(world.getId()));
return backupConfig;
}
private void updateVanilla(RSConfig config) throws IOException, VerificationException
{
Certificate[][] jagexCertificateChains = {
loadCertificateChain("jagex.crt"),
loadCertificateChain("jagex2021.crt")
};
// Get the mtime of the first thing in the vanilla cache
// we check this against what the server gives us to let us skip downloading and patching the whole thing
try (FileChannel vanilla = FileChannel.open(VANILLA_CACHE.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE))
{
long vanillaCacheMTime = -1;
boolean vanillaCacheIsInvalid = false;
try
{
JarInputStream vanillaCacheTest = new JarInputStream(Channels.newInputStream(vanilla));
vanillaCacheTest.skip(Long.MAX_VALUE);
JarEntry je = vanillaCacheTest.getNextJarEntry();
if (je != null)
{
verifyJarEntry(je, jagexCertificateChains);
vanillaCacheMTime = je.getLastModifiedTime().toMillis();
}
else
{
vanillaCacheIsInvalid = true;
}
}
catch (Exception e)
{
log.info("Failed to read the vanilla cache: {}", e.toString());
vanillaCacheIsInvalid = true;
}
vanilla.position(0);
if (!vanillaCacheIsInvalid && "false".equals(System.getProperty("runelite.updateVanilla")))
{
return;
}
// Start downloading the vanilla client
HttpUrl url;
if (config.isFallback())
{
// If we are using the backup config, use our own gamepack and ignore the codebase
url = HttpUrl.get(config.getRuneLiteGamepack());
}
else
{
String codebase = config.getCodeBase();
String initialJar = config.getInitialJar();
url = HttpUrl.get(codebase + initialJar);
}
for (int attempt = 0; ; attempt++)
{
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = okHttpClient.newCall(request).execute())
{
// Its important to not close the response manually - this should be the only close or
// try-with-resources on this stream or it's children
if (!response.isSuccessful())
{
throw new IOException("unsuccessful response fetching gamepack: " + response.message());
}
int length = (int) response.body().contentLength();
if (length < 0)
{
length = 3 * 1024 * 1024;
}
else
{
if (!vanillaCacheIsInvalid && vanilla.size() != length)
{
// The zip trailer filetab can be missing and the ZipInputStream will not notice
log.info("Vanilla cache is the wrong size");
vanillaCacheIsInvalid = true;
}
}
final int flength = length;
TeeInputStream copyStream = new TeeInputStream(new CountingInputStream(response.body().byteStream(),
read -> SplashScreen.stage(.05, .35, null, "Downloading Old School RuneScape", read, flength, true)));
// Save the bytes from the mtime test so we can write it to disk
// if the test fails, or the cache doesn't verify
ByteArrayOutputStream preRead = new ByteArrayOutputStream();
copyStream.setOut(preRead);
JarInputStream networkJIS = new JarInputStream(copyStream);
// Get the mtime from the first entry so check it against the cache
{
JarEntry je = networkJIS.getNextJarEntry();
if (je == null)
{
throw new IOException("unable to peek first jar entry");
}
networkJIS.skip(Long.MAX_VALUE);
verifyJarEntry(je, jagexCertificateChains);
long vanillaClientMTime = je.getLastModifiedTime().toMillis();
if (!vanillaCacheIsInvalid && vanillaClientMTime != vanillaCacheMTime)
{
log.info("Vanilla cache is out of date: {} != {}", vanillaClientMTime, vanillaCacheMTime);
vanillaCacheIsInvalid = true;
}
}
// the mtime matches so the cache is probably up to date, but just make sure its fully
// intact before closing the server connection
if (!vanillaCacheIsInvalid)
{
try
{
// as with the request stream, its important to not early close vanilla too
JarInputStream vanillaCacheTest = new JarInputStream(Channels.newInputStream(vanilla));
verifyWholeJar(vanillaCacheTest, jagexCertificateChains);
}
catch (Exception e)
{
log.warn("Failed to verify the vanilla cache", e);
vanillaCacheIsInvalid = true;
}
}
if (vanillaCacheIsInvalid)
{
// the cache is not up to date, commit our peek to the file and write the rest of it, while verifying
vanilla.position(0);
OutputStream out = Channels.newOutputStream(vanilla);
out.write(preRead.toByteArray());
copyStream.setOut(out);
verifyWholeJar(networkJIS, jagexCertificateChains);
copyStream.skip(Long.MAX_VALUE); // write the trailer to the file too
out.flush();
vanilla.truncate(vanilla.position());
}
else
{
log.info("Using cached vanilla client");
}
return;
}
catch (IOException e)
{
log.warn("Failed to download gamepack from \"{}\"", url, e);
if (checkOutages())
{
throw new OutageException(e);
}
// With fallback config do 1 attempt (there are no additional urls to try)
if (!javConfigUrl.equals(RuneLiteProperties.getJavConfig()) || config.isFallback() || attempt >= NUM_ATTEMPTS)
{
throw e;
}
url = url.newBuilder().host(worldSupplier.get().getAddress()).build();
}
}
}
}
private void applyPatch() throws IOException
{
byte[] vanillaHash = new byte[64];
byte[] appliedPatchHash = new byte[64];
try (InputStream is = ClientLoader.class.getResourceAsStream("/client.serial"))
{
if (is == null)
{
SwingUtilities.invokeLater(() ->
new FatalErrorDialog("The client-patch is missing from the classpath. If you are building " +
"the client you need to re-run maven")
.addHelpButtons()
.addBuildingGuide()
.open());
throw new NullPointerException();
}
DataInputStream dis = new DataInputStream(is);
dis.readFully(vanillaHash);
dis.readFully(appliedPatchHash);
}
byte[] vanillaCacheHash = Files.asByteSource(VANILLA_CACHE).hash(Hashing.sha512()).asBytes();
if (!Arrays.equals(vanillaHash, vanillaCacheHash))
{
log.info("Client is outdated!");
updateCheckMode = VANILLA;
return;
}
if (PATCHED_CACHE.exists())
{
byte[] diskBytes = Files.asByteSource(PATCHED_CACHE).hash(Hashing.sha512()).asBytes();
if (!Arrays.equals(diskBytes, appliedPatchHash))
{
log.warn("Cached patch hash mismatches, regenerating patch");
}
else
{
log.info("Using cached patched client");
return;
}
}
try (HashingOutputStream hos = new HashingOutputStream(Hashing.sha512(), java.nio.file.Files.newOutputStream(PATCHED_CACHE.toPath()));
InputStream patch = ClientLoader.class.getResourceAsStream("/client.patch"))
{
new FileByFileV1DeltaApplier().applyDelta(VANILLA_CACHE, patch, hos);
if (!Arrays.equals(hos.hash().asBytes(), appliedPatchHash))
{
log.error("Patched client hash mismatch");
updateCheckMode = VANILLA;
return;
}
}
catch (IOException e)
{
log.error("Unable to apply patch despite hash matching", e);
updateCheckMode = VANILLA;
return;
}
}
private ClassLoader createJarClassLoader(File jar) throws IOException, ClassNotFoundException
{
try (JarFile jarFile = new JarFile(jar))
{
ClassLoader classLoader = new ClassLoader(ClientLoader.class.getClassLoader())
{
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
String entryName = name.replace('.', '/').concat(".class");
JarEntry jarEntry;
try
{
jarEntry = jarFile.getJarEntry(entryName);
}
catch (IllegalStateException ex)
{
throw new ClassNotFoundException(name, ex);
}
if (jarEntry == null)
{
throw new ClassNotFoundException(name);
}
try
{
InputStream inputStream = jarFile.getInputStream(jarEntry);
if (inputStream == null)
{
throw new ClassNotFoundException(name);
}
byte[] bytes = ByteStreams.toByteArray(inputStream);
return defineClass(name, bytes, 0, bytes.length);
}
catch (IOException e)
{
throw new ClassNotFoundException(null, e);
}
}
};
// load all of the classes in this jar; after the jar is closed the classloader
// will no longer be able to look up classes
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
if (name.endsWith(".class"))
{
name = name.substring(0, name.length() - 6);
classLoader.loadClass(name.replace('/', '.'));
}
}
return classLoader;
}
}
private Applet loadClient(RSConfig config, ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
String initialClass = config.getInitialClass();
Class<?> clientClass = classLoader.loadClass(initialClass);
Applet rs = (Applet) clientClass.newInstance();
rs.setStub(new RSAppletStub(config, runtimeConfigLoader));
if (rs instanceof Client)
{
log.info("client-patch {}", ((Client) rs).getBuildID());
}
return rs;
}
private static Certificate[] loadCertificateChain(String name)
{
try (InputStream in = ClientLoader.class.getResourceAsStream(name))
{
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
return certificates.toArray(new Certificate[0]);
}
catch (CertificateException | IOException e)
{
throw new RuntimeException("Unable to parse pinned certificates", e);
}
}
private void verifyJarEntry(JarEntry je, Certificate[][] chains) throws VerificationException
{
if (je.getName().equals("META-INF/JAGEXLTD.SF") || je.getName().equals("META-INF/JAGEXLTD.RSA"))
{
// You can't sign the signing files
return;
}
// Jar entry must match one of the trusted certificate chains
Certificate[] entryCertificates = je.getCertificates();
for (Certificate[] chain : chains)
{
if (Arrays.equals(entryCertificates, chain))
{
return;
}
}
throw new VerificationException("Unable to verify jar entry: " + je.getName());
}
private void verifyWholeJar(JarInputStream jis, Certificate[][] chains) throws IOException, VerificationException
{
for (JarEntry je; (je = jis.getNextJarEntry()) != null; )
{
jis.skip(Long.MAX_VALUE);
verifyJarEntry(je, chains);
}
}
private static class OutageException extends RuntimeException
{
private OutageException(Throwable cause)
{
super(cause);
}
}
private boolean checkOutages()
{
RuntimeConfig rtc = runtimeConfigLoader.tryGet();
if (rtc != null)
{
return rtc.showOutageMessage();
}
return false;
}
}
| runelite-client/src/main/java/net/runelite/client/rs/ClientLoader.java | /*
* Copyright (c) 2016-2017, Adam <[email protected]>
* Copyright (c) 2018, Tomas Slusny <[email protected]>
* Copyright (c) 2019 Abex
* 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.
*
* 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 net.runelite.client.rs;
import com.google.archivepatcher.applier.FileByFileV1DeltaApplier;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingOutputStream;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import java.applet.Applet;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.StandardOpenOption;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.function.Supplier;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import javax.annotation.Nonnull;
import javax.swing.SwingUtilities;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.client.RuneLite;
import net.runelite.client.RuneLiteProperties;
import net.runelite.client.RuntimeConfig;
import net.runelite.client.RuntimeConfigLoader;
import static net.runelite.client.rs.ClientUpdateCheckMode.AUTO;
import static net.runelite.client.rs.ClientUpdateCheckMode.NONE;
import static net.runelite.client.rs.ClientUpdateCheckMode.VANILLA;
import net.runelite.client.ui.FatalErrorDialog;
import net.runelite.client.ui.SplashScreen;
import net.runelite.client.util.CountingInputStream;
import net.runelite.client.util.VerificationException;
import net.runelite.http.api.worlds.World;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@Slf4j
@SuppressWarnings({"deprecation", "removal"})
public class ClientLoader implements Supplier<Applet>
{
private static final int NUM_ATTEMPTS = 6;
private static File LOCK_FILE = new File(RuneLite.CACHE_DIR, "cache.lock");
private static File VANILLA_CACHE = new File(RuneLite.CACHE_DIR, "vanilla.cache");
private static File PATCHED_CACHE = new File(RuneLite.CACHE_DIR, "patched.cache");
private final OkHttpClient okHttpClient;
private final ClientConfigLoader clientConfigLoader;
private ClientUpdateCheckMode updateCheckMode;
private final WorldSupplier worldSupplier;
private final RuntimeConfigLoader runtimeConfigLoader;
private final String javConfigUrl;
private Object client;
public ClientLoader(OkHttpClient okHttpClient, ClientUpdateCheckMode updateCheckMode, RuntimeConfigLoader runtimeConfigLoader, String javConfigUrl)
{
this.okHttpClient = okHttpClient;
this.clientConfigLoader = new ClientConfigLoader(okHttpClient);
this.updateCheckMode = updateCheckMode;
this.worldSupplier = new WorldSupplier(okHttpClient);
this.runtimeConfigLoader = runtimeConfigLoader;
this.javConfigUrl = javConfigUrl;
}
@Override
public synchronized Applet get()
{
if (client == null)
{
client = doLoad();
}
if (client instanceof Throwable)
{
throw new RuntimeException((Throwable) client);
}
return (Applet) client;
}
private Object doLoad()
{
if (updateCheckMode == NONE)
{
return null;
}
try
{
SplashScreen.stage(0, null, "Fetching applet viewer config");
RSConfig config = downloadConfig();
SplashScreen.stage(.05, null, "Waiting for other clients to start");
LOCK_FILE.getParentFile().mkdirs();
ClassLoader classLoader;
try (FileChannel lockfile = FileChannel.open(LOCK_FILE.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
FileLock flock = lockfile.lock())
{
SplashScreen.stage(.05, null, "Downloading Old School RuneScape");
try
{
updateVanilla(config);
}
catch (IOException ex)
{
// try again with the fallback config and gamepack
if (javConfigUrl.equals(RuneLiteProperties.getJavConfig()) && !config.isFallback())
{
log.warn("Unable to download game client, attempting to use fallback config", ex);
config = downloadFallbackConfig();
updateVanilla(config);
}
else
{
throw ex;
}
}
if (updateCheckMode == AUTO)
{
SplashScreen.stage(.35, null, "Patching");
applyPatch();
}
SplashScreen.stage(.40, null, "Loading client");
File jarFile = updateCheckMode == AUTO ? PATCHED_CACHE : VANILLA_CACHE;
// create the classloader for the jar while we hold the lock, and eagerly load and link all classes
// in the jar. Otherwise the jar can change on disk and can break future classloads.
classLoader = createJarClassLoader(jarFile);
}
SplashScreen.stage(.465, "Starting", "Starting Old School RuneScape");
Applet rs = loadClient(config, classLoader);
SplashScreen.stage(.5, null, "Starting core classes");
return rs;
}
catch (OutageException e)
{
return e;
}
catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException
| VerificationException | SecurityException e)
{
log.error("Error loading RS!", e);
if (!checkOutages())
{
SwingUtilities.invokeLater(() -> FatalErrorDialog.showNetErrorWindow("loading the client", e));
}
return e;
}
}
private RSConfig downloadConfig() throws IOException
{
HttpUrl url = HttpUrl.get(javConfigUrl);
IOException err = null;
for (int attempt = 0; attempt < NUM_ATTEMPTS; attempt++)
{
try
{
RSConfig config = clientConfigLoader.fetch(url);
if (Strings.isNullOrEmpty(config.getCodeBase()) || Strings.isNullOrEmpty(config.getInitialJar()) || Strings.isNullOrEmpty(config.getInitialClass()))
{
throw new IOException("Invalid or missing jav_config");
}
return config;
}
catch (IOException e)
{
log.info("Failed to get jav_config from host \"{}\" ({})", url.host(), e.getMessage());
if (checkOutages())
{
throw new OutageException(e);
}
if (!javConfigUrl.equals(RuneLiteProperties.getJavConfig()))
{
throw e;
}
String host = worldSupplier.get().getAddress();
url = url.newBuilder().host(host).build();
err = e;
}
}
log.info("Falling back to backup client config");
try
{
return downloadFallbackConfig();
}
catch (IOException ex)
{
log.debug("error downloading backup config", ex);
throw err; // use error from Jagex's servers
}
}
@Nonnull
private RSConfig downloadFallbackConfig() throws IOException
{
RSConfig backupConfig = clientConfigLoader.fetch(HttpUrl.get(RuneLiteProperties.getJavConfigBackup()));
if (Strings.isNullOrEmpty(backupConfig.getCodeBase()) || Strings.isNullOrEmpty(backupConfig.getInitialJar()) || Strings.isNullOrEmpty(backupConfig.getInitialClass()))
{
throw new IOException("Invalid or missing jav_config");
}
if (Strings.isNullOrEmpty(backupConfig.getRuneLiteGamepack()) || Strings.isNullOrEmpty(backupConfig.getRuneLiteWorldParam()))
{
throw new IOException("Backup config does not have RuneLite gamepack url");
}
// Randomize the codebase
World world = worldSupplier.get();
backupConfig.setCodebase("http://" + world.getAddress() + "/");
// Update the world applet parameter
Map<String, String> appletProperties = backupConfig.getAppletProperties();
appletProperties.put(backupConfig.getRuneLiteWorldParam(), Integer.toString(world.getId()));
return backupConfig;
}
private void updateVanilla(RSConfig config) throws IOException, VerificationException
{
Certificate[][] jagexCertificateChains = {
loadCertificateChain("jagex.crt"),
loadCertificateChain("jagex2021.crt")
};
// Get the mtime of the first thing in the vanilla cache
// we check this against what the server gives us to let us skip downloading and patching the whole thing
try (FileChannel vanilla = FileChannel.open(VANILLA_CACHE.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE))
{
long vanillaCacheMTime = -1;
boolean vanillaCacheIsInvalid = false;
try
{
JarInputStream vanillaCacheTest = new JarInputStream(Channels.newInputStream(vanilla));
vanillaCacheTest.skip(Long.MAX_VALUE);
JarEntry je = vanillaCacheTest.getNextJarEntry();
if (je != null)
{
verifyJarEntry(je, jagexCertificateChains);
vanillaCacheMTime = je.getLastModifiedTime().toMillis();
}
else
{
vanillaCacheIsInvalid = true;
}
}
catch (Exception e)
{
log.info("Failed to read the vanilla cache: {}", e.toString());
vanillaCacheIsInvalid = true;
}
vanilla.position(0);
if (!vanillaCacheIsInvalid && "false".equals(System.getProperty("runelite.updateVanilla")))
{
return;
}
// Start downloading the vanilla client
HttpUrl url;
if (config.isFallback())
{
// If we are using the backup config, use our own gamepack and ignore the codebase
url = HttpUrl.get(config.getRuneLiteGamepack());
}
else
{
String codebase = config.getCodeBase();
String initialJar = config.getInitialJar();
url = HttpUrl.get(codebase + initialJar);
}
for (int attempt = 0; ; attempt++)
{
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = okHttpClient.newCall(request).execute())
{
// Its important to not close the response manually - this should be the only close or
// try-with-resources on this stream or it's children
if (!response.isSuccessful())
{
throw new IOException("unsuccessful response fetching gamepack: " + response.message());
}
int length = (int) response.body().contentLength();
if (length < 0)
{
length = 3 * 1024 * 1024;
}
else
{
if (!vanillaCacheIsInvalid && vanilla.size() != length)
{
// The zip trailer filetab can be missing and the ZipInputStream will not notice
log.info("Vanilla cache is the wrong size");
vanillaCacheIsInvalid = true;
}
}
final int flength = length;
TeeInputStream copyStream = new TeeInputStream(new CountingInputStream(response.body().byteStream(),
read -> SplashScreen.stage(.05, .35, null, "Downloading Old School RuneScape", read, flength, true)));
// Save the bytes from the mtime test so we can write it to disk
// if the test fails, or the cache doesn't verify
ByteArrayOutputStream preRead = new ByteArrayOutputStream();
copyStream.setOut(preRead);
JarInputStream networkJIS = new JarInputStream(copyStream);
// Get the mtime from the first entry so check it against the cache
{
JarEntry je = networkJIS.getNextJarEntry();
if (je == null)
{
throw new IOException("unable to peek first jar entry");
}
networkJIS.skip(Long.MAX_VALUE);
verifyJarEntry(je, jagexCertificateChains);
long vanillaClientMTime = je.getLastModifiedTime().toMillis();
if (!vanillaCacheIsInvalid && vanillaClientMTime != vanillaCacheMTime)
{
log.info("Vanilla cache is out of date: {} != {}", vanillaClientMTime, vanillaCacheMTime);
vanillaCacheIsInvalid = true;
}
}
// the mtime matches so the cache is probably up to date, but just make sure its fully
// intact before closing the server connection
if (!vanillaCacheIsInvalid)
{
try
{
// as with the request stream, its important to not early close vanilla too
JarInputStream vanillaCacheTest = new JarInputStream(Channels.newInputStream(vanilla));
verifyWholeJar(vanillaCacheTest, jagexCertificateChains);
}
catch (Exception e)
{
log.warn("Failed to verify the vanilla cache", e);
vanillaCacheIsInvalid = true;
}
}
if (vanillaCacheIsInvalid)
{
// the cache is not up to date, commit our peek to the file and write the rest of it, while verifying
vanilla.position(0);
OutputStream out = Channels.newOutputStream(vanilla);
out.write(preRead.toByteArray());
copyStream.setOut(out);
verifyWholeJar(networkJIS, jagexCertificateChains);
copyStream.skip(Long.MAX_VALUE); // write the trailer to the file too
out.flush();
vanilla.truncate(vanilla.position());
}
else
{
log.info("Using cached vanilla client");
}
return;
}
catch (IOException e)
{
log.warn("Failed to download gamepack from \"{}\"", url, e);
if (checkOutages())
{
throw new OutageException(e);
}
// With fallback config do 1 attempt (there are no additional urls to try)
if (!javConfigUrl.equals(RuneLiteProperties.getJavConfig()) || config.isFallback() || attempt >= NUM_ATTEMPTS)
{
throw e;
}
url = url.newBuilder().host(worldSupplier.get().getAddress()).build();
}
}
}
}
private void applyPatch() throws IOException
{
byte[] vanillaHash = new byte[64];
byte[] appliedPatchHash = new byte[64];
try (InputStream is = ClientLoader.class.getResourceAsStream("/client.serial"))
{
if (is == null)
{
SwingUtilities.invokeLater(() ->
new FatalErrorDialog("The client-patch is missing from the classpath. If you are building " +
"the client you need to re-run maven")
.addHelpButtons()
.addBuildingGuide()
.open());
throw new NullPointerException();
}
DataInputStream dis = new DataInputStream(is);
dis.readFully(vanillaHash);
dis.readFully(appliedPatchHash);
}
byte[] vanillaCacheHash = Files.asByteSource(VANILLA_CACHE).hash(Hashing.sha512()).asBytes();
if (!Arrays.equals(vanillaHash, vanillaCacheHash))
{
log.info("Client is outdated!");
updateCheckMode = VANILLA;
return;
}
if (PATCHED_CACHE.exists())
{
byte[] diskBytes = Files.asByteSource(PATCHED_CACHE).hash(Hashing.sha512()).asBytes();
if (!Arrays.equals(diskBytes, appliedPatchHash))
{
log.warn("Cached patch hash mismatches, regenerating patch");
}
else
{
log.info("Using cached patched client");
return;
}
}
try (HashingOutputStream hos = new HashingOutputStream(Hashing.sha512(), new FileOutputStream(PATCHED_CACHE));
InputStream patch = ClientLoader.class.getResourceAsStream("/client.patch"))
{
new FileByFileV1DeltaApplier().applyDelta(VANILLA_CACHE, patch, hos);
if (!Arrays.equals(hos.hash().asBytes(), appliedPatchHash))
{
log.error("Patched client hash mismatch");
updateCheckMode = VANILLA;
return;
}
}
catch (IOException e)
{
log.error("Unable to apply patch despite hash matching", e);
updateCheckMode = VANILLA;
return;
}
}
private ClassLoader createJarClassLoader(File jar) throws IOException, ClassNotFoundException
{
try (JarFile jarFile = new JarFile(jar))
{
ClassLoader classLoader = new ClassLoader(ClientLoader.class.getClassLoader())
{
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
String entryName = name.replace('.', '/').concat(".class");
JarEntry jarEntry;
try
{
jarEntry = jarFile.getJarEntry(entryName);
}
catch (IllegalStateException ex)
{
throw new ClassNotFoundException(name, ex);
}
if (jarEntry == null)
{
throw new ClassNotFoundException(name);
}
try
{
InputStream inputStream = jarFile.getInputStream(jarEntry);
if (inputStream == null)
{
throw new ClassNotFoundException(name);
}
byte[] bytes = ByteStreams.toByteArray(inputStream);
return defineClass(name, bytes, 0, bytes.length);
}
catch (IOException e)
{
throw new ClassNotFoundException(null, e);
}
}
};
// load all of the classes in this jar; after the jar is closed the classloader
// will no longer be able to look up classes
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
if (name.endsWith(".class"))
{
name = name.substring(0, name.length() - 6);
classLoader.loadClass(name.replace('/', '.'));
}
}
return classLoader;
}
}
private Applet loadClient(RSConfig config, ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
String initialClass = config.getInitialClass();
Class<?> clientClass = classLoader.loadClass(initialClass);
Applet rs = (Applet) clientClass.newInstance();
rs.setStub(new RSAppletStub(config, runtimeConfigLoader));
if (rs instanceof Client)
{
log.info("client-patch {}", ((Client) rs).getBuildID());
}
return rs;
}
private static Certificate[] loadCertificateChain(String name)
{
try (InputStream in = ClientLoader.class.getResourceAsStream(name))
{
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
return certificates.toArray(new Certificate[0]);
}
catch (CertificateException | IOException e)
{
throw new RuntimeException("Unable to parse pinned certificates", e);
}
}
private void verifyJarEntry(JarEntry je, Certificate[][] chains) throws VerificationException
{
if (je.getName().equals("META-INF/JAGEXLTD.SF") || je.getName().equals("META-INF/JAGEXLTD.RSA"))
{
// You can't sign the signing files
return;
}
// Jar entry must match one of the trusted certificate chains
Certificate[] entryCertificates = je.getCertificates();
for (Certificate[] chain : chains)
{
if (Arrays.equals(entryCertificates, chain))
{
return;
}
}
throw new VerificationException("Unable to verify jar entry: " + je.getName());
}
private void verifyWholeJar(JarInputStream jis, Certificate[][] chains) throws IOException, VerificationException
{
for (JarEntry je; (je = jis.getNextJarEntry()) != null; )
{
jis.skip(Long.MAX_VALUE);
verifyJarEntry(je, chains);
}
}
private static class OutageException extends RuntimeException
{
private OutageException(Throwable cause)
{
super(cause);
}
}
private boolean checkOutages()
{
RuntimeConfig rtc = runtimeConfigLoader.tryGet();
if (rtc != null)
{
return rtc.showOutageMessage();
}
return false;
}
}
| ClientLoader: don't fail patching to hidden files
FileOutputStream (by design) passes FILE_ATTRIBUTE_NORMAL and
CREATE_ALWAYS to CreateFile, which causes it to fail with access denied
if it is opening a FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM file
See JDK-8047342
| runelite-client/src/main/java/net/runelite/client/rs/ClientLoader.java | ClientLoader: don't fail patching to hidden files | <ide><path>unelite-client/src/main/java/net/runelite/client/rs/ClientLoader.java
<ide> import java.io.ByteArrayOutputStream;
<ide> import java.io.DataInputStream;
<ide> import java.io.File;
<del>import java.io.FileOutputStream;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide> import java.io.OutputStream;
<ide> }
<ide> }
<ide>
<del> try (HashingOutputStream hos = new HashingOutputStream(Hashing.sha512(), new FileOutputStream(PATCHED_CACHE));
<add> try (HashingOutputStream hos = new HashingOutputStream(Hashing.sha512(), java.nio.file.Files.newOutputStream(PATCHED_CACHE.toPath()));
<ide> InputStream patch = ClientLoader.class.getResourceAsStream("/client.patch"))
<ide> {
<ide> new FileByFileV1DeltaApplier().applyDelta(VANILLA_CACHE, patch, hos); |
|
Java | mit | 44e259d57159f2dcf28c00de26db244ba1a6899b | 0 | AusDTO/citizenship-appointment-server,AusDTO/citizenship-appointment-server,AusDTO/citizenship-appointment-server | package au.gov.dto.dibp.appointments.qflowintegration;
import au.gov.dto.dibp.appointments.util.ResponseWrapper;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
@Service
class ApiLoginService {
private static final String SIGN_IN_TEMPLATE_PATH = "FormsSignIn.mustache";
private static final String API_SESSION_ID = "//FormsSignInResponse/FormsSignInResult";
private static final Logger LOGGER = LoggerFactory.getLogger(ApiLoginService.class);
static final int MAX_ATTEMPTS = 10;
private final String serviceAddressUser;
private final String userForceLogin;
private final List<ApiUser> apiUsers;
private final ResourceLoader resourceLoader;
private final HttpClient httpClient;
@Autowired
public ApiLoginService(ResourceLoader resourceLoader, ApiUserService apiUserService, HttpClient httpClient, @Value("${SERVICE.ADDRESS.USER}") String serviceAddressUser, @Value("${USER.FORCE.LOGIN}") String userForceLogin) {
this.resourceLoader = resourceLoader;
this.apiUsers = Collections.unmodifiableList(apiUserService.initializeApiUsers());
this.httpClient = httpClient;
this.serviceAddressUser = serviceAddressUser;
this.userForceLogin = userForceLogin;
}
public ApiSession login() {
Resource resource = resourceLoader.getResource("classpath:request_templates/" + SIGN_IN_TEMPLATE_PATH);
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
} catch (IOException e) {
throw new RuntimeException("Problem reading request template: " + SIGN_IN_TEMPLATE_PATH, e);
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Template tmpl = Mustache.compiler().compile(inputStreamReader);
for (int attempts = 1 ; attempts <= MAX_ATTEMPTS; attempts++) {
int index = new Random().nextInt(apiUsers.size());
ResponseWrapper response = sendLoginRequest(tmpl, index);
if (response!=null && response.getCode() == 200) {
String apiSessionId = response.getStringAttribute(API_SESSION_ID);
String userId = apiUsers.get(index).getUserId();
return new ApiSession(apiSessionId, userId);
}
if (attempts >= MAX_ATTEMPTS*.8) {
LOGGER.warn("Reached {} of {} max FormsSignIn attempts", attempts, MAX_ATTEMPTS);
}
}
throw new ApiLoginException("Failed to authenticate to Q-Flow API. Exceeded max FormsSignIn attempts: " + MAX_ATTEMPTS);
}
private ResponseWrapper sendLoginRequest(Template tmpl, int index) {
Map<String, String> messageParams = new HashMap<>();
messageParams.put("username", apiUsers.get(index).getUsername());
messageParams.put("password", apiUsers.get(index).getPassword());
messageParams.put("forceSignIn", userForceLogin);
messageParams.put("messageUUID", UUID.randomUUID().toString());
messageParams.put("serviceAddress", serviceAddressUser);
messageParams.put("ipAddressUUID", UUID.randomUUID().toString());
String messageBody = tmpl.execute(messageParams);
return httpClient.post(serviceAddressUser, messageBody);
}
}
| src/main/java/au/gov/dto/dibp/appointments/qflowintegration/ApiLoginService.java | package au.gov.dto.dibp.appointments.qflowintegration;
import au.gov.dto.dibp.appointments.util.ResponseWrapper;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
@Service
class ApiLoginService {
private static final String SIGN_IN_TEMPLATE_PATH = "FormsSignIn.mustache";
private static final String API_SESSION_ID = "//FormsSignInResponse/FormsSignInResult";
private static final Logger LOGGER = LoggerFactory.getLogger(ApiLoginService.class);
static final int MAX_ATTEMPTS = 10;
private final String serviceAddressUser;
private final String userForceLogin;
private final List<ApiUser> apiUsers;
private final ResourceLoader resourceLoader;
private final HttpClient httpClient;
@Autowired
public ApiLoginService(ResourceLoader resourceLoader, ApiUserService apiUserService, HttpClient httpClient, @Value("${SERVICE.ADDRESS.USER}") String serviceAddressUser, @Value("${USER.FORCE.LOGIN}") String userForceLogin) {
this.resourceLoader = resourceLoader;
this.apiUsers = Collections.unmodifiableList(apiUserService.initializeApiUsers());
this.httpClient = httpClient;
this.serviceAddressUser = serviceAddressUser;
this.userForceLogin = userForceLogin;
}
public ApiSession login() {
Resource resource = resourceLoader.getResource("classpath:request_templates/" + SIGN_IN_TEMPLATE_PATH);
InputStream inputStream = null;
try {
inputStream = resource.getInputStream();
} catch (IOException e) {
throw new RuntimeException("Problem reading request template: " + SIGN_IN_TEMPLATE_PATH, e);
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
Template tmpl = Mustache.compiler().compile(inputStreamReader);
for (int attempts = 1 ; attempts <= MAX_ATTEMPTS; attempts++) {
int index = new Random().nextInt(apiUsers.size());
ResponseWrapper response = sendLoginRequest(tmpl, index);
if (response!=null && response.getCode() == 200) {
String apiSessionId = response.getStringAttribute(API_SESSION_ID);
String userId = apiUsers.get(index).getUserId();
return new ApiSession(apiSessionId, userId);
}
if (attempts >= MAX_ATTEMPTS*.8) {
LOGGER.warn("Reached {} of {} max FormsSignIn attempts", attempts, MAX_ATTEMPTS);
}
}
throw new ApiLoginException("Failed to authenticate to Q-Flow API. Exceeded max FormsSignIn attempts: " + MAX_ATTEMPTS);
}
private ResponseWrapper sendLoginRequest(Template tmpl, int index) {
Map<String, String> messageParams = new HashMap<>();
messageParams.put("username", apiUsers.get(index).getUsername());
messageParams.put("password", apiUsers.get(index).getPassword());
messageParams.put("forceSignIn", userForceLogin);
messageParams.put("messageUUID", UUID.randomUUID().toString());
messageParams.put("serviceAddress", serviceAddressUser);
messageParams.put("ipAddressUUID", UUID.randomUUID().toString());
String messageBody = tmpl.execute(messageParams);
try{
return httpClient.post(serviceAddressUser, messageBody);
}catch(RuntimeException e){
//do nothing, retries
return null;
}
}
}
| Don't swallow exceptions on login
| src/main/java/au/gov/dto/dibp/appointments/qflowintegration/ApiLoginService.java | Don't swallow exceptions on login | <ide><path>rc/main/java/au/gov/dto/dibp/appointments/qflowintegration/ApiLoginService.java
<ide> messageParams.put("ipAddressUUID", UUID.randomUUID().toString());
<ide> String messageBody = tmpl.execute(messageParams);
<ide>
<del> try{
<del> return httpClient.post(serviceAddressUser, messageBody);
<del> }catch(RuntimeException e){
<del> //do nothing, retries
<del> return null;
<del> }
<add> return httpClient.post(serviceAddressUser, messageBody);
<ide> }
<ide> } |
|
Java | mit | dac6f6acaaf7439ef7bc38f22fdba2db19bdbbcf | 0 | noogotte/DiamondRush | package fr.aumgn.diamondrush.command;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import fr.aumgn.bukkitutils.command.Command;
import fr.aumgn.bukkitutils.command.CommandArgs;
import fr.aumgn.bukkitutils.command.NestedCommands;
import fr.aumgn.bukkitutils.command.exception.CommandError;
import fr.aumgn.bukkitutils.command.Commands;
import fr.aumgn.diamondrush.DiamondRush;
import fr.aumgn.diamondrush.exception.PlayerNotInGame;
import fr.aumgn.diamondrush.game.Game;
import fr.aumgn.diamondrush.game.Spectators;
import fr.aumgn.diamondrush.game.Team;
import fr.aumgn.diamondrush.region.TeamSpawn;
import fr.aumgn.diamondrush.region.Totem;
import fr.aumgn.diamondrush.stage.JoinStage;
@NestedCommands(name = "diamondrush")
public class SpectatorsCommands implements Commands {
@Command(name = "watch")
public void watchGame(Player player, CommandArgs args) {
Game game = DiamondRush.getGame();
if (game.contains(player)) {
throw new CommandError("Vous êtes déjà dans la partie.");
}
if (game.getStage() instanceof JoinStage) {
throw new CommandError(
"Impossible de passer en spectateur durant une phase de join.");
}
Spectators spectators = game.getSpectators();
if (spectators.contains(player)) {
throw new CommandError("Vous êtes déjà spectateur.");
}
game.sendMessage(player.getDisplayName() + ChatColor.YELLOW +
" est maintenant spectateur.");
spectators.add(player);
player.sendMessage(ChatColor.GREEN + "Vous êtes maintenant spectateur.");
}
private void ensureIsSpectator(Player player) {
Game game = DiamondRush.getGame();
if (!game.getSpectators().contains(player)) {
throw new CommandError("Cette commande n'est utilisable que pour un spectateur.");
}
}
private Player matchPlayer(String name) {
List<Player> players = Bukkit.matchPlayer(name);
if (players.size() > 1) {
throw new CommandError("Plus d'un joueur trouvés avec le motif " + name + ".");
} else if (players.size() < 1) {
throw new CommandError("Aucun joueur trouvé.");
}
return players.get(0);
}
@Command(name = "unwatch", max = 1)
public void unwatchGame(Player player, CommandArgs args) {
Player spectator;
if (args.length() == 0) {
spectator = player;
} else {
spectator = matchPlayer(args.get(0));
}
ensureIsSpectator(spectator);
Game game = DiamondRush.getGame();
game.getSpectators().remove(spectator);
spectator.sendMessage(ChatColor.GREEN + "Vous n'êtes plus spectateur.");
game.sendMessage(spectator.getDisplayName() + ChatColor.YELLOW +
" n'est plus spectateur.");
}
@Command(name = "tp-player", min = 1, max = 1)
public void tpPlayer(Player player, CommandArgs args) {
ensureIsSpectator(player);
Game game = DiamondRush.getGame();
Player target = matchPlayer(args.get(0));
if (!game.contains(target) || !game.getSpectators().contains(player)) {
throw new PlayerNotInGame();
}
player.teleport(target);
player.sendMessage(ChatColor.GREEN + "Poof !");
}
@Command(name = "tp-team", min = 1, max = 1, flags = "sf")
public void tpTeam(Player player, CommandArgs args) {
ensureIsSpectator(player);
Game game = DiamondRush.getGame();
String arg = args.get(0);
Team team = game.getTeam(arg);
if (args.hasFlag('f')) {
Player foreman = team.getForeman();
if (foreman == null) {
throw new CommandError("Cette équipe n'a pas encore de chef d'équipe.");
}
player.teleport(foreman);
} else if (args.hasFlag('s')) {
TeamSpawn spawn = team.getSpawn();
if (spawn == null) {
throw new CommandError("Cette équipe n'a pas encore de spawn.");
}
Location loc = spawn.getTeleportLocation(game.getWorld(), game.getSpawn());
player.teleport(loc);
} else {
Totem totem = team.getTotem();
if (totem == null) {
throw new CommandError("Cette équipe n'a pas encore de totem.");
}
Location loc = totem.getTeleportLocation(game.getWorld(), game.getSpawn());
player.teleport(loc);
}
player.sendMessage(ChatColor.GREEN + "Poof !");
}
}
| src/main/java/fr/aumgn/diamondrush/command/SpectatorsCommands.java | package fr.aumgn.diamondrush.command;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import fr.aumgn.bukkitutils.command.Command;
import fr.aumgn.bukkitutils.command.CommandArgs;
import fr.aumgn.bukkitutils.command.NestedCommands;
import fr.aumgn.bukkitutils.command.exception.CommandError;
import fr.aumgn.bukkitutils.command.Commands;
import fr.aumgn.diamondrush.DiamondRush;
import fr.aumgn.diamondrush.exception.PlayerNotInGame;
import fr.aumgn.diamondrush.game.Game;
import fr.aumgn.diamondrush.game.Spectators;
import fr.aumgn.diamondrush.game.Team;
import fr.aumgn.diamondrush.region.TeamSpawn;
import fr.aumgn.diamondrush.region.Totem;
import fr.aumgn.diamondrush.stage.JoinStage;
@NestedCommands(name = "diamondrush")
public class SpectatorsCommands implements Commands {
@Command(name = "watch")
public void watchGame(Player player, CommandArgs args) {
Game game = DiamondRush.getGame();
if (game.contains(player)) {
throw new CommandError("Vous êtes déjà dans la partie.");
}
if (game.getStage() instanceof JoinStage) {
throw new CommandError(
"Impossible de passer en spectateur durant une phase de join.");
}
Spectators spectators = game.getSpectators();
if (spectators.contains(player)) {
throw new CommandError("Vous êtes déjà spectateur.");
}
game.sendMessage(player.getDisplayName() + ChatColor.YELLOW +
" est maintenant spectateur.");
spectators.add(player);
player.sendMessage(ChatColor.GREEN + "Vous êtes maintenant spectateur.");
}
private void ensureIsSpectator(Player player) {
Game game = DiamondRush.getGame();
if (!game.getSpectators().contains(player)) {
throw new CommandError("Cette commande n'est utilisable qu'en tant que spectateur.");
}
}
private Player matchPlayer(String name) {
List<Player> players = Bukkit.matchPlayer(name);
if (players.size() > 1) {
throw new CommandError("Plus d'un joueur trouvés avec le motif " + name + ".");
} else if (players.size() < 1) {
throw new CommandError("Aucun joueur trouvé.");
}
return players.get(0);
}
@Command(name = "unwatch", max = 1)
public void unwatchGame(Player player, CommandArgs args) {
ensureIsSpectator(player);
Game game = DiamondRush.getGame();
Player spectator;
if (args.length() == 0) {
spectator = player;
} else {
spectator = matchPlayer(args.get(0));
}
game.getSpectators().remove(spectator);
player.sendMessage(ChatColor.GREEN + "Vous n'êtes plus spectateur.");
game.sendMessage(player.getDisplayName() + ChatColor.YELLOW +
" n'est plus spectateur.");
}
@Command(name = "tp-player", min = 1, max = 1)
public void tpPlayer(Player player, CommandArgs args) {
ensureIsSpectator(player);
Game game = DiamondRush.getGame();
Player target = matchPlayer(args.get(0));
if (!game.contains(target) || !game.getSpectators().contains(player)) {
throw new PlayerNotInGame();
}
player.teleport(target);
player.sendMessage(ChatColor.GREEN + "Poof !");
}
@Command(name = "tp-team", min = 1, max = 1, flags = "sf")
public void tpTeam(Player player, CommandArgs args) {
ensureIsSpectator(player);
Game game = DiamondRush.getGame();
String arg = args.get(0);
Team team = game.getTeam(arg);
if (args.hasFlag('f')) {
Player foreman = team.getForeman();
if (foreman == null) {
throw new CommandError("Cette équipe n'a pas encore de chef d'équipe.");
}
player.teleport(foreman);
} else if (args.hasFlag('s')) {
TeamSpawn spawn = team.getSpawn();
if (spawn == null) {
throw new CommandError("Cette équipe n'a pas encore de spawn.");
}
Location loc = spawn.getTeleportLocation(game.getWorld(), game.getSpawn());
player.teleport(loc);
} else {
Totem totem = team.getTotem();
if (totem == null) {
throw new CommandError("Cette équipe n'a pas encore de totem.");
}
Location loc = totem.getTeleportLocation(game.getWorld(), game.getSpawn());
player.teleport(loc);
}
player.sendMessage(ChatColor.GREEN + "Poof !");
}
}
| Fix unwatch command
| src/main/java/fr/aumgn/diamondrush/command/SpectatorsCommands.java | Fix unwatch command | <ide><path>rc/main/java/fr/aumgn/diamondrush/command/SpectatorsCommands.java
<ide> private void ensureIsSpectator(Player player) {
<ide> Game game = DiamondRush.getGame();
<ide> if (!game.getSpectators().contains(player)) {
<del> throw new CommandError("Cette commande n'est utilisable qu'en tant que spectateur.");
<add> throw new CommandError("Cette commande n'est utilisable que pour un spectateur.");
<ide> }
<ide> }
<ide>
<ide>
<ide> @Command(name = "unwatch", max = 1)
<ide> public void unwatchGame(Player player, CommandArgs args) {
<del> ensureIsSpectator(player);
<del> Game game = DiamondRush.getGame();
<del>
<ide> Player spectator;
<ide> if (args.length() == 0) {
<ide> spectator = player;
<ide> spectator = matchPlayer(args.get(0));
<ide> }
<ide>
<add> ensureIsSpectator(spectator);
<add> Game game = DiamondRush.getGame();
<add>
<ide> game.getSpectators().remove(spectator);
<del> player.sendMessage(ChatColor.GREEN + "Vous n'êtes plus spectateur.");
<del> game.sendMessage(player.getDisplayName() + ChatColor.YELLOW +
<add> spectator.sendMessage(ChatColor.GREEN + "Vous n'êtes plus spectateur.");
<add> game.sendMessage(spectator.getDisplayName() + ChatColor.YELLOW +
<ide> " n'est plus spectateur.");
<ide> }
<ide> |
|
Java | apache-2.0 | 45df3a467d47956867ab371d785c663e21c65fb5 | 0 | k21/buck,brettwooldridge/buck,Dominator008/buck,janicduplessis/buck,shybovycha/buck,shybovycha/buck,janicduplessis/buck,dsyang/buck,facebook/buck,zhan-xiong/buck,clonetwin26/buck,zpao/buck,JoelMarcey/buck,brettwooldridge/buck,shs96c/buck,ilya-klyuchnikov/buck,k21/buck,darkforestzero/buck,shs96c/buck,davido/buck,k21/buck,bocon13/buck,marcinkwiatkowski/buck,rowillia/buck,LegNeato/buck,shybovycha/buck,clonetwin26/buck,darkforestzero/buck,romanoid/buck,Dominator008/buck,zpao/buck,LegNeato/buck,daedric/buck,LegNeato/buck,OkBuilds/buck,zhan-xiong/buck,sdwilsh/buck,justinmuller/buck,shybovycha/buck,rmaz/buck,raviagarwal7/buck,sdwilsh/buck,marcinkwiatkowski/buck,zhan-xiong/buck,SeleniumHQ/buck,brettwooldridge/buck,grumpyjames/buck,dsyang/buck,OkBuilds/buck,SeleniumHQ/buck,Addepar/buck,illicitonion/buck,bocon13/buck,daedric/buck,ilya-klyuchnikov/buck,davido/buck,davido/buck,daedric/buck,mikekap/buck,romanoid/buck,justinmuller/buck,SeleniumHQ/buck,robbertvanginkel/buck,zhan-xiong/buck,LegNeato/buck,darkforestzero/buck,marcinkwiatkowski/buck,nguyentruongtho/buck,vschs007/buck,facebook/buck,darkforestzero/buck,darkforestzero/buck,mikekap/buck,ilya-klyuchnikov/buck,justinmuller/buck,robbertvanginkel/buck,Dominator008/buck,robbertvanginkel/buck,LegNeato/buck,SeleniumHQ/buck,shs96c/buck,SeleniumHQ/buck,justinmuller/buck,marcinkwiatkowski/buck,janicduplessis/buck,SeleniumHQ/buck,dsyang/buck,justinmuller/buck,rmaz/buck,mikekap/buck,Dominator008/buck,shs96c/buck,vschs007/buck,nguyentruongtho/buck,zpao/buck,ilya-klyuchnikov/buck,Addepar/buck,OkBuilds/buck,darkforestzero/buck,marcinkwiatkowski/buck,LegNeato/buck,grumpyjames/buck,marcinkwiatkowski/buck,JoelMarcey/buck,davido/buck,darkforestzero/buck,Addepar/buck,vschs007/buck,illicitonion/buck,darkforestzero/buck,shs96c/buck,raviagarwal7/buck,JoelMarcey/buck,OkBuilds/buck,grumpyjames/buck,OkBuilds/buck,darkforestzero/buck,clonetwin26/buck,grumpyjames/buck,raviagarwal7/buck,raviagarwal7/buck,justinmuller/buck,mikekap/buck,nguyentruongtho/buck,SeleniumHQ/buck,robbertvanginkel/buck,justinmuller/buck,Dominator008/buck,OkBuilds/buck,grumpyjames/buck,romanoid/buck,clonetwin26/buck,marcinkwiatkowski/buck,shybovycha/buck,zhan-xiong/buck,k21/buck,davido/buck,JoelMarcey/buck,rowillia/buck,bocon13/buck,janicduplessis/buck,davido/buck,shybovycha/buck,rowillia/buck,zhan-xiong/buck,ilya-klyuchnikov/buck,illicitonion/buck,Addepar/buck,daedric/buck,ilya-klyuchnikov/buck,rowillia/buck,ilya-klyuchnikov/buck,bocon13/buck,SeleniumHQ/buck,raviagarwal7/buck,bocon13/buck,rowillia/buck,shs96c/buck,darkforestzero/buck,clonetwin26/buck,SeleniumHQ/buck,daedric/buck,JoelMarcey/buck,SeleniumHQ/buck,facebook/buck,kageiit/buck,ilya-klyuchnikov/buck,mikekap/buck,mikekap/buck,janicduplessis/buck,marcinkwiatkowski/buck,marcinkwiatkowski/buck,zhan-xiong/buck,illicitonion/buck,Addepar/buck,brettwooldridge/buck,facebook/buck,shs96c/buck,bocon13/buck,clonetwin26/buck,romanoid/buck,Dominator008/buck,romanoid/buck,rmaz/buck,facebook/buck,Addepar/buck,raviagarwal7/buck,shs96c/buck,dsyang/buck,JoelMarcey/buck,zhan-xiong/buck,k21/buck,shs96c/buck,marcinkwiatkowski/buck,grumpyjames/buck,darkforestzero/buck,OkBuilds/buck,shybovycha/buck,mikekap/buck,grumpyjames/buck,dsyang/buck,grumpyjames/buck,davido/buck,sdwilsh/buck,kageiit/buck,LegNeato/buck,shybovycha/buck,mikekap/buck,LegNeato/buck,Dominator008/buck,dsyang/buck,k21/buck,vschs007/buck,clonetwin26/buck,robbertvanginkel/buck,rmaz/buck,romanoid/buck,brettwooldridge/buck,daedric/buck,rowillia/buck,kageiit/buck,janicduplessis/buck,brettwooldridge/buck,vschs007/buck,bocon13/buck,kageiit/buck,ilya-klyuchnikov/buck,robbertvanginkel/buck,Addepar/buck,bocon13/buck,ilya-klyuchnikov/buck,Dominator008/buck,darkforestzero/buck,LegNeato/buck,brettwooldridge/buck,rmaz/buck,k21/buck,janicduplessis/buck,vschs007/buck,kageiit/buck,sdwilsh/buck,shybovycha/buck,Addepar/buck,clonetwin26/buck,zpao/buck,vschs007/buck,romanoid/buck,shybovycha/buck,vschs007/buck,daedric/buck,shs96c/buck,marcinkwiatkowski/buck,robbertvanginkel/buck,sdwilsh/buck,janicduplessis/buck,zhan-xiong/buck,vschs007/buck,raviagarwal7/buck,romanoid/buck,OkBuilds/buck,davido/buck,daedric/buck,JoelMarcey/buck,illicitonion/buck,LegNeato/buck,marcinkwiatkowski/buck,k21/buck,LegNeato/buck,SeleniumHQ/buck,JoelMarcey/buck,rowillia/buck,zhan-xiong/buck,facebook/buck,ilya-klyuchnikov/buck,illicitonion/buck,facebook/buck,robbertvanginkel/buck,SeleniumHQ/buck,zhan-xiong/buck,mikekap/buck,dsyang/buck,bocon13/buck,LegNeato/buck,Addepar/buck,janicduplessis/buck,raviagarwal7/buck,robbertvanginkel/buck,romanoid/buck,robbertvanginkel/buck,justinmuller/buck,vschs007/buck,sdwilsh/buck,grumpyjames/buck,dsyang/buck,dsyang/buck,robbertvanginkel/buck,illicitonion/buck,bocon13/buck,OkBuilds/buck,justinmuller/buck,Addepar/buck,OkBuilds/buck,zpao/buck,rmaz/buck,sdwilsh/buck,raviagarwal7/buck,justinmuller/buck,shs96c/buck,k21/buck,raviagarwal7/buck,davido/buck,rowillia/buck,mikekap/buck,daedric/buck,clonetwin26/buck,illicitonion/buck,Dominator008/buck,grumpyjames/buck,clonetwin26/buck,dsyang/buck,vschs007/buck,kageiit/buck,dsyang/buck,justinmuller/buck,rmaz/buck,romanoid/buck,daedric/buck,brettwooldridge/buck,sdwilsh/buck,rmaz/buck,rowillia/buck,OkBuilds/buck,robbertvanginkel/buck,shs96c/buck,k21/buck,sdwilsh/buck,davido/buck,shybovycha/buck,rowillia/buck,sdwilsh/buck,romanoid/buck,JoelMarcey/buck,JoelMarcey/buck,marcinkwiatkowski/buck,Addepar/buck,clonetwin26/buck,brettwooldridge/buck,romanoid/buck,mikekap/buck,rowillia/buck,nguyentruongtho/buck,shs96c/buck,rmaz/buck,janicduplessis/buck,rowillia/buck,rmaz/buck,zhan-xiong/buck,dsyang/buck,k21/buck,rmaz/buck,OkBuilds/buck,brettwooldridge/buck,zhan-xiong/buck,Dominator008/buck,janicduplessis/buck,robbertvanginkel/buck,rmaz/buck,k21/buck,SeleniumHQ/buck,sdwilsh/buck,nguyentruongtho/buck,davido/buck,JoelMarcey/buck,vschs007/buck,raviagarwal7/buck,daedric/buck,nguyentruongtho/buck,raviagarwal7/buck,bocon13/buck,clonetwin26/buck,daedric/buck,brettwooldridge/buck,brettwooldridge/buck,JoelMarcey/buck,shybovycha/buck,vschs007/buck,Dominator008/buck,daedric/buck,ilya-klyuchnikov/buck,illicitonion/buck,Addepar/buck,davido/buck,sdwilsh/buck,nguyentruongtho/buck,shybovycha/buck,dsyang/buck,mikekap/buck,romanoid/buck,Dominator008/buck,OkBuilds/buck,sdwilsh/buck,LegNeato/buck,bocon13/buck,k21/buck,Addepar/buck,illicitonion/buck,illicitonion/buck,kageiit/buck,illicitonion/buck,darkforestzero/buck,zpao/buck,ilya-klyuchnikov/buck,justinmuller/buck,grumpyjames/buck,rmaz/buck,JoelMarcey/buck,janicduplessis/buck,davido/buck,grumpyjames/buck,justinmuller/buck,clonetwin26/buck,illicitonion/buck,brettwooldridge/buck,zpao/buck,raviagarwal7/buck | /*
* Copyright 2015-present Facebook, 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.facebook.buck.apple;
import com.dd.plist.NSObject;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.Pair;
import com.facebook.buck.rules.RuleKeyAppendable;
import com.facebook.buck.rules.RuleKeyBuilder;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.hash.HashCode;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.Map.Entry;
/**
* A collection of provisioning profiles.
*/
public class ProvisioningProfileStore implements RuleKeyAppendable {
public static final Optional<ImmutableMap<String, NSObject>> MATCH_ANY_ENTITLEMENT =
Optional.<ImmutableMap<String, NSObject>>absent();
public static final Optional<ImmutableList<CodeSignIdentity>> MATCH_ANY_IDENTITY =
Optional.<ImmutableList<CodeSignIdentity>>absent();
private static final Logger LOG = Logger.get(ProvisioningProfileStore.class);
private final Supplier<ImmutableList<ProvisioningProfileMetadata>>
provisioningProfilesSupplier;
private ProvisioningProfileStore(
Supplier<ImmutableList<ProvisioningProfileMetadata>> provisioningProfilesSupplier) {
this.provisioningProfilesSupplier = provisioningProfilesSupplier;
}
public ImmutableList<ProvisioningProfileMetadata> getProvisioningProfiles() {
return provisioningProfilesSupplier.get();
}
public Optional<ProvisioningProfileMetadata> getProvisioningProfileByUUID(
String provisioningProfileUUID) {
for (ProvisioningProfileMetadata profile : getProvisioningProfiles()) {
if (profile.getUUID().equals(provisioningProfileUUID)) {
return Optional.of(profile);
}
}
return Optional.absent();
}
// If multiple valid ones, find the one which matches the most specifically. I.e.,
// XXXXXXXXXX.com.example.* will match over XXXXXXXXXX.* for com.example.TestApp
public Optional<ProvisioningProfileMetadata> getBestProvisioningProfile(
String bundleID,
Optional<ImmutableMap<String, NSObject>> entitlements,
Optional<? extends Iterable<CodeSignIdentity>> identities) {
final Optional<String> prefix;
if (entitlements.isPresent()) {
prefix = Optional.of(ProvisioningProfileMetadata.prefixFromEntitlements(entitlements.get()));
} else {
prefix = Optional.<String>absent();
}
int bestMatchLength = -1;
Optional<ProvisioningProfileMetadata> bestMatch = Optional.absent();
for (ProvisioningProfileMetadata profile : getProvisioningProfiles()) {
if (profile.getExpirationDate().after(new Date())) {
Pair<String, String> appID = profile.getAppID();
LOG.debug("Looking at provisioning profile " + profile.getUUID() + "," + appID.toString());
if (!prefix.isPresent() || prefix.get().equals(appID.getFirst())) {
String profileBundleID = appID.getSecond();
boolean match;
if (profileBundleID.endsWith("*")) {
// Chop the ending * if wildcard.
profileBundleID =
profileBundleID.substring(0, profileBundleID.length() - 1);
match = bundleID.startsWith(profileBundleID);
} else {
match = (bundleID.equals(profileBundleID));
}
if (!match) {
LOG.debug("Ignoring non-matching ID for profile " + profile.getUUID());
}
// Match against other keys of the entitlements. Otherwise, we could potentially select
// a profile that doesn't have all the needed entitlements, causing a error when
// installing to device.
//
// For example: get-task-allow, aps-environment, etc.
if (match && entitlements.isPresent()) {
ImmutableMap<String, NSObject> entitlementsDict = entitlements.get();
ImmutableMap<String, NSObject> profileEntitlements = profile.getEntitlements();
for (Entry<String, NSObject> entry : entitlementsDict.entrySet()) {
if (!(entry.getKey().equals("keychain-access-groups") ||
entry.getKey().equals("application-identifier") ||
entry.getValue().equals(profileEntitlements.get(entry.getKey())))) {
match = false;
LOG.debug("Ignoring profile " + profile.getUUID() +
" with mismatched entitlement " + entry.getKey() + "; value is " +
profileEntitlements.get(entry.getKey()) + " but expected " + entry.getValue());
break;
}
}
}
// Reject any certificate which we know we can't sign with the supplied identities.
ImmutableSet<HashCode> validFingerprints = profile.getDeveloperCertificateFingerprints();
if (match && identities.isPresent() && !validFingerprints.isEmpty()) {
match = false;
for (CodeSignIdentity identity : identities.get()) {
Optional<HashCode> fingerprint = identity.getFingerprint();
if (fingerprint.isPresent() && validFingerprints.contains(fingerprint.get())) {
match = true;
break;
}
}
if (!match) {
LOG.debug("Ignoring profile " + profile.getUUID() +
" because it can't be signed with any valid identity in the current keychain.");
}
}
if (match && profileBundleID.length() > bestMatchLength) {
bestMatchLength = profileBundleID.length();
bestMatch = Optional.of(profile);
}
}
} else {
LOG.debug("Ignoring expired profile " + profile.getUUID());
}
}
LOG.debug("Found provisioning profile " + bestMatch.toString());
return bestMatch;
}
// TODO(yiding): remove this once the precise provisioning profile can be determined.
@Override
public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) {
return builder.setReflectively("provisioning-profile-store", getProvisioningProfiles());
}
public static ProvisioningProfileStore fromSearchPath(final Path searchPath) {
LOG.debug("Provisioning profile search path: " + searchPath);
return new ProvisioningProfileStore(Suppliers.memoize(
new Supplier<ImmutableList<ProvisioningProfileMetadata>>() {
@Override
public ImmutableList<ProvisioningProfileMetadata> get() {
final ImmutableList.Builder<ProvisioningProfileMetadata> profilesBuilder =
ImmutableList.builder();
try {
Files.walkFileTree(
searchPath.toAbsolutePath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (file.toString().endsWith(".mobileprovision")) {
try {
ProvisioningProfileMetadata profile =
ProvisioningProfileMetadata.fromProvisioningProfilePath(file);
profilesBuilder.add(profile);
} catch (IOException | IllegalArgumentException e) {
LOG.error(e, "Ignoring invalid or malformed .mobileprovision file");
} catch (InterruptedException e) {
throw new IOException(e);
}
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
if (e.getCause() instanceof InterruptedException) {
LOG.error(e, "Interrupted while searching for mobileprovision files");
} else {
LOG.error(e, "Error while searching for mobileprovision files");
}
}
return profilesBuilder.build();
}
}
));
}
public static ProvisioningProfileStore fromProvisioningProfiles(
Iterable<ProvisioningProfileMetadata> profiles) {
return new ProvisioningProfileStore(Suppliers.ofInstance(ImmutableList.copyOf(profiles)));
}
}
| src/com/facebook/buck/apple/ProvisioningProfileStore.java | /*
* Copyright 2015-present Facebook, 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.facebook.buck.apple;
import com.dd.plist.NSObject;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.Pair;
import com.facebook.buck.rules.RuleKeyAppendable;
import com.facebook.buck.rules.RuleKeyBuilder;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.hash.HashCode;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.Map.Entry;
/**
* A collection of provisioning profiles.
*/
public class ProvisioningProfileStore implements RuleKeyAppendable {
public static final Optional<ImmutableMap<String, NSObject>> MATCH_ANY_ENTITLEMENT =
Optional.<ImmutableMap<String, NSObject>>absent();
public static final Optional<ImmutableList<CodeSignIdentity>> MATCH_ANY_IDENTITY =
Optional.<ImmutableList<CodeSignIdentity>>absent();
private static final Logger LOG = Logger.get(ProvisioningProfileStore.class);
private final Supplier<ImmutableList<ProvisioningProfileMetadata>>
provisioningProfilesSupplier;
private ProvisioningProfileStore(
Supplier<ImmutableList<ProvisioningProfileMetadata>> provisioningProfilesSupplier) {
this.provisioningProfilesSupplier = provisioningProfilesSupplier;
}
public ImmutableList<ProvisioningProfileMetadata> getProvisioningProfiles() {
return provisioningProfilesSupplier.get();
}
public Optional<ProvisioningProfileMetadata> getProvisioningProfileByUUID(
String provisioningProfileUUID) {
for (ProvisioningProfileMetadata profile : getProvisioningProfiles()) {
if (profile.getUUID().equals(provisioningProfileUUID)) {
return Optional.of(profile);
}
}
return Optional.absent();
}
// If multiple valid ones, find the one which matches the most specifically. I.e.,
// XXXXXXXXXX.com.example.* will match over XXXXXXXXXX.* for com.example.TestApp
public Optional<ProvisioningProfileMetadata> getBestProvisioningProfile(
String bundleID,
Optional<ImmutableMap<String, NSObject>> entitlements,
Optional<? extends Iterable<CodeSignIdentity>> identities) {
final Optional<String> prefix;
if (entitlements.isPresent()) {
prefix = Optional.of(ProvisioningProfileMetadata.prefixFromEntitlements(entitlements.get()));
} else {
prefix = Optional.<String>absent();
}
int bestMatchLength = -1;
Optional<ProvisioningProfileMetadata> bestMatch = Optional.absent();
for (ProvisioningProfileMetadata profile : getProvisioningProfiles()) {
if (profile.getExpirationDate().after(new Date())) {
Pair<String, String> appID = profile.getAppID();
LOG.debug("Looking at provisioning profile " + profile.getUUID() + "," + appID.toString());
if (!prefix.isPresent() || prefix.get().equals(appID.getFirst())) {
String profileBundleID = appID.getSecond();
boolean match;
if (profileBundleID.endsWith("*")) {
// Chop the ending * if wildcard.
profileBundleID =
profileBundleID.substring(0, profileBundleID.length() - 1);
match = bundleID.startsWith(profileBundleID);
} else {
match = (bundleID.equals(profileBundleID));
}
// Match against other keys of the entitlements. Otherwise, we could potentially select
// a profile that doesn't have all the needed entitlements, causing a error when
// installing to device.
//
// For example: get-task-allow, aps-environment, etc.
if (match && entitlements.isPresent()) {
ImmutableMap<String, NSObject> entitlementsDict = entitlements.get();
ImmutableMap<String, NSObject> profileEntitlements = profile.getEntitlements();
for (Entry<String, NSObject> entry : entitlementsDict.entrySet()) {
if (!(entry.getKey().equals("keychain-access-groups") ||
entry.getKey().equals("application-identifier") ||
entry.getValue().equals(profileEntitlements.get(entry.getKey())))) {
match = false;
break;
}
}
}
// Reject any certificate which we know we can't sign with the supplied identities.
ImmutableSet<HashCode> validFingerprints = profile.getDeveloperCertificateFingerprints();
if (match && identities.isPresent() && !validFingerprints.isEmpty()) {
match = false;
for (CodeSignIdentity identity : identities.get()) {
Optional<HashCode> fingerprint = identity.getFingerprint();
if (fingerprint.isPresent() && validFingerprints.contains(fingerprint.get())) {
match = true;
break;
}
}
}
if (match && profileBundleID.length() > bestMatchLength) {
bestMatchLength = profileBundleID.length();
bestMatch = Optional.of(profile);
}
}
}
}
LOG.debug("Found provisioning profile " + bestMatch.toString());
return bestMatch;
}
// TODO(yiding): remove this once the precise provisioning profile can be determined.
@Override
public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) {
return builder.setReflectively("provisioning-profile-store", getProvisioningProfiles());
}
public static ProvisioningProfileStore fromSearchPath(final Path searchPath) {
return new ProvisioningProfileStore(Suppliers.memoize(
new Supplier<ImmutableList<ProvisioningProfileMetadata>>() {
@Override
public ImmutableList<ProvisioningProfileMetadata> get() {
final ImmutableList.Builder<ProvisioningProfileMetadata> profilesBuilder =
ImmutableList.builder();
try {
Files.walkFileTree(
searchPath.toAbsolutePath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (file.toString().endsWith(".mobileprovision")) {
try {
ProvisioningProfileMetadata profile =
ProvisioningProfileMetadata.fromProvisioningProfilePath(file);
profilesBuilder.add(profile);
} catch (IOException | IllegalArgumentException e) {
LOG.error(e, "Ignoring invalid or malformed .mobileprovision file");
} catch (InterruptedException e) {
throw new IOException(e);
}
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
if (e.getCause() instanceof InterruptedException) {
LOG.error(e, "Interrupted while searching for mobileprovision files");
} else {
LOG.error(e, "Error while searching for mobileprovision files");
}
}
return profilesBuilder.build();
}
}
));
}
public static ProvisioningProfileStore fromProvisioningProfiles(
Iterable<ProvisioningProfileMetadata> profiles) {
return new ProvisioningProfileStore(Suppliers.ofInstance(ImmutableList.copyOf(profiles)));
}
}
| [apple] Add more logging for provisioning profile selection
Summary: This enables more transparency for codesigning-related issues when building for iOS devices.
Test Plan: Build a iOS target for device, grep for `ProvisioningProfileStore` in the logs to see they're written out.
Reviewed By: Coneko
fb-gh-sync-id: 52964c6
| src/com/facebook/buck/apple/ProvisioningProfileStore.java | [apple] Add more logging for provisioning profile selection | <ide><path>rc/com/facebook/buck/apple/ProvisioningProfileStore.java
<ide> match = (bundleID.equals(profileBundleID));
<ide> }
<ide>
<add> if (!match) {
<add> LOG.debug("Ignoring non-matching ID for profile " + profile.getUUID());
<add> }
<add>
<ide> // Match against other keys of the entitlements. Otherwise, we could potentially select
<ide> // a profile that doesn't have all the needed entitlements, causing a error when
<ide> // installing to device.
<ide> entry.getKey().equals("application-identifier") ||
<ide> entry.getValue().equals(profileEntitlements.get(entry.getKey())))) {
<ide> match = false;
<add> LOG.debug("Ignoring profile " + profile.getUUID() +
<add> " with mismatched entitlement " + entry.getKey() + "; value is " +
<add> profileEntitlements.get(entry.getKey()) + " but expected " + entry.getValue());
<ide> break;
<ide> }
<ide> }
<ide> break;
<ide> }
<ide> }
<add>
<add> if (!match) {
<add> LOG.debug("Ignoring profile " + profile.getUUID() +
<add> " because it can't be signed with any valid identity in the current keychain.");
<add> }
<ide> }
<ide>
<ide> if (match && profileBundleID.length() > bestMatchLength) {
<ide> bestMatch = Optional.of(profile);
<ide> }
<ide> }
<add> } else {
<add> LOG.debug("Ignoring expired profile " + profile.getUUID());
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> public static ProvisioningProfileStore fromSearchPath(final Path searchPath) {
<add> LOG.debug("Provisioning profile search path: " + searchPath);
<ide> return new ProvisioningProfileStore(Suppliers.memoize(
<ide> new Supplier<ImmutableList<ProvisioningProfileMetadata>>() {
<ide> @Override |
|
Java | bsd-3-clause | 41f3c1c519016063a0095624c919d429cf119972 | 0 | lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon | /*
* $Id: $
*/
/*
Copyright (c) 2000-2015 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.atypon.massachusettsmedicalsociety;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.Iterator;
import org.lockss.config.ConfigManager;
import org.lockss.config.Configuration;
import org.lockss.daemon.ConfigParamDescr;
import org.lockss.extractor.MetadataTarget;
import org.lockss.plugin.*;
import org.lockss.test.*;
import org.lockss.util.*;
/*
* HTML Full Text: http://www.nejm.org/doi/full/10.1056/NEJMoa042957
* PDF Full Text: http://www.nejm.org/doi/pdf/10.1056/NEJMoa042957
* Citation (containing metadata): www.nejm.org/action/downloadCitation?format=(ris|endnote|bibTex|medlars|procite|referenceManager)&doi=10.1056%2FNEJMoa042957&include=cit&direct=checked
* Supplemental Materials page: http://www.nejm.org/action/showSupplements?doi=10.1056%2FNEJMc1304053
*/
public class TestMassachusettsMedicalSocietyArticleIteratorFactory extends ArticleIteratorTestCase {
private final String PATTERN_FAIL_MSG = "Article file URL pattern changed or incorrect";
private final String PLUGIN_NAME = "org.lockss.plugin.atypon.massachusettsmedicalsociety.MassachusettsMedicalSocietyPlugin";
static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();
static final String JOURNAL_ID_KEY = ConfigParamDescr.JOURNAL_ID.getKey();
static final String VOLUME_NAME_KEY = ConfigParamDescr.VOLUME_NAME.getKey();
private final String BASE_URL = "http://www.example.com/";
//private final String BASE_URL2 = "http:/cdn.example.com/";
private final String VOLUME_NAME = "352";
private final String JOURNAL_ID = "nejm";
private final Configuration AU_CONFIG = ConfigurationUtil.fromArgs(
BASE_URL_KEY, BASE_URL,
VOLUME_NAME_KEY, VOLUME_NAME,
JOURNAL_ID_KEY, JOURNAL_ID);
private CIProperties pdfHeader = new CIProperties();
private CIProperties textHeader = new CIProperties();
private static final String ContentString = "foo blah";
InputStream random_content_stream;
public void setUp() throws Exception {
super.setUp();
setUpDiskSpace();
au = createAu();
// set up headers for creating mock CU's of the appropriate type
pdfHeader.put(CachedUrl.PROPERTY_CONTENT_TYPE, "application/pdf");
textHeader.put(CachedUrl.PROPERTY_CONTENT_TYPE, "text/html");
// the content in the urls doesn't really matter for the test
random_content_stream = new ByteArrayInputStream(ContentString.getBytes(Constants.ENCODING_UTF_8));
}
public void tearDown() throws Exception {
super.tearDown();
}
/**
* Configuration method.
* @return
*/
Configuration auConfig() {
Configuration conf = ConfigManager.newConfiguration();
conf.put("base_url", BASE_URL);
conf.put("journal_id", JOURNAL_ID);
conf.put("volume_name", VOLUME_NAME);
return conf;
}
protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException {
return
PluginTestUtil.createAndStartAu(PLUGIN_NAME, AU_CONFIG);
}
public void testRoots() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
assertEquals("Article file root URL pattern changed or incorrect" ,ListUtil.list( BASE_URL + "doi/"),
getRootUrls(artIter));
}
public void testUrlsWithPrefixes() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
Pattern pat = getPattern(artIter);
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, "http://www.wrong.com/doi/full/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "dooi/full/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "/full/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi1/full/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "//10.5339/nejm12315");
//assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdfplus/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/ful/10.5339/nejm12315");
//assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/124/10.5339/nejm12315"); // this is now allowed
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, "http://www.wrong.com/doi/pdf/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "dooi/pdf/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "/pdf/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi1/pdf/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/abs/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "action/showSupplements?doi=10.1056%2FNEJMc1304053");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/full/10.5339/nejm12315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/full/10.533329/nejm123324315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/full/1023.5339/nejmb123b315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/full/10232.533339/nejm12315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdf/10.5339/nejm12315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdf/10.533329/nejm123324315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdf/1023.5339/nejmb123b315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdf/10232.533339/nejm12315");
//assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL2 + "6.0/img/blueDownArrow.gif");
}
public void testCreateArticleFiles() throws Exception {
// key the expected content to the fullTextUrl for the ArticleFiles
HashMap<String, ArticleFiles> fullUrlToAF = new HashMap<String, ArticleFiles>();
// add the following URLs to the AU
String[] au_urls = {
// article "NEJM1231" - abs, pdf, full, supplements and citation
BASE_URL + "doi/abs/10.1056/NEJM1231",
BASE_URL + "doi/pdf/10.5339/NEJM1231",
BASE_URL + "doi/full/10.5339/NEJM1231",
BASE_URL + "action/showSupplements?doi=10.5339%2FNEJM1231",
BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM1231&format=ris&include=cit",
// article nejm12345 - full text only
BASE_URL + "doi/full/10.5339/nejm12345",
// article nejm1231113 - pdf, full, ris
BASE_URL + "doi/full/10.5339/nejm1231113",
BASE_URL + "doi/pdf/10.5339/nejm1231113",
//BASE_URL + "doi/image/10.5339/nejm1231113",
BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM1231113&format=ris&include=cit",
// article nejm12315002, pdf, supp, ris
BASE_URL + "doi/pdf/10.5339/nejm12315002",
BASE_URL + "action/showSupplements?doi=10.5339%2Fnejm12315002",
BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM12315002&format=ris&include=cit",
// article nejm123456 pdf, full, supp, ris
BASE_URL + "doi/pdf/10.5339/NEJM123456",
BASE_URL + "doi/full/10.5339/NEJM123456",
BASE_URL + "action/showSupplements?doi=10.5339%2FNEJM123456",
BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM123456&format=ris&include=cit",
// randoms
BASE_URL + "doi/",
BASE_URL + "bq/352/12"
// cdn
};
// the content is never checked so just use a random input stream with the
//correct header
for(String url : au_urls) {
if(url.contains("pdf")){
storeContent(random_content_stream,pdfHeader, url);
}
else {
storeContent(random_content_stream,textHeader, url);
}
}
// article NEJM1231 - mostly full complement
ArticleFiles af1 = new ArticleFiles();
af1.setRoleString(ArticleFiles.ROLE_ABSTRACT,BASE_URL + "doi/abs/10.5339/NEJM1231");
af1.setRoleString(ArticleFiles.ROLE_FULL_TEXT_HTML,BASE_URL + "doi/full/10.5339/NEJM1231");
af1.setRoleString(ArticleFiles.ROLE_FULL_TEXT_PDF,BASE_URL + "doi/pdf/10.5339/NEJM1231");
af1.setRoleString(ArticleFiles.ROLE_CITATION_RIS,BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM1231&format=ris&include=cit");
af1.setRoleString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS,BASE_URL + "action/showSupplements?doi=10.5339%2FNEJM1231");
//log.info(af1.toString());
fullUrlToAF.put(BASE_URL + "doi/pdf/10.5339/NEJM1231", af1);
// article nejm12345
ArticleFiles af2 = new ArticleFiles();
af2.setRoleString(ArticleFiles.ROLE_FULL_TEXT_HTML, BASE_URL + "doi/full/10.5339/nejm12345");
//log.info(af2.toString());
fullUrlToAF.put(BASE_URL + "doi/full/10.5339/nejm12345", af2);
// article nejm1231113
ArticleFiles af3 = new ArticleFiles();
af3.setRoleString(ArticleFiles.ROLE_FULL_TEXT_PDF, BASE_URL + "doi/pdf/10.5339/nejm1231113");
af3.setRoleString(ArticleFiles.ROLE_FULL_TEXT_HTML, BASE_URL + "doi/full/10.5339/nejm1231113");
af3.setRoleString(ArticleFiles.ROLE_CITATION_RIS, BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM1231113&format=ris&include=cit");
//log.info(af3.toString());
fullUrlToAF.put(BASE_URL + "doi/pdf/10.5339/nejm1231113", af3);
// article nejm12315002
ArticleFiles af4 = new ArticleFiles();
af4.setRoleString(ArticleFiles.ROLE_FULL_TEXT_PDF,BASE_URL + "doi/pdf/10.5339/nejm12315002");
af4.setRoleString(ArticleFiles.ROLE_CITATION_RIS, BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM12315002&format=ris&include=cit");
af4.setRoleString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS,BASE_URL + "action/showSupplements?doi=10.5339%2Fnejm12315002");
//log.info(af4.toString());
fullUrlToAF.put(BASE_URL + "doi/pdf/10.5339/nejm12315002", af4);
// article nejm123456
ArticleFiles af5 = new ArticleFiles();
af5.setRoleString(ArticleFiles.ROLE_FULL_TEXT_PDF,BASE_URL + "doi/pdf/10.5339/NEJM123456");
af5.setRoleString(ArticleFiles.ROLE_FULL_TEXT_HTML,BASE_URL + "doi/full/10.5339/NEJM123456");
af5.setRoleString(ArticleFiles.ROLE_CITATION_RIS,BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM123456&format=ris&include=cit");
af5.setRoleString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS,BASE_URL + "action/showSupplements?doi=10.5339%2FNEJM123456");
//log.info(af5.toString());
fullUrlToAF.put(BASE_URL + "doi/pdf/10.5339/NEJM123456", af5);
for ( Iterator<ArticleFiles> it = au.getArticleIterator(MetadataTarget.Any()); it.hasNext(); ) {
ArticleFiles af = it.next();
//log.info("next AF: " + af.getFullTextUrl());
ArticleFiles exp= fullUrlToAF.get(af.getFullTextUrl());
assertNotNull(exp);
compareArticleFiles(exp, af);
}
}
public void testCitationPattern() {
}
private void compareArticleFiles(ArticleFiles exp, ArticleFiles act) {
/*
log.info("CompareArticleFiles: " );
log.info("checking html:");
log.info("expected: "+exp.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_HTML));
log.info("actual: "+act.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_HTML));
log.info("checking pdf:");
log.info("expected: "+exp.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_PDF));
log.info("actual: "+act.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_PDF));
*/
assertEquals("ROLE_FULL_TEXT_PDF: ",
exp.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_PDF),
act.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_PDF));
assertEquals("ROLE_FULL_TEXT_HTML",
exp.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_HTML),
act.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_HTML));
/*
log.info("checking ris:");
log.info("ris expected: "+exp.getRoleAsString(ArticleFiles.ROLE_CITATION_RIS));
log.info("ris actual: "+act.getRoleAsString(ArticleFiles.ROLE_CITATION_RIS));
log.info("checking supplementary:");
log.info("expected: "+exp.getRoleAsString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS));
log.info("actual: "+act.getRoleAsString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS));
*/
assertEquals("ROLE_CITATION: ",
exp.getRoleAsString(ArticleFiles.ROLE_CITATION),
act.getRoleAsString(ArticleFiles.ROLE_CITATION));
assertEquals("ROLE_SUPPLEMENTARY_MATERIALS: ",
exp.getRoleAsString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS),
act.getRoleAsString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS));
}
}
| plugins/test/src/org/lockss/plugin/atypon/massachusettsmedicalsociety/TestMassachusettsMedicalSocietyArticleIteratorFactory.java | /*
* $Id: $
*/
/*
Copyright (c) 2000-2015 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.atypon.massachusettsmedicalsociety;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.Iterator;
import org.lockss.config.ConfigManager;
import org.lockss.config.Configuration;
import org.lockss.daemon.ConfigParamDescr;
import org.lockss.extractor.MetadataTarget;
import org.lockss.plugin.*;
import org.lockss.test.*;
import org.lockss.util.*;
/*
* HTML Full Text: http://www.nejm.org/doi/full/10.1056/NEJMoa042957
* PDF Full Text: http://www.nejm.org/doi/pdf/10.1056/NEJMoa042957
* Citation (containing metadata): www.nejm.org/action/downloadCitation?format=(ris|endnote|bibTex|medlars|procite|referenceManager)&doi=10.1056%2FNEJMoa042957&include=cit&direct=checked
* Supplemental Materials page: http://www.nejm.org/action/showSupplements?doi=10.1056%2FNEJMc1304053
*/
public class TestMassachusettsMedicalSocietyArticleIteratorFactory extends ArticleIteratorTestCase {
private final String PATTERN_FAIL_MSG = "Article file URL pattern changed or incorrect";
private final String PLUGIN_NAME = "org.lockss.plugin.atypon.massachusettsmedicalsociety.MassachusettsMedicalSocietyPlugin";
static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();
static final String JOURNAL_ID_KEY = ConfigParamDescr.JOURNAL_ID.getKey();
static final String VOLUME_NAME_KEY = ConfigParamDescr.VOLUME_NAME.getKey();
private final String BASE_URL = "http://www.example.com/";
//private final String BASE_URL2 = "http:/cdn.example.com/";
private final String VOLUME_NAME = "352";
private final String JOURNAL_ID = "nejm";
private final Configuration AU_CONFIG = ConfigurationUtil.fromArgs(
BASE_URL_KEY, BASE_URL,
VOLUME_NAME_KEY, VOLUME_NAME,
JOURNAL_ID_KEY, JOURNAL_ID);
private CIProperties pdfHeader = new CIProperties();
private CIProperties textHeader = new CIProperties();
private static final String ContentString = "foo blah";
InputStream random_content_stream;
public void setUp() throws Exception {
super.setUp();
setUpDiskSpace();
au = createAu();
// set up headers for creating mock CU's of the appropriate type
pdfHeader.put(CachedUrl.PROPERTY_CONTENT_TYPE, "application/pdf");
textHeader.put(CachedUrl.PROPERTY_CONTENT_TYPE, "text/html");
// the content in the urls doesn't really matter for the test
random_content_stream = new ByteArrayInputStream(ContentString.getBytes(Constants.ENCODING_UTF_8));
}
public void tearDown() throws Exception {
super.tearDown();
}
/**
* Configuration method.
* @return
*/
Configuration auConfig() {
Configuration conf = ConfigManager.newConfiguration();
conf.put("base_url", BASE_URL);
conf.put("journal_id", JOURNAL_ID);
conf.put("volume_name", VOLUME_NAME);
return conf;
}
protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException {
return
PluginTestUtil.createAndStartAu(PLUGIN_NAME, AU_CONFIG);
}
public void testRoots() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
assertEquals("Article file root URL pattern changed or incorrect" ,ListUtil.list( BASE_URL + "doi/"),
getRootUrls(artIter));
}
public void testUrlsWithPrefixes() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
Pattern pat = getPattern(artIter);
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, "http://www.wrong.com/doi/full/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "dooi/full/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "/full/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi1/full/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "//10.5339/nejm12315");
//assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdfplus/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/ful/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/124/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, "http://www.wrong.com/doi/pdf/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "dooi/pdf/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "/pdf/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi1/pdf/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/abs/10.5339/nejm12315");
assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "action/showSupplements?doi=10.1056%2FNEJMc1304053");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/full/10.5339/nejm12315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/full/10.533329/nejm123324315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/full/1023.5339/nejmb123b315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/full/10232.533339/nejm12315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdf/10.5339/nejm12315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdf/10.533329/nejm123324315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdf/1023.5339/nejmb123b315");
assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdf/10232.533339/nejm12315");
//assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL2 + "6.0/img/blueDownArrow.gif");
}
public void testCreateArticleFiles() throws Exception {
// key the expected content to the fullTextUrl for the ArticleFiles
HashMap<String, ArticleFiles> fullUrlToAF = new HashMap<String, ArticleFiles>();
// add the following URLs to the AU
String[] au_urls = {
// article "NEJM1231" - abs, pdf, full, supplements and citation
BASE_URL + "doi/abs/10.1056/NEJM1231",
BASE_URL + "doi/pdf/10.5339/NEJM1231",
BASE_URL + "doi/full/10.5339/NEJM1231",
BASE_URL + "action/showSupplements?doi=10.5339%2FNEJM1231",
BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM1231&format=ris&include=cit",
// article nejm12345 - full text only
BASE_URL + "doi/full/10.5339/nejm12345",
// article nejm1231113 - pdf, full, ris
BASE_URL + "doi/full/10.5339/nejm1231113",
BASE_URL + "doi/pdf/10.5339/nejm1231113",
//BASE_URL + "doi/image/10.5339/nejm1231113",
BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM1231113&format=ris&include=cit",
// article nejm12315002, pdf, supp, ris
BASE_URL + "doi/pdf/10.5339/nejm12315002",
BASE_URL + "action/showSupplements?doi=10.5339%2Fnejm12315002",
BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM12315002&format=ris&include=cit",
// article nejm123456 pdf, full, supp, ris
BASE_URL + "doi/pdf/10.5339/NEJM123456",
BASE_URL + "doi/full/10.5339/NEJM123456",
BASE_URL + "action/showSupplements?doi=10.5339%2FNEJM123456",
BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM123456&format=ris&include=cit",
// randoms
BASE_URL + "doi/",
BASE_URL + "bq/352/12"
// cdn
};
// the content is never checked so just use a random input stream with the
//correct header
for(String url : au_urls) {
if(url.contains("pdf")){
storeContent(random_content_stream,pdfHeader, url);
}
else {
storeContent(random_content_stream,textHeader, url);
}
}
// article NEJM1231 - mostly full complement
ArticleFiles af1 = new ArticleFiles();
af1.setRoleString(ArticleFiles.ROLE_ABSTRACT,BASE_URL + "doi/abs/10.5339/NEJM1231");
af1.setRoleString(ArticleFiles.ROLE_FULL_TEXT_HTML,BASE_URL + "doi/full/10.5339/NEJM1231");
af1.setRoleString(ArticleFiles.ROLE_FULL_TEXT_PDF,BASE_URL + "doi/pdf/10.5339/NEJM1231");
af1.setRoleString(ArticleFiles.ROLE_CITATION_RIS,BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM1231&format=ris&include=cit");
af1.setRoleString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS,BASE_URL + "action/showSupplements?doi=10.5339%2FNEJM1231");
//log.info(af1.toString());
fullUrlToAF.put(BASE_URL + "doi/pdf/10.5339/NEJM1231", af1);
// article nejm12345
ArticleFiles af2 = new ArticleFiles();
af2.setRoleString(ArticleFiles.ROLE_FULL_TEXT_HTML, BASE_URL + "doi/full/10.5339/nejm12345");
//log.info(af2.toString());
fullUrlToAF.put(BASE_URL + "doi/full/10.5339/nejm12345", af2);
// article nejm1231113
ArticleFiles af3 = new ArticleFiles();
af3.setRoleString(ArticleFiles.ROLE_FULL_TEXT_PDF, BASE_URL + "doi/pdf/10.5339/nejm1231113");
af3.setRoleString(ArticleFiles.ROLE_FULL_TEXT_HTML, BASE_URL + "doi/full/10.5339/nejm1231113");
af3.setRoleString(ArticleFiles.ROLE_CITATION_RIS, BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM1231113&format=ris&include=cit");
//log.info(af3.toString());
fullUrlToAF.put(BASE_URL + "doi/pdf/10.5339/nejm1231113", af3);
// article nejm12315002
ArticleFiles af4 = new ArticleFiles();
af4.setRoleString(ArticleFiles.ROLE_FULL_TEXT_PDF,BASE_URL + "doi/pdf/10.5339/nejm12315002");
af4.setRoleString(ArticleFiles.ROLE_CITATION_RIS, BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM12315002&format=ris&include=cit");
af4.setRoleString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS,BASE_URL + "action/showSupplements?doi=10.5339%2Fnejm12315002");
//log.info(af4.toString());
fullUrlToAF.put(BASE_URL + "doi/pdf/10.5339/nejm12315002", af4);
// article nejm123456
ArticleFiles af5 = new ArticleFiles();
af5.setRoleString(ArticleFiles.ROLE_FULL_TEXT_PDF,BASE_URL + "doi/pdf/10.5339/NEJM123456");
af5.setRoleString(ArticleFiles.ROLE_FULL_TEXT_HTML,BASE_URL + "doi/full/10.5339/NEJM123456");
af5.setRoleString(ArticleFiles.ROLE_CITATION_RIS,BASE_URL + "action/downloadCitation?doi=10.5339%2FNEJM123456&format=ris&include=cit");
af5.setRoleString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS,BASE_URL + "action/showSupplements?doi=10.5339%2FNEJM123456");
//log.info(af5.toString());
fullUrlToAF.put(BASE_URL + "doi/pdf/10.5339/NEJM123456", af5);
for ( Iterator<ArticleFiles> it = au.getArticleIterator(MetadataTarget.Any()); it.hasNext(); ) {
ArticleFiles af = it.next();
//log.info("next AF: " + af.getFullTextUrl());
ArticleFiles exp= fullUrlToAF.get(af.getFullTextUrl());
assertNotNull(exp);
compareArticleFiles(exp, af);
}
}
public void testCitationPattern() {
}
private void compareArticleFiles(ArticleFiles exp, ArticleFiles act) {
/*
log.info("CompareArticleFiles: " );
log.info("checking html:");
log.info("expected: "+exp.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_HTML));
log.info("actual: "+act.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_HTML));
log.info("checking pdf:");
log.info("expected: "+exp.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_PDF));
log.info("actual: "+act.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_PDF));
*/
assertEquals("ROLE_FULL_TEXT_PDF: ",
exp.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_PDF),
act.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_PDF));
assertEquals("ROLE_FULL_TEXT_HTML",
exp.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_HTML),
act.getRoleAsString(ArticleFiles.ROLE_FULL_TEXT_HTML));
/*
log.info("checking ris:");
log.info("ris expected: "+exp.getRoleAsString(ArticleFiles.ROLE_CITATION_RIS));
log.info("ris actual: "+act.getRoleAsString(ArticleFiles.ROLE_CITATION_RIS));
log.info("checking supplementary:");
log.info("expected: "+exp.getRoleAsString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS));
log.info("actual: "+act.getRoleAsString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS));
*/
assertEquals("ROLE_CITATION: ",
exp.getRoleAsString(ArticleFiles.ROLE_CITATION),
act.getRoleAsString(ArticleFiles.ROLE_CITATION));
assertEquals("ROLE_SUPPLEMENTARY_MATERIALS: ",
exp.getRoleAsString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS),
act.getRoleAsString(ArticleFiles.ROLE_SUPPLEMENTARY_MATERIALS));
}
}
| AI now allows for doi without aspect | plugins/test/src/org/lockss/plugin/atypon/massachusettsmedicalsociety/TestMassachusettsMedicalSocietyArticleIteratorFactory.java | AI now allows for doi without aspect | <ide><path>lugins/test/src/org/lockss/plugin/atypon/massachusettsmedicalsociety/TestMassachusettsMedicalSocietyArticleIteratorFactory.java
<ide> assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "//10.5339/nejm12315");
<ide> //assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/pdfplus/10.5339/nejm12315");
<ide> assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/ful/10.5339/nejm12315");
<del> assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/124/10.5339/nejm12315");
<add> //assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "doi/124/10.5339/nejm12315"); // this is now allowed
<ide> assertNotMatchesRE(PATTERN_FAIL_MSG, pat, "http://www.wrong.com/doi/pdf/10.5339/nejm12315");
<ide> assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "dooi/pdf/10.5339/nejm12315");
<ide> assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "/pdf/10.5339/nejm12315"); |
|
Java | lgpl-2.1 | 714e20b26e8c27c279a53d51a5267e36ae5294b9 | 0 | redvox/gka | package a1_p01_JS_MJ;
import java.io.*;
import java.util.Scanner;
import org.jgrapht.Graph;
import org.jgrapht.Graphs;
import org.jgrapht.WeightedGraph;
import org.jgrapht.graph.*;
import a2_p01_JS_MJ.AttributedNode;
public class GraphParser {
public static Graph parseGraphFile(String filename) throws Exception {
File file = new File(filename);
Scanner scanner = new Scanner(new FileReader(file));
try {
String firstLine = scanner.nextLine();
String secondLine = scanner.nextLine();
int graphType = 0;
// Erste Zeile Parsen
if(firstLine.equalsIgnoreCase("#gerichtet")){
graphType += 1;
} else if(firstLine.equalsIgnoreCase("#ungerichtet")){
graphType += 11;
} else {
throw new IOException("Falscher Header in erster Zeile");
}
// Zweite Zeile Parsen
if(secondLine.equalsIgnoreCase("#attributiert")){
graphType += 1;
} else if(secondLine.equalsIgnoreCase("#gewichtet")){
graphType += 2;
} else if(secondLine.equalsIgnoreCase("#attributiert,gewichted")){
graphType += 3;
}
System.out.println(firstLine);
System.out.println(secondLine);
System.out.println(graphType);
switch (graphType) {
case 1: // nur Gerichtet
return parseDircetedGraph(scanner);
case 2: // Gerichtet und Attributiert
throw new Exception("Not yet implemented");
case 3: // Gerichtet und Gewichtet
throw new Exception("Not yet implemented");
case 4: // Gerichtet und Gewichtet und Attributiert
throw new Exception("Not yet implemented");
case 11: // nur Ungerichtet
return parseUndircetedGraph(scanner);
case 12: // Ungerichtet und Attributiert
throw new Exception("Not yet implemented");
case 13: // Ungerichtet und Gewichtet
return parseWeightedGraph(scanner);
case 14: // Ungerichtet und Gewichtet und Attributiert
return parseWeightedAttributedGraph(scanner);
default:
throw new Exception("Falscher Header");
}
} finally {
scanner.close();
}
}
private static Pseudograph<String, DefaultEdge> parseUndircetedGraph(Scanner scanner){
Pseudograph<String, DefaultEdge> graph =
new Pseudograph<String, DefaultEdge>(DefaultEdge.class);
String[] line;
while (scanner.hasNextLine()){
line = splitLine(scanner.nextLine());
graph.addVertex(line[0]);
graph.addVertex(line[1]);
graph.addEdge(line[0], line[1]);
}
return graph;
}
private static DirectedMultigraph<String, DefaultEdge> parseDircetedGraph(Scanner scanner){
DirectedMultigraph<String, DefaultEdge> graph =
new DirectedMultigraph<String, DefaultEdge>(DefaultEdge.class);
String[] line;
while (scanner.hasNextLine()){
line = splitLine(scanner.nextLine());
graph.addVertex(line[0]);
graph.addVertex(line[1]);
graph.addEdge(line[0], line[1]);
}
return graph;
}
public static WeightedGraph<String, DefaultWeightedEdge> parseWeightedGraph(Scanner scanner)
{
WeightedGraph<String, DefaultWeightedEdge> graph = new WeightedPseudograph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
String[] line;
while(scanner.hasNextLine())
{
line = splitLine(scanner.nextLine());
Graphs.addEdgeWithVertices(graph,line[0],line[1]);
graph.setEdgeWeight(graph.getEdge(line[0],line[1]),Double.parseDouble(line[2]));
}
return graph;
}
public static WeightedGraph<AttributedNode<String>,DefaultWeightedEdge> parseWeightedAttributedGraph(Scanner scanner)
{
WeightedGraph<AttributedNode<String>,DefaultWeightedEdge> graph = new WeightedPseudograph<AttributedNode<String>, DefaultWeightedEdge>(DefaultWeightedEdge.class);
String[] line;
while (scanner.hasNextLine())
{
line = splitLine(scanner.nextLine());
AttributedNode<String> n1 = new AttributedNode<String>(line[0],Double.parseDouble(line[1]));
AttributedNode<String> n2 = new AttributedNode<String>(line[2],Double.parseDouble(line[3]));
Graphs.addEdgeWithVertices(graph,n1,n2);
graph.setEdgeWeight(graph.getEdge(n1,n2),Double.parseDouble(line[4]));
}
return graph;
}
private static String[] splitLine(String line){
return line.split(",");
}
}
| src/a1_p01_JS_MJ/GraphParser.java | package a1_p01_JS_MJ;
import java.io.*;
import java.util.Scanner;
import org.jgrapht.Graph;
import org.jgrapht.Graphs;
import org.jgrapht.WeightedGraph;
import org.jgrapht.graph.*;
import a2_p01_JS_MJ.AttributedNode;
public class GraphParser {
public static Graph parseGraphFile(String filename) throws Exception {
File file = new File(filename);
Scanner scanner = new Scanner(new FileReader(file));
try {
String firstLine = scanner.nextLine();
String secondLine = scanner.nextLine();
int graphType = 0;
// Erste Zeile Parsen
if(firstLine.equalsIgnoreCase("#gerichtet")){
graphType += 1;
} else if(firstLine.equalsIgnoreCase("#ungerichtet")){
graphType += 11;
} else {
throw new IOException("Falscher Header in erster Zeile");
}
// Zweite Zeile Parsen
if(secondLine.equalsIgnoreCase("#attributiert")){
graphType += 1;
} else if(secondLine.equalsIgnoreCase("#gewichted")){
graphType += 2;
} else if(secondLine.equalsIgnoreCase("#attributiert,gewichted")){
graphType += 3;
}
switch (graphType) {
case 1: // nur Gerichtet
return parseDircetedGraph(scanner);
case 2: // Gerichtet und Attributiert
throw new Exception("Not yet implemented");
case 3: // Gerichtet und Gewichtet
throw new Exception("Not yet implemented");
case 4: // Gerichtet und Gewichtet und Attributiert
throw new Exception("Not yet implemented");
case 11: // nur Ungerichtet
return parseUndircetedGraph(scanner);
case 12: // Ungerichtet und Attributiert
throw new Exception("Not yet implemented");
case 13: // Ungerichtet und Gewichtet
return parseWeightedGraph(scanner);
case 14: // Ungerichtet und Gewichtet und Attributiert
return parseWeightedAttributedGraph(scanner);
default:
throw new Exception("Falscher Header");
}
} finally {
scanner.close();
}
}
private static Pseudograph<String, DefaultEdge> parseUndircetedGraph(Scanner scanner){
Pseudograph<String, DefaultEdge> graph =
new Pseudograph<String, DefaultEdge>(DefaultEdge.class);
String[] line;
while (scanner.hasNextLine()){
line = splitLine(scanner.nextLine());
graph.addVertex(line[0]);
graph.addVertex(line[1]);
graph.addEdge(line[0], line[1]);
}
return graph;
}
private static DirectedMultigraph<String, DefaultEdge> parseDircetedGraph(Scanner scanner){
DirectedMultigraph<String, DefaultEdge> graph =
new DirectedMultigraph<String, DefaultEdge>(DefaultEdge.class);
String[] line;
while (scanner.hasNextLine()){
line = splitLine(scanner.nextLine());
graph.addVertex(line[0]);
graph.addVertex(line[1]);
graph.addEdge(line[0], line[1]);
}
return graph;
}
public static WeightedGraph<String, DefaultWeightedEdge> parseWeightedGraph(Scanner scanner)
{
WeightedGraph<String, DefaultWeightedEdge> graph = new WeightedPseudograph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
String[] line;
while(scanner.hasNextLine())
{
line = splitLine(scanner.nextLine());
Graphs.addEdgeWithVertices(graph,line[0],line[2]);
graph.setEdgeWeight(graph.getEdge(line[0],line[2]),Double.parseDouble(line[4]));
}
return graph;
}
public static WeightedGraph<AttributedNode<String>,DefaultWeightedEdge> parseWeightedAttributedGraph(Scanner scanner)
{
WeightedGraph<AttributedNode<String>,DefaultWeightedEdge> graph = new WeightedPseudograph<AttributedNode<String>, DefaultWeightedEdge>(DefaultWeightedEdge.class);
String[] line;
while (scanner.hasNextLine())
{
line = splitLine(scanner.nextLine());
AttributedNode<String> n1 = new AttributedNode<String>(line[0],Double.parseDouble(line[1]));
AttributedNode<String> n2 = new AttributedNode<String>(line[2],Double.parseDouble(line[3]));
Graphs.addEdgeWithVertices(graph,n1,n2);
graph.setEdgeWeight(graph.getEdge(n1,n2),Double.parseDouble(line[4]));
}
return graph;
}
private static String[] splitLine(String line){
return line.split(",");
}
}
| Typo in GraphParser fixed, it should now parse undirected, weighted graphs correctly.
| src/a1_p01_JS_MJ/GraphParser.java | Typo in GraphParser fixed, it should now parse undirected, weighted graphs correctly. | <ide><path>rc/a1_p01_JS_MJ/GraphParser.java
<ide> if(secondLine.equalsIgnoreCase("#attributiert")){
<ide> graphType += 1;
<ide>
<del> } else if(secondLine.equalsIgnoreCase("#gewichted")){
<add> } else if(secondLine.equalsIgnoreCase("#gewichtet")){
<ide> graphType += 2;
<ide>
<ide> } else if(secondLine.equalsIgnoreCase("#attributiert,gewichted")){
<ide> graphType += 3;
<ide> }
<add>
<add> System.out.println(firstLine);
<add> System.out.println(secondLine);
<add> System.out.println(graphType);
<ide>
<ide> switch (graphType) {
<ide> case 1: // nur Gerichtet
<ide> while(scanner.hasNextLine())
<ide> {
<ide> line = splitLine(scanner.nextLine());
<del> Graphs.addEdgeWithVertices(graph,line[0],line[2]);
<del> graph.setEdgeWeight(graph.getEdge(line[0],line[2]),Double.parseDouble(line[4]));
<add> Graphs.addEdgeWithVertices(graph,line[0],line[1]);
<add> graph.setEdgeWeight(graph.getEdge(line[0],line[1]),Double.parseDouble(line[2]));
<ide> }
<ide> return graph;
<ide> } |
|
Java | apache-2.0 | 488b655439cebbdbe1a7f81d58a009dbc0fdbc68 | 0 | zanella/ttorrent,akkinenirajesh/ttorrent,shevek/ttorrent,13922841464/ttorrent,tsbatista/ttorrent,zanella/ttorrent,indeedeng/ttorrent,fspereira/ttorrent,pisek/ttorrent,andrew749/ttorrent,d3roch4/ttorrent,d3roch4/ttorrent,JetBrains/ttorrent-lib,indeedeng/ttorrent,sroze/ttorrent,rambegaokar/ttorrent,henkel/ttorrent,fspereira/ttorrent,JetBrains/ttorrent-lib,sroze/ttorrent,mpetazzoni/ttorrent,henkel/ttorrent,mpetazzoni/ttorrent,akkinenirajesh/ttorrent,rambegaokar/ttorrent,tsbatista/ttorrent,shevek/ttorrent,13922841464/ttorrent,pisek/ttorrent,andrew749/ttorrent | /**
* Copyright (C) 2011-2012 Turn, 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.turn.ttorrent.client.announce;
import com.turn.ttorrent.client.SharedTorrent;
import com.turn.ttorrent.common.Peer;
import com.turn.ttorrent.common.protocol.TrackerMessage;
import com.turn.ttorrent.common.protocol.TrackerMessage.*;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public abstract class TrackerClient {
/** The set of listeners to announce request answers. */
private final Set<AnnounceResponseListener> listeners;
protected final SharedTorrent torrent;
protected final Peer peer;
protected final URI tracker;
public TrackerClient(SharedTorrent torrent, Peer peer, URI tracker) {
this.listeners = new HashSet<AnnounceResponseListener>();
this.torrent = torrent;
this.peer = peer;
this.tracker = tracker;
}
/**
* Register a new announce response listener.
*
* @param listener The listener to register on this announcer events.
*/
public void register(AnnounceResponseListener listener) {
this.listeners.add(listener);
}
/**
* Returns the URI this tracker clients connects to.
*/
public URI getTrackerURI() {
return this.tracker;
}
/**
* Build, send and process a tracker announce request.
*
* <p>
* This function first builds an announce request for the specified event
* with all the required parameters. Then, the request is made to the
* tracker and the response analyzed.
* </p>
*
* <p>
* All registered {@link AnnounceResponseListener} objects are then fired
* with the decoded payload.
* </p>
*
* @param event The announce event type (can be AnnounceEvent.NONE for
* periodic updates).
* @param inhibitEvent Prevent event listeners from being notified.
*/
public abstract void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvent) throws AnnounceException;
/**
* Close any opened announce connection.
*
* <p>
* This method is called by {@link #stop()} to make sure all connections
* are correctly closed when the announce thread is asked to stop.
* </p>
*/
protected void close() {
// Do nothing by default, but can be overloaded.
}
/**
* Formats an announce event into a usable string.
*/
protected String formatAnnounceEvent(
AnnounceRequestMessage.RequestEvent event) {
return AnnounceRequestMessage.RequestEvent.NONE.equals(event)
? ""
: String.format(" %s", event.name());
}
/**
* Handle the announce response from the tracker.
*
* <p>
* Analyzes the response from the tracker and acts on it. If the response
* is an error, it is logged. Otherwise, the announce response is used
* to fire the corresponding announce and peer events to all announce
* listeners.
* </p>
*
* @param message The incoming {@link TrackerMessage}.
* @param inhibitEvents Whether or not to prevent events from being fired.
*/
protected void handleTrackerAnnounceResponse(TrackerMessage message,
boolean inhibitEvents) throws AnnounceException {
if (message instanceof ErrorMessage) {
ErrorMessage error = (ErrorMessage)message;
throw new AnnounceException(error.getReason());
}
if (! (message instanceof AnnounceResponseMessage)) {
throw new AnnounceException("Unexpected tracker message type " +
message.getType().name() + "!");
}
if (inhibitEvents) {
return;
}
AnnounceResponseMessage response =
(AnnounceResponseMessage)message;
this.fireAnnounceResponseEvent(
response.getComplete(),
response.getIncomplete(),
response.getInterval());
this.fireDiscoveredPeersEvent(
response.getPeers());
}
/**
* Fire the announce response event to all listeners.
*
* @param complete The number of seeders on this torrent.
* @param incomplete The number of leechers on this torrent.
* @param interval The announce interval requested by the tracker.
*/
protected void fireAnnounceResponseEvent(int complete, int incomplete,
int interval) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleAnnounceResponse(interval, complete, incomplete);
}
}
/**
* Fire the new peer discovery event to all listeners.
*
* @param peers The list of peers discovered.
*/
protected void fireDiscoveredPeersEvent(List<Peer> peers) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleDiscoveredPeers(peers);
}
}
}
| src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java | /**
* Copyright (C) 2011-2012 Turn, 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.turn.ttorrent.client.announce;
import com.turn.ttorrent.client.SharedTorrent;
import com.turn.ttorrent.common.Peer;
import com.turn.ttorrent.common.protocol.TrackerMessage;
import com.turn.ttorrent.common.protocol.TrackerMessage.*;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public abstract class TrackerClient {
/** The set of listeners to announce request answers. */
private final Set<AnnounceResponseListener> listeners;
protected final SharedTorrent torrent;
protected final Peer peer;
protected final URI tracker;
public TrackerClient(SharedTorrent torrent, Peer peer, URI tracker) {
this.listeners = new HashSet<AnnounceResponseListener>();
this.torrent = torrent;
this.peer = peer;
this.tracker = tracker;
}
/**
* Register a new announce response listener.
*
* @param listener The listener to register on this announcer events.
*/
public void register(AnnounceResponseListener listener) {
this.listeners.add(listener);
}
/**
* Returns the URI this tracker clients connects to.
*/
public URI getTrackerURI() {
return this.tracker;
}
/**
* Build, send and process a tracker announce request.
*
* <p>
* This function first builds an announce request for the specified event
* with all the required parameters. Then, the request is made to the
* tracker and the response analyzed.
* </p>
*
* <p>
* All registered {@link AnnounceResponseListener} objects are then fired
* with the decoded payload.
* </p>
*
* @param event The announce event type (can be AnnounceEvent.NONE for
* periodic updates).
* @param inhibitEvent Prevent event listeners from being notified.
*/
public abstract void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvent) throws AnnounceException;
/**
* Close any opened announce connection.
*
* <p>
* This method is called by {@link #stop()} to make sure all connections
* are correctly closed when the announce thread is asked to stop.
* </p>
*/
protected void close() {
// Do nothing by default, but can be overloaded.
}
/**
* Formats an announce event into a usable string.
*/
protected String formatAnnounceEvent(
AnnounceRequestMessage.RequestEvent event) {
return AnnounceRequestMessage.RequestEvent.NONE.equals(event)
? ""
: String.format(" %s", event.name());
}
/**
* Handle the announce response from the tracker.
*
* <p>
* Analyzes the response from the tracker and acts on it. If the response
* is an error, it is logged. Otherwise, the announce response is used
* to fire the corresponding announce and peer events to all announce
* listeners.
* </p>
*
* @param message The incoming {@link TrackerMessage}.
* @param inhibitEvents Whether or not to prevent events from being fired.
*/
protected void handleTrackerAnnounceResponse(TrackerMessage message,
boolean inhibitEvents) throws AnnounceException {
if (message instanceof ErrorMessage) {
ErrorMessage error = (ErrorMessage)message;
throw new AnnounceException(error.getReason());
}
if (! (message instanceof AnnounceResponseMessage)) {
throw new AnnounceException("Unexpected tracker message type " +
message.getType().name() + "!");
}
if (inhibitEvents) {
return;
}
AnnounceResponseMessage response =
(AnnounceResponseMessage)message;
this.fireAnnounceResponseEvent(
response.getComplete(),
response.getIncomplete(),
response.getInterval());
this.fireDiscoveredPeersEvent(
response.getPeers());
}
/**
* Fire the announce response event to all listeners.
*
* @param complete The number of seeders on this torrent.
* @param incomplete The number of leechers on this torrent.
* @param interval The announce interval requested by the tracker.
*/
protected void fireAnnounceResponseEvent(int complete, int incomplete,
int interval) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleAnnounceResponse(complete, incomplete, interval);
}
}
/**
* Fire the new peer discovery event to all listeners.
*
* @param peers The list of peers discovered.
*/
protected void fireDiscoveredPeersEvent(List<Peer> peers) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleDiscoveredPeers(peers);
}
}
}
| Fix order of parameters passed to handleAnnounceResponse()
Signed-off-by: Maxime Petazzoni <[email protected]>
| src/main/java/com/turn/ttorrent/client/announce/TrackerClient.java | Fix order of parameters passed to handleAnnounceResponse() | <ide><path>rc/main/java/com/turn/ttorrent/client/announce/TrackerClient.java
<ide> protected void fireAnnounceResponseEvent(int complete, int incomplete,
<ide> int interval) {
<ide> for (AnnounceResponseListener listener : this.listeners) {
<del> listener.handleAnnounceResponse(complete, incomplete, interval);
<add> listener.handleAnnounceResponse(interval, complete, incomplete);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 463c9ea498a4824fb49dfa261a70892c1e9ea282 | 0 | lburgazzoli/apache-logging-log4j2,codescale/logging-log4j2,lburgazzoli/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,lburgazzoli/logging-log4j2,apache/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2,lburgazzoli/logging-log4j2,lburgazzoli/apache-logging-log4j2,xnslong/logging-log4j2,lqbweb/logging-log4j2,GFriedrich/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,lburgazzoli/apache-logging-log4j2,lqbweb/logging-log4j2,lqbweb/logging-log4j2 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.osgi;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.plugins.util.PluginRegistry;
import org.apache.logging.log4j.core.util.Constants;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.framework.wiring.BundleWiring;
/**
* OSGi BundleActivator.
*/
public final class Activator implements BundleActivator, SynchronousBundleListener {
private static final Logger LOGGER = StatusLogger.getLogger();
private final AtomicReference<BundleContext> contextRef = new AtomicReference<>();
@Override
public void start(final BundleContext context) throws Exception {
// allow the user to override the default ContextSelector (e.g., by using BasicContextSelector for a global cfg)
if (PropertiesUtil.getProperties().getStringProperty(Constants.LOG4J_CONTEXT_SELECTOR) == null) {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BundleContextSelector.class.getName());
}
if (this.contextRef.compareAndSet(null, context)) {
context.addBundleListener(this);
// done after the BundleListener as to not miss any new bundle installs in the interim
scanInstalledBundlesForPlugins(context);
}
}
private static void scanInstalledBundlesForPlugins(final BundleContext context) {
final Bundle[] bundles = context.getBundles();
for (final Bundle bundle : bundles) {
// LOG4J2-920: don't scan system bundle for plugins
if (bundle.getState() == Bundle.ACTIVE && bundle.getBundleId() != 0) {
// TODO: bundle state can change during this
scanBundleForPlugins(bundle);
}
}
}
private static void scanBundleForPlugins(final Bundle bundle) {
LOGGER.trace("Scanning bundle [{}] for plugins.", bundle.getSymbolicName());
PluginRegistry.getInstance().loadFromBundle(bundle.getBundleId(),
bundle.adapt(BundleWiring.class).getClassLoader());
}
private static void stopBundlePlugins(final Bundle bundle) {
LOGGER.trace("Stopping bundle [{}] plugins.", bundle.getSymbolicName());
// TODO: plugin lifecycle code
PluginRegistry.getInstance().clearBundlePlugins(bundle.getBundleId());
}
@Override
public void stop(final BundleContext context) throws Exception {
this.contextRef.compareAndSet(context, null);
LogManager.shutdown();
}
@Override
public void bundleChanged(final BundleEvent event) {
switch (event.getType()) {
// FIXME: STARTING instead of STARTED?
case BundleEvent.STARTED:
scanBundleForPlugins(event.getBundle());
break;
case BundleEvent.STOPPING:
stopBundlePlugins(event.getBundle());
break;
default:
break;
}
}
}
| log4j-core/src/main/java/org/apache/logging/log4j/core/osgi/Activator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.osgi;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.plugins.util.PluginRegistry;
import org.apache.logging.log4j.core.util.Constants;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.framework.wiring.BundleWiring;
/**
* OSGi BundleActivator.
*/
public final class Activator implements BundleActivator, SynchronousBundleListener {
private static final Logger LOGGER = StatusLogger.getLogger();
private final AtomicReference<BundleContext> context = new AtomicReference<>();
@Override
public void start(final BundleContext context) throws Exception {
// allow the user to override the default ContextSelector (e.g., by using BasicContextSelector for a global cfg)
if (PropertiesUtil.getProperties().getStringProperty(Constants.LOG4J_CONTEXT_SELECTOR) == null) {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BundleContextSelector.class.getName());
}
if (this.context.compareAndSet(null, context)) {
context.addBundleListener(this);
// done after the BundleListener as to not miss any new bundle installs in the interim
scanInstalledBundlesForPlugins(context);
}
}
private static void scanInstalledBundlesForPlugins(final BundleContext context) {
final Bundle[] bundles = context.getBundles();
for (final Bundle bundle : bundles) {
// LOG4J2-920: don't scan system bundle for plugins
if (bundle.getState() == Bundle.ACTIVE && bundle.getBundleId() != 0) {
// TODO: bundle state can change during this
scanBundleForPlugins(bundle);
}
}
}
private static void scanBundleForPlugins(final Bundle bundle) {
LOGGER.trace("Scanning bundle [{}] for plugins.", bundle.getSymbolicName());
PluginRegistry.getInstance().loadFromBundle(bundle.getBundleId(),
bundle.adapt(BundleWiring.class).getClassLoader());
}
private static void stopBundlePlugins(final Bundle bundle) {
LOGGER.trace("Stopping bundle [{}] plugins.", bundle.getSymbolicName());
// TODO: plugin lifecycle code
PluginRegistry.getInstance().clearBundlePlugins(bundle.getBundleId());
}
@Override
public void stop(final BundleContext context) throws Exception {
this.context.compareAndSet(context, null);
LogManager.shutdown();
}
@Override
public void bundleChanged(final BundleEvent event) {
switch (event.getType()) {
// FIXME: STARTING instead of STARTED?
case BundleEvent.STARTED:
scanBundleForPlugins(event.getBundle());
break;
case BundleEvent.STOPPING:
stopBundlePlugins(event.getBundle());
break;
default:
break;
}
}
}
| Fix compiler warning by using a better ivar name. | log4j-core/src/main/java/org/apache/logging/log4j/core/osgi/Activator.java | Fix compiler warning by using a better ivar name. | <ide><path>og4j-core/src/main/java/org/apache/logging/log4j/core/osgi/Activator.java
<ide>
<ide> private static final Logger LOGGER = StatusLogger.getLogger();
<ide>
<del> private final AtomicReference<BundleContext> context = new AtomicReference<>();
<add> private final AtomicReference<BundleContext> contextRef = new AtomicReference<>();
<ide>
<ide> @Override
<ide> public void start(final BundleContext context) throws Exception {
<ide> if (PropertiesUtil.getProperties().getStringProperty(Constants.LOG4J_CONTEXT_SELECTOR) == null) {
<ide> System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BundleContextSelector.class.getName());
<ide> }
<del> if (this.context.compareAndSet(null, context)) {
<add> if (this.contextRef.compareAndSet(null, context)) {
<ide> context.addBundleListener(this);
<ide> // done after the BundleListener as to not miss any new bundle installs in the interim
<ide> scanInstalledBundlesForPlugins(context);
<ide>
<ide> @Override
<ide> public void stop(final BundleContext context) throws Exception {
<del> this.context.compareAndSet(context, null);
<add> this.contextRef.compareAndSet(context, null);
<ide> LogManager.shutdown();
<ide> }
<ide> |
|
JavaScript | mit | d4c5bfd4663b97da1838f360e774c5410a953353 | 0 | BelinChung/HiApp,BelinChung/HiApp,BeedleCars/Mobile,BeedleCars/Mobile | // Import Vue
import Vue from 'vue'
// Import F7, F7-Vue
import 'framework7'
import Framework7Vue from 'framework7-vue'
// Import F7 iOS Theme Styles
import 'framework7/dist/css/framework7.ios.min.css'
import 'framework7/dist/css/framework7.ios.colors.min.css'
/* OR for Material Theme:
import Framework7Theme from 'framework7/dist/css/framework7.material.min.css'
import Framework7ThemeColors from 'framework7/dist/css/framework7.material.colors.min.css'
*/
// Import App Custom Styles
import './assets/fonts/iconfont.css'
import './assets/styles/app.less'
// Import Routes
import Routes from './routes.js'
// Import App Component
import App from './app'
// Import Vuex store
import store from './store'
import {getLoginUser} from './store/actions'
// Init network framework
import './network'
// Init Vue Plugin
Vue.use(Framework7Vue)
// Import language file
import VueI18n from 'vue-i18n'
import StoreCache from './utils/storeCache'
import enUS from './lang/en_us'
import zhCN from './lang/zh_cn'
let cache = new StoreCache('vuex')
Vue.use(VueI18n)
Vue.config.lang = cache.get('lang') || 'en'
Vue.locale('en', enUS)
Vue.locale('zh', zhCN)
// Init App
new Vue({
el: '#app',
store,
template: '<app/>',
// Init Framework7 by passing parameters here
framework7: {
root: '#app',
modalTitle: Vue.t('app.modal.title'),
modalButtonOk: Vue.t('app.modal.button_ok'),
modalButtonCancel: Vue.t('app.cancel'),
/* Uncomment to enable Material theme: */
// material: true,
routes: Routes,
},
// Register App Component
components: {
app: App
}
})
getLoginUser(store)
| src/main.js | // Import Vue
import Vue from 'vue'
// Import F7, F7-Vue
import 'framework7'
import Framework7Vue from 'framework7-vue'
// Import F7 iOS Theme Styles
import 'framework7/dist/css/framework7.ios.min.css'
import 'framework7/dist/css/framework7.ios.colors.min.css'
/* OR for Material Theme:
import Framework7Theme from 'framework7/dist/css/framework7.material.min.css'
import Framework7ThemeColors from 'framework7/dist/css/framework7.material.colors.min.css'
*/
// Import App Custom Styles
import './assets/fonts/iconfont.css'
import './assets/styles/app.less'
// Import Routes
import Routes from './routes.js'
// Import App Component
import App from './app'
// Import Vuex store
import store from './store'
import {getLoginUser} from './store/actions'
// Init network framework
import './network'
// Init Vue Plugin
Vue.use(Framework7Vue)
// Import language file
import VueI18n from 'vue-i18n'
import StoreCache from './utils/storeCache'
import enUS from './lang/en_us'
import zhCN from './lang/zh_cn'
let cache = new StoreCache('vuex')
Vue.use(VueI18n)
Vue.config.lang = cache.get('lang')
Vue.locale('en', enUS)
Vue.locale('zh', zhCN)
// Init App
new Vue({
el: '#app',
store,
template: '<app/>',
// Init Framework7 by passing parameters here
framework7: {
root: '#app',
modalTitle: Vue.t('app.modal.title'),
modalButtonOk: Vue.t('app.modal.button_ok'),
modalButtonCancel: Vue.t('app.cancel'),
/* Uncomment to enable Material theme: */
// material: true,
routes: Routes,
},
// Register App Component
components: {
app: App
}
})
getLoginUser(store)
| Set default lang
| src/main.js | Set default lang | <ide><path>rc/main.js
<ide>
<ide> let cache = new StoreCache('vuex')
<ide> Vue.use(VueI18n)
<del>Vue.config.lang = cache.get('lang')
<add>Vue.config.lang = cache.get('lang') || 'en'
<ide> Vue.locale('en', enUS)
<ide> Vue.locale('zh', zhCN)
<ide> |
|
JavaScript | mit | 07af218014691a5a249cc7cc262a1ebe99ff1fb5 | 0 | nus-mtp/etutorial,nus-mtp/reindeer,nus-mtp/reindeer,nus-mtp/reindeer | /**
* Created by shiyu on 1/4/16.
*/
var Presentation = require('./presentation');
var Presentations = function () {
this.hashOfPresentations = {};
this.currentPresentationID = undefined;
this.nextPresentationID = 0;
this.newBlankPresentation();
}
Presentations.prototype.newPresentation = function(presentationObject) {
var presentationID = this.getNewPresentationID();
this.hashOfPresentations[presentationID] = new Presentation(presentationObject);
if (!this.currentPresentationID) {
this.currentPresentationID = presentationID;
}
return presentationID;
}
Presentations.prototype.newBlankPresentation = function() {
var presentationID = this.getNewPresentationID();
this.hashOfPresentations[presentationID] = new Presentation([{path: null}]);
if (!this.currentPresentationID) {
this.currentPresentationID = presentationID;
}
return presentationID;
}
Presentations.prototype.getNewPresentationID = function() {
return this.nextPresentationID++;
}
Presentations.prototype.getCurrentPresentation = function() {
return this.hashOfPresentations[this.currentPresentationID];
}
Presentations.prototype.switchToPresentationByID = function(presentationID) {
if (this.hashOfPresentations[presentationID]) {
this.currentPresentationID = presentationID;
return true;
} else {
return false;
}
}
Presentations.prototype.getAllPresentations = function() {
// Iterate through all presentations, extract presentationID and path to first page(this will be the thumbnail)
var presentations = [];
for (var presentationID in this.hashOfPresentations) {
var presentation = this.hashOfPresentations[presentationID];
var presentationObject = {};
presentationObject['id'] = presentationID;
var firstSlideOfPresentation = presentation.getSlideByIndex(0);
presentationObject['thumbnailPath'] = firstSlideOfPresentation.slideImagePath;
presentationObject['class'] = '';
if (presentationID == this.currentPresentationID) {
presentationObject['class'] = "active";
}
presentations.push(presentationObject);
}
return presentations;
}
module.exports = Presentations;
| source/models/Presentations.js | /**
* Created by shiyu on 1/4/16.
*/
var Presentation = require('./Presentation');
var Presentations = function () {
this.hashOfPresentations = {};
this.currentPresentationID = undefined;
this.nextPresentationID = 0;
this.newBlankPresentation();
}
Presentations.prototype.newPresentation = function(presentationObject) {
var presentationID = this.getNewPresentationID();
this.hashOfPresentations[presentationID] = new Presentation(presentationObject);
if (!this.currentPresentationID) {
this.currentPresentationID = presentationID;
}
return presentationID;
}
Presentations.prototype.newBlankPresentation = function() {
var presentationID = this.getNewPresentationID();
this.hashOfPresentations[presentationID] = new Presentation([{path: null}]);
if (!this.currentPresentationID) {
this.currentPresentationID = presentationID;
}
return presentationID;
}
Presentations.prototype.getNewPresentationID = function() {
return this.nextPresentationID++;
}
Presentations.prototype.getCurrentPresentation = function() {
return this.hashOfPresentations[this.currentPresentationID];
}
Presentations.prototype.switchToPresentationByID = function(presentationID) {
if (this.hashOfPresentations[presentationID]) {
this.currentPresentationID = presentationID;
return true;
} else {
return false;
}
}
Presentations.prototype.getAllPresentations = function() {
// Iterate through all presentations, extract presentationID and path to first page(this will be the thumbnail)
var presentations = [];
for (var presentationID in this.hashOfPresentations) {
var presentation = this.hashOfPresentations[presentationID];
var presentationObject = {};
presentationObject['id'] = presentationID;
var firstSlideOfPresentation = presentation.getSlideByIndex(0);
presentationObject['thumbnailPath'] = firstSlideOfPresentation.slideImagePath;
presentationObject['class'] = '';
if (presentationID == this.currentPresentationID) {
presentationObject['class'] = "active";
}
presentations.push(presentationObject);
}
return presentations;
}
module.exports = Presentations;
| Fix requrie
| source/models/Presentations.js | Fix requrie | <ide><path>ource/models/Presentations.js
<ide> /**
<ide> * Created by shiyu on 1/4/16.
<ide> */
<del>var Presentation = require('./Presentation');
<add>var Presentation = require('./presentation');
<ide>
<ide> var Presentations = function () {
<ide> this.hashOfPresentations = {}; |
|
Java | mit | f42658d0c1c248ff68ba1c19ac3eb50cadabf68e | 0 | hpautonomy/find,hpe-idol/find,hpe-idol/find,hpe-idol/find,hpautonomy/find,hpautonomy/find,hpautonomy/find,hpe-idol/find,hpe-idol/find,hpautonomy/find | /*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.core.export.service;
import com.hp.autonomy.searchcomponents.core.search.QueryRequest;
import com.hp.autonomy.searchcomponents.core.search.QueryRequestBuilder;
import com.hp.autonomy.searchcomponents.core.search.QueryRestrictions;
import com.hp.autonomy.searchcomponents.core.test.TestUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.*;
@SuppressWarnings("SpringJavaAutowiredMembersInspection")
@RunWith(SpringRunner.class)
@JsonTest
@AutoConfigureJsonTesters(enabled = false)
public abstract class PlatformDataExportServiceIT<R extends QueryRequest<Q>, Q extends QueryRestrictions<?>, E extends Exception> {
@Autowired
private PlatformDataExportService<R, E> exportService;
@Autowired
private TestUtils<Q> testUtils;
@Autowired
private ObjectFactory<QueryRequestBuilder<R, Q, ?>> queryRequestBuilderFactory;
@Test
public void exportToCsv() throws E, IOException {
final R queryRequest = queryRequestBuilderFactory.getObject()
.queryRestrictions(testUtils.buildQueryRestrictions())
.queryType(QueryRequest.QueryType.MODIFIED)
.build();
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
exportService.exportQueryResults(outputStream, queryRequest, ExportFormat.CSV, Collections.emptyList(), 1001L);
final String output = outputStream.toString();
assertNotNull(output);
try (final CSVParser csvParser = CSVParser.parse(output, CSVFormat.EXCEL)) {
final List<CSVRecord> records = csvParser.getRecords();
assertThat(records, not(empty()));
final CSVRecord headerRecord = records.get(0);
assertThat(headerRecord.get(0), endsWith("Reference")); // byte-order mark may get in the way
assertEquals("Database", headerRecord.get(1));
final CSVRecord firstDataRecord = records.get(1);
final String firstDataRecordReference = firstDataRecord.get(0);
assertNotNull(firstDataRecordReference);
assertFalse(firstDataRecordReference.trim().isEmpty());
final String firstDataRecordDatabase = firstDataRecord.get(1);
assertFalse(firstDataRecordDatabase.trim().isEmpty());
}
}
}
| webapp/core/src/test/java/com/hp/autonomy/frontend/find/core/export/service/PlatformDataExportServiceIT.java | /*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.core.export.service;
import com.hp.autonomy.searchcomponents.core.search.QueryRequest;
import com.hp.autonomy.searchcomponents.core.search.QueryRequestBuilder;
import com.hp.autonomy.searchcomponents.core.search.QueryRestrictions;
import com.hp.autonomy.searchcomponents.core.test.TestUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.Collections;
import static org.junit.Assert.assertNotNull;
@SuppressWarnings("SpringJavaAutowiredMembersInspection")
@RunWith(SpringRunner.class)
@JsonTest
@AutoConfigureJsonTesters(enabled = false)
public abstract class PlatformDataExportServiceIT<R extends QueryRequest<Q>, Q extends QueryRestrictions<?>, E extends Exception> {
@Autowired
private PlatformDataExportService<R, E> exportService;
@Autowired
private TestUtils<Q> testUtils;
@Autowired
private ObjectFactory<QueryRequestBuilder<R, Q, ?>> queryRequestBuilderFactory;
@Test
public void exportToCsv() throws E, IOException {
final R queryRequest = queryRequestBuilderFactory.getObject()
.queryRestrictions(testUtils.buildQueryRestrictions())
.queryType(QueryRequest.QueryType.MODIFIED)
.build();
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
exportService.exportQueryResults(outputStream, queryRequest, ExportFormat.CSV, Collections.emptyList(), 1001L);
assertNotNull(outputStream.toString());
}
}
| Make service integration test for field export more rigorous (FIND-934)
[rev. matthew.gordon]
| webapp/core/src/test/java/com/hp/autonomy/frontend/find/core/export/service/PlatformDataExportServiceIT.java | Make service integration test for field export more rigorous (FIND-934) | <ide><path>ebapp/core/src/test/java/com/hp/autonomy/frontend/find/core/export/service/PlatformDataExportServiceIT.java
<ide> import com.hp.autonomy.searchcomponents.core.search.QueryRequestBuilder;
<ide> import com.hp.autonomy.searchcomponents.core.search.QueryRestrictions;
<ide> import com.hp.autonomy.searchcomponents.core.test.TestUtils;
<add>import org.apache.commons.csv.CSVFormat;
<add>import org.apache.commons.csv.CSVParser;
<add>import org.apache.commons.csv.CSVRecord;
<ide> import org.apache.commons.io.output.ByteArrayOutputStream;
<ide> import org.junit.Test;
<ide> import org.junit.runner.RunWith;
<ide>
<ide> import java.io.IOException;
<ide> import java.util.Collections;
<add>import java.util.List;
<ide>
<del>import static org.junit.Assert.assertNotNull;
<add>import static org.hamcrest.Matchers.empty;
<add>import static org.hamcrest.Matchers.endsWith;
<add>import static org.hamcrest.Matchers.not;
<add>import static org.junit.Assert.*;
<ide>
<ide> @SuppressWarnings("SpringJavaAutowiredMembersInspection")
<ide> @RunWith(SpringRunner.class)
<ide>
<ide> final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
<ide> exportService.exportQueryResults(outputStream, queryRequest, ExportFormat.CSV, Collections.emptyList(), 1001L);
<del> assertNotNull(outputStream.toString());
<add> final String output = outputStream.toString();
<add> assertNotNull(output);
<add>
<add> try (final CSVParser csvParser = CSVParser.parse(output, CSVFormat.EXCEL)) {
<add> final List<CSVRecord> records = csvParser.getRecords();
<add> assertThat(records, not(empty()));
<add> final CSVRecord headerRecord = records.get(0);
<add> assertThat(headerRecord.get(0), endsWith("Reference")); // byte-order mark may get in the way
<add> assertEquals("Database", headerRecord.get(1));
<add> final CSVRecord firstDataRecord = records.get(1);
<add> final String firstDataRecordReference = firstDataRecord.get(0);
<add> assertNotNull(firstDataRecordReference);
<add> assertFalse(firstDataRecordReference.trim().isEmpty());
<add> final String firstDataRecordDatabase = firstDataRecord.get(1);
<add> assertFalse(firstDataRecordDatabase.trim().isEmpty());
<add> }
<ide> }
<ide> } |
|
JavaScript | mit | d189904deb71ed2edf8858f4628e2cb619a4fa32 | 0 | casa-dv/front_end,casa-dv/front_end | /**
* Map setup
*/
console.log("Step 0: load main.js");
function load_map(id,options){
console.log("Step 2: load map "+id);
var map = L.map(id).setView([options.lat, options.lng], options.zoom);
var access_token = 'pk.eyJ1IjoidG9tYWxydXNzZWxsIiwiYSI6Im9TM1lfSWsifQ.0dE4yPsqc7HJbBT22ceU5g';
var mapbox_style = 'mapbox.satellite';
var tile_url = 'https://{s}.tiles.mapbox.com/v4/' + mapbox_style + '/{z}/{x}/{y}.png?access_token=' + access_token;
L.tileLayer(tile_url, {
attribution: 'Imagery © <a href="//mapbox.com">Mapbox</a>',
maxZoom: 16
}).addTo(map);
return map;
}
function load_data_for_map_places(){
d3.json('http://casa-dv.made-by-tom.co.uk/places?lat='+options.lat+"&lon="+options.lng+"&type=cafe", function(response){
console.log("Step 3: done loading place data, now add it to the map");
L.geoJson(response, {
onEachFeature: function (feature, layer) {
layer.on("click",function(){
document.getElementById("place_name").innerHTML = feature.properties.name;
});
}
}).addTo(window.maps.map_places);
});
}
function load_data_for_map_events(){
d3.json('http://casa-dv.made-by-tom.co.uk/eventbrite?lat='+options.lat+"&lon="+options.lng, function(response){
console.log("Step 3: done loading event data, now add it to the map");
var timeline = L.timeline(response, {
onEachFeature: function (feature, layer) {
layer.on("click",function(){
console.log(feature.properties);
// TODO fill in details with event time, description etc.
});
}
}).addTo(window.maps.map_events);
// create timeline control
var timelineControl = L.timelineSliderControl({
formatOutput: function(date){
return moment(date).format("YYYY-MM-DD");
},
enableKeyboardControls: true,
});
// add timeline control to page
var timelineControlElement = timelineControl.onAdd(maps.map_events);
timelineControl.addTimelines(timeline);
document.getElementById('timeline').appendChild(timelineControlElement);
});
}
function setup(){
console.log("Step 1: set up options");
var options = {
lat: 51.5218991,
lng: -0.1381519,
zoom: 15
};
window.options = options;
window.maps = {};
var map_ids = [
"map_buses",
"map_places",
"map_events"
];
// http://casa-dv.made-by-tom.co.uk/eventbrite?lat=51.5218991&lon=-0.1381519
// http://casa-dv.made-by-tom.co.uk/forecast?lat=51.5218991&lon=-0.1381519
for (var i = 0; i < map_ids.length; i++) {
maps[map_ids[i]] = load_map(map_ids[i], options);
}
load_data_for_map_places();
load_data_for_map_events();
}
setup(); | timeline_position_example/main.js | /**
* Map setup
*/
function load_map(id,options){
var map = L.map(id).setView([options.lat, options.lng], options.zoom);
var access_token = 'pk.eyJ1IjoidG9tYWxydXNzZWxsIiwiYSI6Im9TM1lfSWsifQ.0dE4yPsqc7HJbBT22ceU5g';
var mapbox_style = 'mapbox.satellite';
var tile_url = 'https://{s}.tiles.mapbox.com/v4/' + mapbox_style + '/{z}/{x}/{y}.png?access_token=' + access_token;
L.tileLayer(tile_url, {
attribution: 'Imagery © <a href="//mapbox.com">Mapbox</a>',
maxZoom: 16
}).addTo(map);
return map;
}
function update_options_from_hash(options){
var hash = window.location.hash;
if (hash.length){
var elements = hash.substring(1).split('&');
for (var i = 0; i < elements.length; i++) {
var pair = elements[i].split('=');
options[pair[0]] = pair[1];
}
}
return options;
}
function load_data_for_map_places(){
d3.json('http://casa-dv.made-by-tom.co.uk/places?lat='+options.lat+"&lon="+options.lng+"&type=cafe", function(response){
L.geoJson(response, {
onEachFeature: function (feature, layer) {
layer.on("click",function(){
document.getElementById("place_name").innerHTML = feature.properties.name;
});
}
}).addTo(window.maps.map_places);
console.log(response);
});
}
function load_data_for_map_events(){
d3.json('http://casa-dv.made-by-tom.co.uk/eventbrite?lat='+options.lat+"&lon="+options.lng, function(response){
var timeline = L.timeline(response, {
onEachFeature: function (feature, layer) {
layer.on("click",function(){
console.log(feature.properties);
// TODO fill in details with event time, description etc.
});
}
}).addTo(window.maps.map_events);
var timelineControl = L.timelineSliderControl({
formatOutput: function(date){
return moment(date).format("YYYY-MM-DD");
},
enableKeyboardControls: true,
});
var timelineControlElement = timelineControl.onAdd(maps.map_events);
timelineControl.addTimelines(timeline);
document.getElementById('timeline').appendChild(timelineControlElement);
console.log(response);
});
}
function init(){
var defaults = {
lat: 51.5218991,
lng: -0.1381519,
zoom: 15
};
window.options = update_options_from_hash(defaults);
window.maps = {};
var map_ids = [
"map_buses",
"map_places",
"map_events"
];
// http://casa-dv.made-by-tom.co.uk/eventbrite?lat=51.5218991&lon=-0.1381519
// http://casa-dv.made-by-tom.co.uk/forecast?lat=51.5218991&lon=-0.1381519
for (var i = 0; i < map_ids.length; i++) {
maps[map_ids[i]] = load_map(map_ids[i], options);
}
load_data_for_map_places();
load_data_for_map_events();
}
init(); | add console.log
| timeline_position_example/main.js | add console.log | <ide><path>imeline_position_example/main.js
<ide> /**
<ide> * Map setup
<ide> */
<add>console.log("Step 0: load main.js");
<ide>
<ide> function load_map(id,options){
<add> console.log("Step 2: load map "+id);
<add>
<ide> var map = L.map(id).setView([options.lat, options.lng], options.zoom);
<ide>
<ide> var access_token = 'pk.eyJ1IjoidG9tYWxydXNzZWxsIiwiYSI6Im9TM1lfSWsifQ.0dE4yPsqc7HJbBT22ceU5g';
<ide> return map;
<ide> }
<ide>
<del>function update_options_from_hash(options){
<del> var hash = window.location.hash;
<del> if (hash.length){
<del> var elements = hash.substring(1).split('&');
<del> for (var i = 0; i < elements.length; i++) {
<del> var pair = elements[i].split('=');
<del> options[pair[0]] = pair[1];
<del> }
<del> }
<del> return options;
<del>}
<del>
<ide> function load_data_for_map_places(){
<ide> d3.json('http://casa-dv.made-by-tom.co.uk/places?lat='+options.lat+"&lon="+options.lng+"&type=cafe", function(response){
<add> console.log("Step 3: done loading place data, now add it to the map");
<add>
<ide> L.geoJson(response, {
<ide> onEachFeature: function (feature, layer) {
<ide> layer.on("click",function(){
<ide> });
<ide> }
<ide> }).addTo(window.maps.map_places);
<del> console.log(response);
<ide> });
<ide> }
<ide>
<ide> function load_data_for_map_events(){
<ide> d3.json('http://casa-dv.made-by-tom.co.uk/eventbrite?lat='+options.lat+"&lon="+options.lng, function(response){
<add> console.log("Step 3: done loading event data, now add it to the map");
<add>
<ide> var timeline = L.timeline(response, {
<ide> onEachFeature: function (feature, layer) {
<ide> layer.on("click",function(){
<ide> });
<ide> }
<ide> }).addTo(window.maps.map_events);
<add>
<add> // create timeline control
<ide> var timelineControl = L.timelineSliderControl({
<ide> formatOutput: function(date){
<ide> return moment(date).format("YYYY-MM-DD");
<ide> },
<ide> enableKeyboardControls: true,
<ide> });
<add>
<add> // add timeline control to page
<ide> var timelineControlElement = timelineControl.onAdd(maps.map_events);
<ide> timelineControl.addTimelines(timeline);
<ide> document.getElementById('timeline').appendChild(timelineControlElement);
<del> console.log(response);
<add>
<ide> });
<ide> }
<ide>
<del>function init(){
<del> var defaults = {
<add>
<add>function setup(){
<add> console.log("Step 1: set up options");
<add>
<add> var options = {
<ide> lat: 51.5218991,
<ide> lng: -0.1381519,
<ide> zoom: 15
<ide> };
<ide>
<del> window.options = update_options_from_hash(defaults);
<add> window.options = options;
<ide> window.maps = {};
<ide>
<ide> var map_ids = [
<ide> }
<ide>
<ide>
<del>init();
<add>setup(); |
|
Java | agpl-3.0 | da36e02231998de0a879ce6e127be8ea8154e69b | 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 | aba40ae0-2e5f-11e5-9284-b827eb9e62be | hello.java | ab9e8df4-2e5f-11e5-9284-b827eb9e62be | aba40ae0-2e5f-11e5-9284-b827eb9e62be | hello.java | aba40ae0-2e5f-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>ab9e8df4-2e5f-11e5-9284-b827eb9e62be
<add>aba40ae0-2e5f-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 747e11c6ff28fc833855b9979ce68a15b99915f6 | 0 | khorimoto/connectbot,kruton/connectbot,jklein24/connectbot,connectbot/connectbot,rhansby/connectbot,Potass/ConnectBot,alescdb/connectbot,connectbot/connectbot,nixomose/connectbot,alescdb/connectbot,redshodan/connectbot,jklein24/connectbot,iiordanov/BSSH,rhansby/connectbot,alescdb/connectbot,iiordanov/BSSH,ipmobiletech/connectbot,trygveaa/connectbot,redshodan/connectbot,lotan/connectbot,Potass/ConnectBot,ipmobiletech/connectbot,ipmobiletech/connectbot,khorimoto/connectbot,jklein24/connectbot,khorimoto/connectbot,rhansby/connectbot,ipmobiletech/connectbot,lotan/connectbot,redshodan/connectbot,nixomose/connectbot,connectbot/connectbot,trygveaa/connectbot,iiordanov/BSSH,lotan/connectbot,kruton/connectbot,kruton/connectbot,nixomose/connectbot,trygveaa/connectbot,Potass/ConnectBot | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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.connectbot;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Collections;
import java.util.EventListener;
import java.util.LinkedList;
import java.util.List;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import org.openintents.intents.FileManagerIntents;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.PEMDecoder;
import com.trilead.ssh2.crypto.PEMStructure;
/**
* List public keys in database by nickname and describe their properties. Allow users to import,
* generate, rename, and delete key pairs.
*
* @author Kenny Root
*/
public class PubkeyListActivity extends ListActivity implements EventListener {
public final static String TAG = "CB.PubkeyListActivity";
private static final int MAX_KEYFILE_SIZE = 8192;
private static final int REQUEST_CODE_PICK_FILE = 1;
// Constants for AndExplorer's file picking intent
private static final String ANDEXPLORER_TITLE = "explorer_title";
private static final String MIME_TYPE_ANDEXPLORER_FILE = "vnd.android.cursor.dir/lysesoft.andexplorer.file";
protected PubkeyDatabase pubkeydb;
private List<PubkeyBean> pubkeys;
protected ClipboardManager clipboard;
protected LayoutInflater inflater = null;
protected TerminalManager bound = null;
private MenuItem onstartToggle = null;
private MenuItem confirmUse = null;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
updateList();
}
public void onServiceDisconnected(ComponentName className) {
bound = null;
updateList();
}
};
@Override
public void onStart() {
super.onStart();
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
pubkeydb = PubkeyDatabase.get(this);
updateList();
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
pubkeydb = null;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_pubkeylist);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_pubkey_list)));
registerForContextMenu(getListView());
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(position);
boolean loaded = bound != null && bound.isKeyLoaded(pubkey.getNickname());
// handle toggling key in-memory on/off
if (loaded) {
bound.removeKey(pubkey.getNickname());
updateList();
} else {
handleAddKey(pubkey);
}
}
});
clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
inflater = LayoutInflater.from(this);
}
/**
* Read given file into memory as <code>byte[]</code>.
*/
protected static byte[] readRaw(File file) throws Exception {
InputStream is = new FileInputStream(file);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
os.close();
is.close();
return os.toByteArray();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem generatekey = menu.add(R.string.pubkey_generate);
generatekey.setIcon(android.R.drawable.ic_menu_manage);
generatekey.setIntent(new Intent(PubkeyListActivity.this, GeneratePubkeyActivity.class));
MenuItem importkey = menu.add(R.string.pubkey_import);
importkey.setIcon(android.R.drawable.ic_menu_upload);
importkey.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Uri sdcard = Uri.fromFile(Environment.getExternalStorageDirectory());
String pickerTitle = getString(R.string.pubkey_list_pick);
// Try to use OpenIntent's file browser to pick a file
Intent intent = new Intent(FileManagerIntents.ACTION_PICK_FILE);
intent.setData(sdcard);
intent.putExtra(FileManagerIntents.EXTRA_TITLE, pickerTitle);
intent.putExtra(FileManagerIntents.EXTRA_BUTTON_TEXT, getString(android.R.string.ok));
try {
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
} catch (ActivityNotFoundException e) {
// If OI didn't work, try AndExplorer
intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(sdcard, MIME_TYPE_ANDEXPLORER_FILE);
intent.putExtra(ANDEXPLORER_TITLE, pickerTitle);
try {
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
} catch (ActivityNotFoundException e1) {
pickFileSimple();
}
}
return true;
}
});
return true;
}
protected void handleAddKey(final PubkeyBean pubkey) {
if (pubkey.isEncrypted()) {
final View view = inflater.inflate(R.layout.dia_password, null);
final EditText passwordField = (EditText) view.findViewById(android.R.id.text1);
new AlertDialog.Builder(PubkeyListActivity.this)
.setView(view)
.setPositiveButton(R.string.pubkey_unlock, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
handleAddKey(pubkey, passwordField.getText().toString());
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
} else {
handleAddKey(pubkey, null);
}
}
protected void handleAddKey(PubkeyBean keybean, String password) {
KeyPair pair = null;
if (PubkeyDatabase.KEY_TYPE_IMPORTED.equals(keybean.getType())) {
// load specific key using pem format
try {
pair = PEMDecoder.decode(new String(keybean.getPrivateKey()).toCharArray(), password);
} catch (Exception e) {
String message = getResources().getString(R.string.pubkey_failed_add, keybean.getNickname());
Log.e(TAG, message, e);
Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG).show();
}
} else {
// load using internal generated format
try {
PrivateKey privKey = PubkeyUtils.decodePrivate(keybean.getPrivateKey(), keybean.getType(), password);
PublicKey pubKey = PubkeyUtils.decodePublic(keybean.getPublicKey(), keybean.getType());
Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey));
pair = new KeyPair(pubKey, privKey);
} catch (Exception e) {
String message = getResources().getString(R.string.pubkey_failed_add, keybean.getNickname());
Log.e(TAG, message, e);
Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG).show();
return;
}
}
if (pair == null) {
return;
}
Log.d(TAG, String.format("Unlocked key '%s'", keybean.getNickname()));
// save this key in memory
bound.addKey(keybean, pair, true);
updateList();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Create menu to handle deleting and editing pubkey
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(info.position);
menu.setHeaderTitle(pubkey.getNickname());
// TODO: option load/unload key from in-memory list
// prompt for password as needed for passworded keys
// cant change password or clipboard imported keys
final boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType());
final boolean loaded = bound != null && bound.isKeyLoaded(pubkey.getNickname());
MenuItem load = menu.add(loaded ? R.string.pubkey_memory_unload : R.string.pubkey_memory_load);
load.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (loaded) {
bound.removeKey(pubkey.getNickname());
updateList();
} else {
handleAddKey(pubkey);
//bound.addKey(nickname, trileadKey);
}
return true;
}
});
onstartToggle = menu.add(R.string.pubkey_load_on_start);
onstartToggle.setEnabled(!pubkey.isEncrypted());
onstartToggle.setCheckable(true);
onstartToggle.setChecked(pubkey.isStartup());
onstartToggle.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// toggle onstart status
pubkey.setStartup(!pubkey.isStartup());
pubkeydb.savePubkey(pubkey);
updateList();
return true;
}
});
MenuItem copyPublicToClipboard = menu.add(R.string.pubkey_copy_public);
copyPublicToClipboard.setEnabled(!imported);
copyPublicToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
try {
PublicKey pk = PubkeyUtils.decodePublic(pubkey.getPublicKey(), pubkey.getType());
String openSSHPubkey = PubkeyUtils.convertToOpenSSHFormat(pk, pubkey.getNickname());
clipboard.setText(openSSHPubkey);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
MenuItem copyPrivateToClipboard = menu.add(R.string.pubkey_copy_private);
copyPrivateToClipboard.setEnabled(!pubkey.isEncrypted() || imported);
copyPrivateToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
try {
String data = null;
if (imported)
data = new String(pubkey.getPrivateKey());
else {
PrivateKey pk = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType());
data = PubkeyUtils.exportPEM(pk, null);
}
clipboard.setText(data);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
MenuItem changePassword = menu.add(R.string.pubkey_change_password);
changePassword.setEnabled(!imported);
changePassword.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final View changePasswordView = inflater.inflate(R.layout.dia_changepassword, null, false);
((TableRow) changePasswordView.findViewById(R.id.old_password_prompt))
.setVisibility(pubkey.isEncrypted() ? View.VISIBLE : View.GONE);
new AlertDialog.Builder(PubkeyListActivity.this)
.setView(changePasswordView)
.setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String oldPassword = ((EditText) changePasswordView.findViewById(R.id.old_password)).getText().toString();
String password1 = ((EditText) changePasswordView.findViewById(R.id.password1)).getText().toString();
String password2 = ((EditText) changePasswordView.findViewById(R.id.password2)).getText().toString();
if (!password1.equals(password2)) {
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_passwords_do_not_match_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
return;
}
try {
if (!pubkey.changePassword(oldPassword, password1))
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_wrong_password_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
else {
pubkeydb.savePubkey(pubkey);
updateList();
}
} catch (Exception e) {
Log.e(TAG, "Could not change private key password", e);
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_key_corrupted_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
}
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
confirmUse = menu.add(R.string.pubkey_confirm_use);
confirmUse.setCheckable(true);
confirmUse.setChecked(pubkey.isConfirmUse());
confirmUse.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// toggle confirm use
pubkey.setConfirmUse(!pubkey.isConfirmUse());
pubkeydb.savePubkey(pubkey);
updateList();
return true;
}
});
MenuItem delete = menu.add(R.string.pubkey_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(getString(R.string.delete_message, pubkey.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// dont forget to remove from in-memory
if (loaded)
bound.removeKey(pubkey.getNickname());
// delete from backend database and update gui
pubkeydb.deletePubkey(pubkey);
updateList();
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
protected void updateList() {
if (pubkeydb == null) return;
pubkeys = pubkeydb.allPubkeys();
PubkeyAdapter adapter = new PubkeyAdapter(this, pubkeys);
this.setListAdapter(adapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && intent != null) {
Uri uri = intent.getData();
try {
if (uri != null) {
readKeyFromFile(new File(URI.create(uri.toString())));
} else {
String filename = intent.getDataString();
if (filename != null)
readKeyFromFile(new File(URI.create(filename)));
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Couldn't read from picked file", e);
}
}
break;
}
}
/**
* @param name
*/
private void readKeyFromFile(File file) {
PubkeyBean pubkey = new PubkeyBean();
// find the exact file selected
pubkey.setNickname(file.getName());
if (file.length() > MAX_KEYFILE_SIZE) {
Toast.makeText(PubkeyListActivity.this,
R.string.pubkey_import_parse_problem,
Toast.LENGTH_LONG).show();
return;
}
// parse the actual key once to check if its encrypted
// then save original file contents into our database
try {
byte[] raw = readRaw(file);
String data = new String(raw);
if (data.startsWith(PubkeyUtils.PKCS8_START)) {
int start = data.indexOf(PubkeyUtils.PKCS8_START) + PubkeyUtils.PKCS8_START.length();
int end = data.indexOf(PubkeyUtils.PKCS8_END);
if (end > start) {
char[] encoded = data.substring(start, end - 1).toCharArray();
Log.d(TAG, "encoded: " + new String(encoded));
byte[] decoded = Base64.decode(encoded);
KeyPair kp = PubkeyUtils.recoverKeyPair(decoded);
pubkey.setType(kp.getPrivate().getAlgorithm());
pubkey.setPrivateKey(kp.getPrivate().getEncoded());
pubkey.setPublicKey(kp.getPublic().getEncoded());
} else {
Log.e(TAG, "Problem parsing PKCS#8 file; corrupt?");
Toast.makeText(PubkeyListActivity.this,
R.string.pubkey_import_parse_problem,
Toast.LENGTH_LONG).show();
}
} else {
PEMStructure struct = PEMDecoder.parsePEM(new String(raw).toCharArray());
pubkey.setEncrypted(PEMDecoder.isPEMEncrypted(struct));
pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
pubkey.setPrivateKey(raw);
}
// write new value into database
pubkeydb = PubkeyDatabase.get(this);
pubkeydb.savePubkey(pubkey);
updateList();
} catch (Exception e) {
Log.e(TAG, "Problem parsing imported private key", e);
Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show();
}
}
/**
*
*/
private void pickFileSimple() {
// build list of all files in sdcard root
final File sdcard = Environment.getExternalStorageDirectory();
Log.d(TAG, sdcard.toString());
// Don't show a dialog if the SD card is completely absent.
final String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)
&& !Environment.MEDIA_MOUNTED.equals(state)) {
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_sdcard_absent)
.setNegativeButton(android.R.string.cancel, null).create().show();
return;
}
List<String> names = new LinkedList<String>();
{
File[] files = sdcard.listFiles();
if (files != null) {
for (File file : sdcard.listFiles()) {
if (file.isDirectory()) continue;
names.add(file.getName());
}
}
}
Collections.sort(names);
final String[] namesList = names.toArray(new String[] {});
Log.d(TAG, names.toString());
// prompt user to select any file from the sdcard root
new AlertDialog.Builder(PubkeyListActivity.this)
.setTitle(R.string.pubkey_list_pick)
.setItems(namesList, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String name = namesList[arg1];
readKeyFromFile(new File(sdcard, name));
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
}
class PubkeyAdapter extends ArrayAdapter<PubkeyBean> {
private List<PubkeyBean> pubkeys;
class ViewHolder {
public TextView nickname;
public TextView caption;
public ImageView icon;
}
public PubkeyAdapter(Context context, List<PubkeyBean> pubkeys) {
super(context, R.layout.item_pubkey, pubkeys);
this.pubkeys = pubkeys;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_pubkey, null, false);
holder = new ViewHolder();
holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
holder.icon = (ImageView) convertView.findViewById(android.R.id.icon1);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
PubkeyBean pubkey = pubkeys.get(position);
holder.nickname.setText(pubkey.getNickname());
boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType());
if (imported) {
try {
PEMStructure struct = PEMDecoder.parsePEM(new String(pubkey.getPrivateKey()).toCharArray());
String type = (struct.pemType == PEMDecoder.PEM_RSA_PRIVATE_KEY) ? "RSA" : "DSA";
holder.caption.setText(String.format("%s unknown-bit", type));
} catch (IOException e) {
Log.e(TAG, "Error decoding IMPORTED public key at " + pubkey.getId(), e);
}
} else {
try {
holder.caption.setText(pubkey.getDescription());
} catch (Exception e) {
Log.e(TAG, "Error decoding public key at " + pubkey.getId(), e);
holder.caption.setText(R.string.pubkey_unknown_format);
}
}
if (bound == null) {
holder.icon.setVisibility(View.GONE);
} else {
holder.icon.setVisibility(View.VISIBLE);
if (bound.isKeyLoaded(pubkey.getNickname()))
holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
else
holder.icon.setImageState(new int[] { }, true);
}
return convertView;
}
}
}
| app/src/main/java/org/connectbot/PubkeyListActivity.java | /*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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.connectbot;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Collections;
import java.util.EventListener;
import java.util.LinkedList;
import java.util.List;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import org.openintents.intents.FileManagerIntents;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.PEMDecoder;
import com.trilead.ssh2.crypto.PEMStructure;
/**
* List public keys in database by nickname and describe their properties. Allow users to import,
* generate, rename, and delete key pairs.
*
* @author Kenny Root
*/
public class PubkeyListActivity extends ListActivity implements EventListener {
public final static String TAG = "CB.PubkeyListActivity";
private static final int MAX_KEYFILE_SIZE = 8192;
private static final int REQUEST_CODE_PICK_FILE = 1;
// Constants for AndExplorer's file picking intent
private static final String ANDEXPLORER_TITLE = "explorer_title";
private static final String MIME_TYPE_ANDEXPLORER_FILE = "vnd.android.cursor.dir/lysesoft.andexplorer.file";
protected PubkeyDatabase pubkeydb;
private List<PubkeyBean> pubkeys;
protected ClipboardManager clipboard;
protected LayoutInflater inflater = null;
protected TerminalManager bound = null;
private MenuItem onstartToggle = null;
private MenuItem confirmUse = null;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
updateList();
}
public void onServiceDisconnected(ComponentName className) {
bound = null;
updateList();
}
};
@Override
public void onStart() {
super.onStart();
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if (pubkeydb == null)
pubkeydb = PubkeyDatabase.get(this);
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
pubkeydb = null;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_pubkeylist);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_pubkey_list)));
// connect with hosts database and populate list
pubkeydb = PubkeyDatabase.get(this);
updateList();
registerForContextMenu(getListView());
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(position);
boolean loaded = bound != null && bound.isKeyLoaded(pubkey.getNickname());
// handle toggling key in-memory on/off
if (loaded) {
bound.removeKey(pubkey.getNickname());
updateList();
} else {
handleAddKey(pubkey);
}
}
});
clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
inflater = LayoutInflater.from(this);
}
/**
* Read given file into memory as <code>byte[]</code>.
*/
protected static byte[] readRaw(File file) throws Exception {
InputStream is = new FileInputStream(file);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
os.close();
is.close();
return os.toByteArray();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem generatekey = menu.add(R.string.pubkey_generate);
generatekey.setIcon(android.R.drawable.ic_menu_manage);
generatekey.setIntent(new Intent(PubkeyListActivity.this, GeneratePubkeyActivity.class));
MenuItem importkey = menu.add(R.string.pubkey_import);
importkey.setIcon(android.R.drawable.ic_menu_upload);
importkey.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Uri sdcard = Uri.fromFile(Environment.getExternalStorageDirectory());
String pickerTitle = getString(R.string.pubkey_list_pick);
// Try to use OpenIntent's file browser to pick a file
Intent intent = new Intent(FileManagerIntents.ACTION_PICK_FILE);
intent.setData(sdcard);
intent.putExtra(FileManagerIntents.EXTRA_TITLE, pickerTitle);
intent.putExtra(FileManagerIntents.EXTRA_BUTTON_TEXT, getString(android.R.string.ok));
try {
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
} catch (ActivityNotFoundException e) {
// If OI didn't work, try AndExplorer
intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(sdcard, MIME_TYPE_ANDEXPLORER_FILE);
intent.putExtra(ANDEXPLORER_TITLE, pickerTitle);
try {
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
} catch (ActivityNotFoundException e1) {
pickFileSimple();
}
}
return true;
}
});
return true;
}
protected void handleAddKey(final PubkeyBean pubkey) {
if (pubkey.isEncrypted()) {
final View view = inflater.inflate(R.layout.dia_password, null);
final EditText passwordField = (EditText) view.findViewById(android.R.id.text1);
new AlertDialog.Builder(PubkeyListActivity.this)
.setView(view)
.setPositiveButton(R.string.pubkey_unlock, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
handleAddKey(pubkey, passwordField.getText().toString());
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
} else {
handleAddKey(pubkey, null);
}
}
protected void handleAddKey(PubkeyBean keybean, String password) {
KeyPair pair = null;
if (PubkeyDatabase.KEY_TYPE_IMPORTED.equals(keybean.getType())) {
// load specific key using pem format
try {
pair = PEMDecoder.decode(new String(keybean.getPrivateKey()).toCharArray(), password);
} catch (Exception e) {
String message = getResources().getString(R.string.pubkey_failed_add, keybean.getNickname());
Log.e(TAG, message, e);
Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG).show();
}
} else {
// load using internal generated format
try {
PrivateKey privKey = PubkeyUtils.decodePrivate(keybean.getPrivateKey(), keybean.getType(), password);
PublicKey pubKey = PubkeyUtils.decodePublic(keybean.getPublicKey(), keybean.getType());
Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey));
pair = new KeyPair(pubKey, privKey);
} catch (Exception e) {
String message = getResources().getString(R.string.pubkey_failed_add, keybean.getNickname());
Log.e(TAG, message, e);
Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG).show();
return;
}
}
if (pair == null) {
return;
}
Log.d(TAG, String.format("Unlocked key '%s'", keybean.getNickname()));
// save this key in memory
bound.addKey(keybean, pair, true);
updateList();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Create menu to handle deleting and editing pubkey
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(info.position);
menu.setHeaderTitle(pubkey.getNickname());
// TODO: option load/unload key from in-memory list
// prompt for password as needed for passworded keys
// cant change password or clipboard imported keys
final boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType());
final boolean loaded = bound != null && bound.isKeyLoaded(pubkey.getNickname());
MenuItem load = menu.add(loaded ? R.string.pubkey_memory_unload : R.string.pubkey_memory_load);
load.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if (loaded) {
bound.removeKey(pubkey.getNickname());
updateList();
} else {
handleAddKey(pubkey);
//bound.addKey(nickname, trileadKey);
}
return true;
}
});
onstartToggle = menu.add(R.string.pubkey_load_on_start);
onstartToggle.setEnabled(!pubkey.isEncrypted());
onstartToggle.setCheckable(true);
onstartToggle.setChecked(pubkey.isStartup());
onstartToggle.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// toggle onstart status
pubkey.setStartup(!pubkey.isStartup());
pubkeydb.savePubkey(pubkey);
updateList();
return true;
}
});
MenuItem copyPublicToClipboard = menu.add(R.string.pubkey_copy_public);
copyPublicToClipboard.setEnabled(!imported);
copyPublicToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
try {
PublicKey pk = PubkeyUtils.decodePublic(pubkey.getPublicKey(), pubkey.getType());
String openSSHPubkey = PubkeyUtils.convertToOpenSSHFormat(pk, pubkey.getNickname());
clipboard.setText(openSSHPubkey);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
MenuItem copyPrivateToClipboard = menu.add(R.string.pubkey_copy_private);
copyPrivateToClipboard.setEnabled(!pubkey.isEncrypted() || imported);
copyPrivateToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
try {
String data = null;
if (imported)
data = new String(pubkey.getPrivateKey());
else {
PrivateKey pk = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType());
data = PubkeyUtils.exportPEM(pk, null);
}
clipboard.setText(data);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
MenuItem changePassword = menu.add(R.string.pubkey_change_password);
changePassword.setEnabled(!imported);
changePassword.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final View changePasswordView = inflater.inflate(R.layout.dia_changepassword, null, false);
((TableRow) changePasswordView.findViewById(R.id.old_password_prompt))
.setVisibility(pubkey.isEncrypted() ? View.VISIBLE : View.GONE);
new AlertDialog.Builder(PubkeyListActivity.this)
.setView(changePasswordView)
.setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String oldPassword = ((EditText) changePasswordView.findViewById(R.id.old_password)).getText().toString();
String password1 = ((EditText) changePasswordView.findViewById(R.id.password1)).getText().toString();
String password2 = ((EditText) changePasswordView.findViewById(R.id.password2)).getText().toString();
if (!password1.equals(password2)) {
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_passwords_do_not_match_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
return;
}
try {
if (!pubkey.changePassword(oldPassword, password1))
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_wrong_password_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
else {
pubkeydb.savePubkey(pubkey);
updateList();
}
} catch (Exception e) {
Log.e(TAG, "Could not change private key password", e);
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_key_corrupted_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
}
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
confirmUse = menu.add(R.string.pubkey_confirm_use);
confirmUse.setCheckable(true);
confirmUse.setChecked(pubkey.isConfirmUse());
confirmUse.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// toggle confirm use
pubkey.setConfirmUse(!pubkey.isConfirmUse());
pubkeydb.savePubkey(pubkey);
updateList();
return true;
}
});
MenuItem delete = menu.add(R.string.pubkey_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(getString(R.string.delete_message, pubkey.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// dont forget to remove from in-memory
if (loaded)
bound.removeKey(pubkey.getNickname());
// delete from backend database and update gui
pubkeydb.deletePubkey(pubkey);
updateList();
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
protected void updateList() {
if (pubkeydb == null) return;
pubkeys = pubkeydb.allPubkeys();
PubkeyAdapter adapter = new PubkeyAdapter(this, pubkeys);
this.setListAdapter(adapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && intent != null) {
Uri uri = intent.getData();
try {
if (uri != null) {
readKeyFromFile(new File(URI.create(uri.toString())));
} else {
String filename = intent.getDataString();
if (filename != null)
readKeyFromFile(new File(URI.create(filename)));
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Couldn't read from picked file", e);
}
}
break;
}
}
/**
* @param name
*/
private void readKeyFromFile(File file) {
PubkeyBean pubkey = new PubkeyBean();
// find the exact file selected
pubkey.setNickname(file.getName());
if (file.length() > MAX_KEYFILE_SIZE) {
Toast.makeText(PubkeyListActivity.this,
R.string.pubkey_import_parse_problem,
Toast.LENGTH_LONG).show();
return;
}
// parse the actual key once to check if its encrypted
// then save original file contents into our database
try {
byte[] raw = readRaw(file);
String data = new String(raw);
if (data.startsWith(PubkeyUtils.PKCS8_START)) {
int start = data.indexOf(PubkeyUtils.PKCS8_START) + PubkeyUtils.PKCS8_START.length();
int end = data.indexOf(PubkeyUtils.PKCS8_END);
if (end > start) {
char[] encoded = data.substring(start, end - 1).toCharArray();
Log.d(TAG, "encoded: " + new String(encoded));
byte[] decoded = Base64.decode(encoded);
KeyPair kp = PubkeyUtils.recoverKeyPair(decoded);
pubkey.setType(kp.getPrivate().getAlgorithm());
pubkey.setPrivateKey(kp.getPrivate().getEncoded());
pubkey.setPublicKey(kp.getPublic().getEncoded());
} else {
Log.e(TAG, "Problem parsing PKCS#8 file; corrupt?");
Toast.makeText(PubkeyListActivity.this,
R.string.pubkey_import_parse_problem,
Toast.LENGTH_LONG).show();
}
} else {
PEMStructure struct = PEMDecoder.parsePEM(new String(raw).toCharArray());
pubkey.setEncrypted(PEMDecoder.isPEMEncrypted(struct));
pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
pubkey.setPrivateKey(raw);
}
// write new value into database
if (pubkeydb == null)
pubkeydb = PubkeyDatabase.get(this);
pubkeydb.savePubkey(pubkey);
updateList();
} catch (Exception e) {
Log.e(TAG, "Problem parsing imported private key", e);
Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show();
}
}
/**
*
*/
private void pickFileSimple() {
// build list of all files in sdcard root
final File sdcard = Environment.getExternalStorageDirectory();
Log.d(TAG, sdcard.toString());
// Don't show a dialog if the SD card is completely absent.
final String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)
&& !Environment.MEDIA_MOUNTED.equals(state)) {
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_sdcard_absent)
.setNegativeButton(android.R.string.cancel, null).create().show();
return;
}
List<String> names = new LinkedList<String>();
{
File[] files = sdcard.listFiles();
if (files != null) {
for (File file : sdcard.listFiles()) {
if (file.isDirectory()) continue;
names.add(file.getName());
}
}
}
Collections.sort(names);
final String[] namesList = names.toArray(new String[] {});
Log.d(TAG, names.toString());
// prompt user to select any file from the sdcard root
new AlertDialog.Builder(PubkeyListActivity.this)
.setTitle(R.string.pubkey_list_pick)
.setItems(namesList, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String name = namesList[arg1];
readKeyFromFile(new File(sdcard, name));
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
}
class PubkeyAdapter extends ArrayAdapter<PubkeyBean> {
private List<PubkeyBean> pubkeys;
class ViewHolder {
public TextView nickname;
public TextView caption;
public ImageView icon;
}
public PubkeyAdapter(Context context, List<PubkeyBean> pubkeys) {
super(context, R.layout.item_pubkey, pubkeys);
this.pubkeys = pubkeys;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_pubkey, null, false);
holder = new ViewHolder();
holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
holder.icon = (ImageView) convertView.findViewById(android.R.id.icon1);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
PubkeyBean pubkey = pubkeys.get(position);
holder.nickname.setText(pubkey.getNickname());
boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType());
if (imported) {
try {
PEMStructure struct = PEMDecoder.parsePEM(new String(pubkey.getPrivateKey()).toCharArray());
String type = (struct.pemType == PEMDecoder.PEM_RSA_PRIVATE_KEY) ? "RSA" : "DSA";
holder.caption.setText(String.format("%s unknown-bit", type));
} catch (IOException e) {
Log.e(TAG, "Error decoding IMPORTED public key at " + pubkey.getId(), e);
}
} else {
try {
holder.caption.setText(pubkey.getDescription());
} catch (Exception e) {
Log.e(TAG, "Error decoding public key at " + pubkey.getId(), e);
holder.caption.setText(R.string.pubkey_unknown_format);
}
}
if (bound == null) {
holder.icon.setVisibility(View.GONE);
} else {
holder.icon.setVisibility(View.VISIBLE);
if (bound.isKeyLoaded(pubkey.getNickname()))
holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
else
holder.icon.setImageState(new int[] { }, true);
}
return convertView;
}
}
}
| Update pubkey list in onStart instead of onCreate
| app/src/main/java/org/connectbot/PubkeyListActivity.java | Update pubkey list in onStart instead of onCreate | <ide><path>pp/src/main/java/org/connectbot/PubkeyListActivity.java
<ide>
<ide> bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
<ide>
<del> if (pubkeydb == null)
<del> pubkeydb = PubkeyDatabase.get(this);
<add> pubkeydb = PubkeyDatabase.get(this);
<add> updateList();
<ide> }
<ide>
<ide> @Override
<ide> this.setTitle(String.format("%s: %s",
<ide> getResources().getText(R.string.app_name),
<ide> getResources().getText(R.string.title_pubkey_list)));
<del>
<del> // connect with hosts database and populate list
<del> pubkeydb = PubkeyDatabase.get(this);
<del>
<del> updateList();
<ide>
<ide> registerForContextMenu(getListView());
<ide>
<ide> }
<ide>
<ide> // write new value into database
<del> if (pubkeydb == null)
<del> pubkeydb = PubkeyDatabase.get(this);
<add> pubkeydb = PubkeyDatabase.get(this);
<ide> pubkeydb.savePubkey(pubkey);
<ide>
<ide> updateList(); |
|
Java | apache-2.0 | 1d47acc429cc00ac1e30c6baf4e39b668139f91a | 0 | twogee/ant-ivy,apache/ant-ivy,jaikiran/ant-ivy,twogee/ant-ivy,twogee/ant-ivy,apache/ant-ivy,apache/ant-ivy,jaikiran/ant-ivy,apache/ant-ivy,jaikiran/ant-ivy,sbt/ivy,jaikiran/ant-ivy,sbt/ivy,twogee/ant-ivy | /*
* 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.ivy.ant;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.Properties;
import org.apache.ivy.Ivy;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.core.settings.IvyVariableContainer;
import org.apache.ivy.util.Message;
import org.apache.ivy.util.url.CredentialsStore;
import org.apache.ivy.util.url.URLHandler;
import org.apache.ivy.util.url.URLHandlerDispatcher;
import org.apache.ivy.util.url.URLHandlerRegistry;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.DataType;
public class IvyAntSettings extends DataType {
public static class Credentials {
private String realm;
private String host;
private String username;
private String passwd;
public String getPasswd() {
return this.passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getRealm() {
return this.realm;
}
public void setRealm(String realm) {
this.realm = format(realm);
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = format(host);
}
public String getUsername() {
return this.username;
}
public void setUsername(String userName) {
this.username = format(userName);
}
}
private Ivy ivyEngine = null;
private File file = null;
private URL url = null;
private String realm = null;
private String host = null;
private String userName = null;
private String passwd = null;
private String id = null;
/**
* Returns the default ivy settings of this classloader. If it doesn't exist yet, a new one is
* created using the given project to back the VariableContainer.
*
* @param project TODO add text.
* @return An IvySetting instance.
*/
public static IvyAntSettings getDefaultInstance(Project project) {
Object defaultInstanceObj = project.getReference("ivy.instance");
if (defaultInstanceObj != null
&& defaultInstanceObj.getClass().getClassLoader() != IvyAntSettings.class
.getClassLoader()) {
Message.warn("ivy.instance reference an ivy:settings defined in an other classloader. "
+ "An new default one will be used in this project.");
defaultInstanceObj = null;
}
if (defaultInstanceObj != null && !(defaultInstanceObj instanceof IvyAntSettings)) {
throw new BuildException("ivy.instance reference a "
+ defaultInstanceObj.getClass().getName()
+ " an not an IvyAntSettings. Please don't use this reference id ()");
}
if (defaultInstanceObj == null) {
Message.info("No ivy:settings found for the default reference 'ivy.instance'. "
+ "A default instance will be used");
IvyAntSettings defaultInstance = new IvyAntSettings();
defaultInstance.setProject(project);
defaultInstance.registerAsDefault();
return defaultInstance;
} else {
return (IvyAntSettings) defaultInstanceObj;
}
}
protected void registerAsDefault() {
getProject().addReference("ivy.instance", this);
}
public File getFile() {
return file;
}
public URL getUrl() {
return url;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String aPasswd) {
passwd = aPasswd;
}
public String getRealm() {
return realm;
}
public void setRealm(String aRealm) {
realm = format(aRealm);
}
public String getHost() {
return host;
}
public void setHost(String aHost) {
host = format(aHost);
}
public String getUsername() {
return userName;
}
public void setUsername(String aUserName) {
userName = format(aUserName);
}
private static String format(String str) {
return str == null ? str : (str.trim().length() == 0 ? null : str.trim());
}
public void addConfiguredCredentials(Credentials c) {
CredentialsStore.INSTANCE.addCredentials(c.getRealm(), c.getHost(), c.getUsername(), c
.getPasswd());
}
public void setFile(File file) {
this.file = file;
}
public void setUrl(String confUrl) throws MalformedURLException {
this.url = new URL(confUrl);
}
/*
* This is usually not necessary to define a reference in Ant, but it's the only
* way to know the id of the settings, which we use to set ant properties.
*/
public void setId(String id) {
this.id = id;
}
/*
* public void execute() throws BuildException {
* ensureMessageInitialised();
* if (getId()==null) {
* log("No id specified for the ivy:settings, set the instance as the default one",
* Project.MSG_DEBUG); getProject().addReference("ivy.instance", this); } else {
* getProject().addReference(id, this); } }
*/
/**
* Return the configured Ivy instance.
* @return Returns the configured Ivy instance.
*/
public Ivy getConfiguredIvyInstance() {
if (ivyEngine == null) {
ivyEngine = createIvyEngine();
}
return ivyEngine;
}
private Ivy createIvyEngine() {
IvyAntVariableContainer ivyAntVariableContainer = new IvyAntVariableContainer(getProject());
IvySettings settings = new IvySettings(ivyAntVariableContainer);
// NB: It is already done in the ivy.configure, but it is required for
// defineDefaultSettingFile (that should be done before the ivy.configure
settings.addAllVariables(getDefaultProperties(), false);
Ivy ivy = Ivy.newInstance(settings);
if (file == null && url == null) {
defineDefaultSettingFile(ivyAntVariableContainer);
}
try {
configureURLHandler();
if (file != null) {
if (!file.exists()) {
throw new BuildException("settings file does not exist: " + file);
}
ivy.configure(file);
} else {
if (url == null) {
throw new AssertionError(
"ivy setting should have either a file, either an url,"
+ " and if not defineDefaultSettingFile must set it.");
}
ivy.configure(url);
}
ivyAntVariableContainer.updateProject(id);
} catch (ParseException e) {
throw new BuildException("impossible to configure ivy:settings with given "
+ (file != null ? "file: " + file : "url :" + url) + " :" + e, e);
} catch (IOException e) {
throw new BuildException("impossible to configure ivy:settings with given "
+ (file != null ? "file: " + file : "url :" + url) + " :" + e, e);
}
return ivy;
}
protected Properties getDefaultProperties() {
URL url = IvySettings.getDefaultPropertiesURL();
// this is copy of loadURL code from ant Property task (not available in 1.5.1)
Properties props = new Properties();
Message.verbose("Loading " + url);
try {
InputStream is = url.openStream();
try {
props.load(is);
} finally {
if (is != null) {
is.close();
}
}
} catch (IOException ex) {
throw new BuildException(ex);
}
return props;
}
/**
* Set _file or _url to its default value
*
* @param variableContainer
*/
private void defineDefaultSettingFile(IvyVariableContainer variableContainer) {
String settingsFileName = variableContainer.getVariable("ivy.conf.file");
if (settingsFileName != null) {
Message.deprecated("'ivy.conf.file' is deprecated, use 'ivy.settings.file' instead");
} else {
settingsFileName = variableContainer.getVariable("ivy.settings.file");
}
File[] settingsLocations = new File[] {
new File(getProject().getBaseDir(), settingsFileName),
new File(getProject().getBaseDir(), "ivyconf.xml"), new File(settingsFileName),
new File("ivyconf.xml") };
for (int i = 0; i < settingsLocations.length; i++) {
file = settingsLocations[i];
Message.verbose("searching settings file: trying " + file);
if (file.exists()) {
break;
}
}
if (!file.exists()) {
if (Boolean.valueOf(getProject().getProperty("ivy.14.compatible")).booleanValue()) {
Message.info("no settings file found, using Ivy 1.4 default...");
file = null;
url = IvySettings.getDefault14SettingsURL();
} else {
Message.info("no settings file found, using default...");
file = null;
url = IvySettings.getDefaultSettingsURL();
}
}
}
private void configureURLHandler() {
// TODO : the credentialStore should also be scoped
CredentialsStore.INSTANCE.addCredentials(getRealm(), getHost(), getUsername(), getPasswd());
URLHandlerDispatcher dispatcher = new URLHandlerDispatcher();
URLHandler httpHandler = URLHandlerRegistry.getHttp();
dispatcher.setDownloader("http", httpHandler);
dispatcher.setDownloader("https", httpHandler);
URLHandlerRegistry.setDefault(dispatcher);
}
}
| src/java/org/apache/ivy/ant/IvyAntSettings.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.ivy.ant;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.Properties;
import org.apache.ivy.Ivy;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.core.settings.IvyVariableContainer;
import org.apache.ivy.util.Message;
import org.apache.ivy.util.url.CredentialsStore;
import org.apache.ivy.util.url.URLHandler;
import org.apache.ivy.util.url.URLHandlerDispatcher;
import org.apache.ivy.util.url.URLHandlerRegistry;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.DataType;
public class IvyAntSettings extends DataType {
public static class Credentials {
private String realm;
private String host;
private String username;
private String passwd;
public String getPasswd() {
return this.passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getRealm() {
return this.realm;
}
public void setRealm(String realm) {
this.realm = format(realm);
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = format(host);
}
public String getUsername() {
return this.username;
}
public void setUsername(String userName) {
this.username = format(userName);
}
}
private Ivy ivyEngine = null;
private File file = null;
private URL url = null;
private String realm = null;
private String host = null;
private String userName = null;
private String passwd = null;
private String id = null;
/**
* Returns the default ivy settings of this classloader. If it doesn't exist yet, a new one is
* created using the given project to back the VariableContainer.
*
* @param project TODO add text.
* @return An IvySetting instance.
*/
public static IvyAntSettings getDefaultInstance(Project project) {
Object defaultInstanceObj = project.getReference("ivy.instance");
if (defaultInstanceObj != null
&& defaultInstanceObj.getClass().getClassLoader() != IvyAntSettings.class
.getClassLoader()) {
Message.warn("ivy.instance reference an ivy:settings defined in an other classloader. "
+ "An new default one will be used in this project.");
defaultInstanceObj = null;
}
if (defaultInstanceObj != null && !(defaultInstanceObj instanceof IvyAntSettings)) {
throw new BuildException("ivy.instance reference a "
+ defaultInstanceObj.getClass().getName()
+ " an not an IvyAntSettings. Please don't use this reference id ()");
}
if (defaultInstanceObj == null) {
Message.info("No ivy:settings found for the default reference 'ivy.instance'. "
+ "A default instance will be used");
IvyAntSettings defaultInstance = new IvyAntSettings();
defaultInstance.setProject(project);
defaultInstance.registerAsDefault();
return defaultInstance;
} else {
return (IvyAntSettings) defaultInstanceObj;
}
}
protected void registerAsDefault() {
getProject().addReference("ivy.instance", this);
}
public File getFile() {
return file;
}
public URL getUrl() {
return url;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String aPasswd) {
passwd = aPasswd;
}
public String getRealm() {
return realm;
}
public void setRealm(String aRealm) {
realm = format(aRealm);
}
public String getHost() {
return host;
}
public void setHost(String aHost) {
host = format(aHost);
}
public String getUsername() {
return userName;
}
public void setUsername(String aUserName) {
userName = format(aUserName);
}
private static String format(String str) {
return str == null ? str : (str.trim().length() == 0 ? null : str.trim());
}
public void addConfiguredCredentials(Credentials c) {
CredentialsStore.INSTANCE.addCredentials(c.getRealm(), c.getHost(), c.getUsername(), c
.getPasswd());
}
public void setFile(File file) {
this.file = file;
}
public void setUrl(String confUrl) throws MalformedURLException {
this.url = new URL(confUrl);
}
/*
* This is usually not necessary to define a reference in Ant, but it's the only
* way to know the id of the settings, which we use to set ant properties.
*/
public void setId(String id) {
this.id = id;
}
/*
* public void execute() throws BuildException {
* ensureMessageInitialised();
* if (getId()==null) {
* log("No id specified for the ivy:settings, set the instance as the default one",
* Project.MSG_DEBUG); getProject().addReference("ivy.instance", this); } else {
* getProject().addReference(id, this); } }
*/
/**
* Return the configured Ivy instance.
* @return Returns the configured Ivy instance.
*/
public Ivy getConfiguredIvyInstance() {
if (ivyEngine == null) {
ivyEngine = createIvyEngine();
}
return ivyEngine;
}
private Ivy createIvyEngine() {
IvyAntVariableContainer ivyAntVariableContainer = new IvyAntVariableContainer(getProject());
IvySettings settings = new IvySettings(ivyAntVariableContainer);
// NB: It is alrady done in the ivy.configure, but it is required for
// defineDefaultSettingFile (that should be done before the ivy.configure
settings.addAllVariables(getDefaultProperties(), false);
Ivy ivy = Ivy.newInstance(settings);
if (file == null && url == null) {
defineDefaultSettingFile(ivyAntVariableContainer);
}
try {
configureURLHandler();
if (file != null) {
if (!file.exists()) {
throw new BuildException("settings file does not exist: " + file);
}
ivy.configure(file);
} else {
if (url == null) {
throw new AssertionError(
"ivy setting should have either a file, either an url,"
+ " and if not defineDefaultSettingFile must set it.");
}
ivy.configure(url);
}
ivyAntVariableContainer.updateProject(id);
} catch (ParseException e) {
throw new BuildException("impossible to configure ivy:settings with given "
+ (file != null ? "file: " + file : "url :" + url) + " :" + e, e);
} catch (IOException e) {
throw new BuildException("impossible to configure ivy:settings with given "
+ (file != null ? "file: " + file : "url :" + url) + " :" + e, e);
}
return ivy;
}
protected Properties getDefaultProperties() {
URL url = IvySettings.getDefaultPropertiesURL();
// this is copy of loadURL code from ant Property task (not available in 1.5.1)
Properties props = new Properties();
Message.verbose("Loading " + url);
try {
InputStream is = url.openStream();
try {
props.load(is);
} finally {
if (is != null) {
is.close();
}
}
} catch (IOException ex) {
throw new BuildException(ex);
}
return props;
}
/**
* Set _file or _url to its default value
*
* @param variableContainer
*/
private void defineDefaultSettingFile(IvyVariableContainer variableContainer) {
String settingsFileName = variableContainer.getVariable("ivy.conf.file");
if (settingsFileName != null) {
Message.deprecated("'ivy.conf.file' is deprecated, use 'ivy.settings.file' instead");
} else {
settingsFileName = variableContainer.getVariable("ivy.settings.file");
}
File[] settingsLocations = new File[] {
new File(getProject().getBaseDir(), settingsFileName),
new File(getProject().getBaseDir(), "ivyconf.xml"), new File(settingsFileName),
new File("ivyconf.xml") };
for (int i = 0; i < settingsLocations.length; i++) {
file = settingsLocations[i];
Message.verbose("searching settings file: trying " + file);
if (file.exists()) {
break;
}
}
if (!file.exists()) {
if (Boolean.valueOf(getProject().getProperty("ivy.14.compatible")).booleanValue()) {
Message.info("no settings file found, using Ivy 1.4 default...");
file = null;
url = IvySettings.getDefault14SettingsURL();
} else {
Message.info("no settings file found, using default...");
file = null;
url = IvySettings.getDefaultSettingsURL();
}
}
}
private void configureURLHandler() {
// TODO : the credentialStore should also be scoped
CredentialsStore.INSTANCE.addCredentials(getRealm(), getHost(), getUsername(), getPasswd());
URLHandlerDispatcher dispatcher = new URLHandlerDispatcher();
URLHandler httpHandler = URLHandlerRegistry.getHttp();
dispatcher.setDownloader("http", httpHandler);
dispatcher.setDownloader("https", httpHandler);
URLHandlerRegistry.setDefault(dispatcher);
}
}
| Fixed typo
git-svn-id: 4757cb15a840ff1a58eff8144c368923fad328dd@577047 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/ivy/ant/IvyAntSettings.java | Fixed typo | <ide><path>rc/java/org/apache/ivy/ant/IvyAntSettings.java
<ide> IvyAntVariableContainer ivyAntVariableContainer = new IvyAntVariableContainer(getProject());
<ide>
<ide> IvySettings settings = new IvySettings(ivyAntVariableContainer);
<del> // NB: It is alrady done in the ivy.configure, but it is required for
<add> // NB: It is already done in the ivy.configure, but it is required for
<ide> // defineDefaultSettingFile (that should be done before the ivy.configure
<ide> settings.addAllVariables(getDefaultProperties(), false);
<ide> |
|
Java | apache-2.0 | cfcb1666d5eaf33da846aaf0d391d9560552298f | 0 | BasinMC/Basin,BasinMC/Basin | /*
* Copyright 2016 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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.basinmc.sink.service;
import com.google.common.collect.MapMaker;
import org.basinmc.faucet.observable.AbstractObservableProperty;
import org.basinmc.faucet.service.ServiceManager;
import org.basinmc.faucet.service.ServiceReference;
import org.basinmc.faucet.service.ServiceRegistration;
import org.basinmc.faucet.util.Priority;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
/**
* TODO: Add leak detection to this implementation.
*
* TODO: This implementation utilizes weak references in order to store its data securely!
*
* TODO: This allows people to create custom versions of Server ... intended?!
*
* @author <a href="mailto:[email protected]">Johannes Donath</a>
*/
@ThreadSafe
public class SinkServiceManager implements ServiceManager {
private final Map<Class<?>, Set> registrationMap; // Using raw types is a bit ugly but Java does not like this sort of thing
private final Map<SimpleServiceRegistration<?>, Object> proxyMap;
private final Map<SimpleServiceRegistration<?>, SimpleServiceReference<?>> referenceMap;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public SinkServiceManager() {
this.registrationMap = (new MapMaker())
.weakKeys()
.makeMap();
this.proxyMap = (new MapMaker())
.weakKeys()
.makeMap();
this.referenceMap = (new MapMaker())
.weakKeys()
.weakValues()
.makeMap();
}
/**
* Creates a new proxy wrapper around an implementation in order to
*
* @param interfaceType an interface type.
* @param implementation an implementation.
* @param <I> an interface type.
* @return a proxy instance.
*/
@Nonnull
@SuppressWarnings("unchecked")
public static <I> I createWeakProxy(@Nonnull Class<I> interfaceType, @Nonnull I implementation) {
// TODO: This method is great but doesn't cover abstract classes
// TODO: For now all users are forced to provide interfaces (which is a sane concept anyways)
if (!interfaceType.isInterface()) {
throw new IllegalArgumentException("Service base type is required to be an interface");
}
return (I) Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class[]{interfaceType}, new ServiceProxyInvocationHandler<>(implementation));
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
@SuppressWarnings("unchecked")
public <T> Optional<ServiceReference<T>> getReference(@Nonnull Class<T> serviceType) {
this.lock.readLock().lock();
try {
return Optional.ofNullable((ServiceReference<T>) this.registrationMap.get(serviceType));
} finally {
this.lock.readLock().unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public void inject(@Nonnull Object object) {
// TODO
throw new UnsupportedOperationException("TODO");
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> T inject(@Nonnull Class<T> type) throws Throwable {
// TODO
throw new UnsupportedOperationException("TODO");
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
@SuppressWarnings("unchecked")
public <I> ServiceRegistration<I> register(@Nonnull Class<I> interfaceType, @Nonnull I implementation, @Nonnull Priority priority) {
this.lock.writeLock().lock();
try {
Set<SimpleServiceRegistration<I>> registrations = this.getRegistrationSet(interfaceType);
SimpleServiceRegistration<I> registration = new SimpleServiceRegistration<>(interfaceType, priority);
SimpleServiceRegistration<I> highestPriorityRegistration = registrations.stream().sorted((a, b) -> a.getPriority().compareTo(b.getPriority())).findFirst().orElse(null);
if (highestPriorityRegistration == registration) {
for (SimpleServiceRegistration<I> oldRegistration : registrations) {
SimpleServiceReference<I> reference = (SimpleServiceReference<I>) this.referenceMap.get(oldRegistration);
this.referenceMap.remove(oldRegistration);
this.referenceMap.put(registration, reference);
}
}
registrations.add(registration);
registration.set(implementation);
return registration;
} finally {
this.lock.writeLock().unlock();
}
}
/**
* Retrieves the registration set for a specific interface type.
*
* @param interfaceType an interface type.
* @param <I> an interface type.
* @return a set of registrations.
*/
@Nonnull
@SuppressWarnings("unchecked")
private <I> Set<SimpleServiceRegistration<I>> getRegistrationSet(@Nonnull Class<I> interfaceType) {
if (this.registrationMap.containsKey(interfaceType)) {
return (Set<SimpleServiceRegistration<I>>) this.registrationMap.get(interfaceType);
}
Set<SimpleServiceRegistration<I>> registrations = Collections.newSetFromMap(new WeakHashMap<SimpleServiceRegistration<I>, Boolean>());
this.registrationMap.put(interfaceType, registrations);
return registrations;
}
/**
* Pushes an update to all known service references.
* @param registration a registration.
* @param value a new implementation.
* @param <I> an interface type.
*/
@SuppressWarnings("unchecked")
private <I> void pushUpdate(@Nonnull SimpleServiceRegistration<I> registration, @Nullable I value) {
this.lock.writeLock().lock();
try {
if (value == null) {
return;
}
final I proxy = createWeakProxy(registration.interfaceType, value);
this.proxyMap.put(registration, proxy);
Optional.ofNullable(this.referenceMap.get(registration)).ifPresent((r) -> ((SimpleServiceReference<I>) r).pushUpdate(proxy));
} finally {
this.lock.writeLock().unlock();
}
}
/**
* Provides a simple invocation handler for handling interface proxies.
*
* @param <I> a reference type.
*/
private static class ServiceProxyInvocationHandler<I> implements InvocationHandler {
private final WeakReference<I> implementation;
public ServiceProxyInvocationHandler(@Nonnull I implementation) {
this.implementation = new WeakReference<>(implementation);
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public Object invoke(@Nonnull Object proxy, @Nonnull Method method, @Nonnull Object[] args) throws Throwable {
I object = this.implementation.get();
if (object == null) {
throw new IllegalStateException("Invalid Proxy Reference - Please fix your code");
}
// TODO: This will just let invocation exceptions bubble up ... We might want to switch that out
method.setAccessible(true);
return method.invoke(object, args);
}
}
/**
* Provides a simple service reference.
*
* @param <I> a service type.
*/
@ThreadSafe
private class SimpleServiceReference<I> extends AbstractObservableProperty<I> implements ServiceReference<I> {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private I implementation;
/**
* {@inheritDoc}
*/
@Override
public I get() {
this.lock.readLock().lock();
try {
return this.implementation;
} finally {
this.lock.readLock().unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean set(I value) {
return false;
}
/**
* Pushes a new update into the reference.
*
* @param implementation an implementation.
*/
protected void pushUpdate(@Nonnull I implementation) {
this.lock.writeLock().lock();
try {
this.callObservers(implementation);
this.implementation = implementation;
} finally {
this.lock.writeLock().unlock();
}
}
}
/**
* Provides a simple interface for updating and removing service registrations.
*
* @param <I> a service type.
*/
@ThreadSafe
private class SimpleServiceRegistration<I> extends AbstractObservableProperty<I> implements ServiceRegistration<I> {
private final Class<I> interfaceType;
private final Priority priority;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private I implementation;
public SimpleServiceRegistration(@Nonnull Class<I> interfaceType, @Nonnull Priority priority) {
this.interfaceType = interfaceType;
this.priority = priority;
}
/**
* {@inheritDoc}
*/
@Override
public void unregister() {
SinkServiceManager.this.lock.writeLock().lock();
try {
if (this.set(null)) {
Set<SimpleServiceRegistration<I>> registrations = SinkServiceManager.this.getRegistrationSet(this.interfaceType);
registrations.remove(this);
SinkServiceManager.this.proxyMap.remove(this);
}
} finally {
SinkServiceManager.this.lock.writeLock().unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public I get() {
this.lock.readLock().lock();
try {
return this.implementation;
} finally {
this.lock.readLock().unlock();
}
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public Priority getPriority() {
return this.priority;
}
/**
* {@inheritDoc}
*/
@Override
public boolean set(I value) {
if (value == null) {
throw new NullPointerException("Service value cannot be null");
}
if (!this.callObservers(value)) {
return false;
}
this.lock.writeLock().lock();
try {
SinkServiceManager.this.pushUpdate(this, value);
this.implementation = value;
return true;
} finally {
this.lock.writeLock().unlock();
}
}
}
}
| src/main/java/org/basinmc/sink/service/SinkServiceManager.java | /*
* Copyright 2016 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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.basinmc.sink.service;
import com.google.common.collect.MapMaker;
import org.basinmc.faucet.observable.AbstractObservableProperty;
import org.basinmc.faucet.service.ServiceManager;
import org.basinmc.faucet.service.ServiceReference;
import org.basinmc.faucet.service.ServiceRegistration;
import org.basinmc.faucet.util.Priority;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
/**
* TODO: Add leak detection to this implementation.
*
* TODO: This implementation utilizes weak references in order to store its data securely!
*
* TODO: This allows people to create custom versions of Server ... intended?!
*
* @author <a href="mailto:[email protected]">Johannes Donath</a>
*/
@ThreadSafe
public class SinkServiceManager implements ServiceManager {
private final Map<Class<?>, Set> registrationMap; // Using raw types is a bit ugly but Java does not like this sort of thing
private final Map<SimpleServiceRegistration<?>, Object> proxyMap;
private final Map<SimpleServiceRegistration<?>, SimpleServiceReference<?>> referenceMap;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public SinkServiceManager() {
this.registrationMap = (new MapMaker())
.weakKeys()
.makeMap();
this.proxyMap = (new MapMaker())
.weakKeys()
.makeMap();
this.referenceMap = (new MapMaker())
.weakKeys()
.weakValues()
.makeMap();
}
/**
* Creates a new proxy wrapper around an implementation in order to
*
* @param interfaceType an interface type.
* @param implementation an implementation.
* @param <I> an interface type.
* @return a proxy instance.
*/
@Nonnull
@SuppressWarnings("unchecked")
private static <I> I createWeakProxy(@Nonnull Class<I> interfaceType, @Nonnull I implementation) {
// TODO: This method is great but doesn't cover abstract classes
// TODO: For now all users are forced to provide interfaces (which is a sane concept anyways)
if (!interfaceType.isInterface()) {
throw new IllegalArgumentException("Service base type is required to be an interface");
}
return (I) Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class[]{interfaceType}, new ServiceProxyInvocationHandler<>(implementation));
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
@SuppressWarnings("unchecked")
public <T> Optional<ServiceReference<T>> getReference(@Nonnull Class<T> serviceType) {
this.lock.readLock().lock();
try {
return Optional.ofNullable((ServiceReference<T>) this.registrationMap.get(serviceType));
} finally {
this.lock.readLock().unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public void inject(@Nonnull Object object) {
// TODO
throw new UnsupportedOperationException("TODO");
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public <T> T inject(@Nonnull Class<T> type) throws Throwable {
// TODO
throw new UnsupportedOperationException("TODO");
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
@SuppressWarnings("unchecked")
public <I> ServiceRegistration<I> register(@Nonnull Class<I> interfaceType, @Nonnull I implementation, @Nonnull Priority priority) {
this.lock.writeLock().lock();
try {
Set<SimpleServiceRegistration<I>> registrations = this.getRegistrationSet(interfaceType);
SimpleServiceRegistration<I> registration = new SimpleServiceRegistration<>(interfaceType, priority);
SimpleServiceRegistration<I> highestPriorityRegistration = registrations.stream().sorted((a, b) -> a.getPriority().compareTo(b.getPriority())).findFirst().orElse(null);
if (highestPriorityRegistration == registration) {
for (SimpleServiceRegistration<I> oldRegistration : registrations) {
SimpleServiceReference<I> reference = (SimpleServiceReference<I>) this.referenceMap.get(oldRegistration);
this.referenceMap.remove(oldRegistration);
this.referenceMap.put(registration, reference);
}
}
registrations.add(registration);
registration.set(implementation);
return registration;
} finally {
this.lock.writeLock().unlock();
}
}
/**
* Retrieves the registration set for a specific interface type.
*
* @param interfaceType an interface type.
* @param <I> an interface type.
* @return a set of registrations.
*/
@Nonnull
@SuppressWarnings("unchecked")
private <I> Set<SimpleServiceRegistration<I>> getRegistrationSet(@Nonnull Class<I> interfaceType) {
if (this.registrationMap.containsKey(interfaceType)) {
return (Set<SimpleServiceRegistration<I>>) this.registrationMap.get(interfaceType);
}
Set<SimpleServiceRegistration<I>> registrations = Collections.newSetFromMap(new WeakHashMap<SimpleServiceRegistration<I>, Boolean>());
this.registrationMap.put(interfaceType, registrations);
return registrations;
}
/**
* Pushes an update to all known service references.
* @param registration a registration.
* @param value a new implementation.
* @param <I> an interface type.
*/
@SuppressWarnings("unchecked")
private <I> void pushUpdate(@Nonnull SimpleServiceRegistration<I> registration, @Nullable I value) {
this.lock.writeLock().lock();
try {
if (value == null) {
return;
}
final I proxy = createWeakProxy(registration.interfaceType, value);
this.proxyMap.put(registration, proxy);
Optional.ofNullable(this.referenceMap.get(registration)).ifPresent((r) -> ((SimpleServiceReference<I>) r).pushUpdate(proxy));
} finally {
this.lock.writeLock().unlock();
}
}
/**
* Provides a simple invocation handler for handling interface proxies.
*
* @param <I> a reference type.
*/
private static class ServiceProxyInvocationHandler<I> implements InvocationHandler {
private final WeakReference<I> implementation;
public ServiceProxyInvocationHandler(@Nonnull I implementation) {
this.implementation = new WeakReference<>(implementation);
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public Object invoke(@Nonnull Object proxy, @Nonnull Method method, @Nonnull Object[] args) throws Throwable {
I object = this.implementation.get();
if (object == null) {
throw new IllegalStateException("Invalid Proxy Reference - Please fix your code");
}
// TODO: This will just let invocation exceptions bubble up ... We might want to switch that out
method.setAccessible(true);
return method.invoke(object, args);
}
}
/**
* Provides a simple service reference.
*
* @param <I> a service type.
*/
@ThreadSafe
private class SimpleServiceReference<I> extends AbstractObservableProperty<I> implements ServiceReference<I> {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private I implementation;
/**
* {@inheritDoc}
*/
@Override
public I get() {
this.lock.readLock().lock();
try {
return this.implementation;
} finally {
this.lock.readLock().unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean set(I value) {
return false;
}
/**
* Pushes a new update into the reference.
*
* @param implementation an implementation.
*/
protected void pushUpdate(@Nonnull I implementation) {
this.lock.writeLock().lock();
try {
this.callObservers(implementation);
this.implementation = implementation;
} finally {
this.lock.writeLock().unlock();
}
}
}
/**
* Provides a simple interface for updating and removing service registrations.
*
* @param <I> a service type.
*/
@ThreadSafe
private class SimpleServiceRegistration<I> extends AbstractObservableProperty<I> implements ServiceRegistration<I> {
private final Class<I> interfaceType;
private final Priority priority;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private I implementation;
public SimpleServiceRegistration(@Nonnull Class<I> interfaceType, @Nonnull Priority priority) {
this.interfaceType = interfaceType;
this.priority = priority;
}
/**
* {@inheritDoc}
*/
@Override
public void unregister() {
SinkServiceManager.this.lock.writeLock().lock();
try {
if (this.set(null)) {
Set<SimpleServiceRegistration<I>> registrations = SinkServiceManager.this.getRegistrationSet(this.interfaceType);
registrations.remove(this);
SinkServiceManager.this.proxyMap.remove(this);
}
} finally {
SinkServiceManager.this.lock.writeLock().unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public I get() {
this.lock.readLock().lock();
try {
return this.implementation;
} finally {
this.lock.readLock().unlock();
}
}
/**
* {@inheritDoc}
*/
@Nonnull
@Override
public Priority getPriority() {
return this.priority;
}
/**
* {@inheritDoc}
*/
@Override
public boolean set(I value) {
if (value == null) {
throw new NullPointerException("Service value cannot be null");
}
if (!this.callObservers(value)) {
return false;
}
this.lock.writeLock().lock();
try {
SinkServiceManager.this.pushUpdate(this, value);
this.implementation = value;
return true;
} finally {
this.lock.writeLock().unlock();
}
}
}
}
| Made proxy capabilities accessible to all implementations in Sink.
| src/main/java/org/basinmc/sink/service/SinkServiceManager.java | Made proxy capabilities accessible to all implementations in Sink. | <ide><path>rc/main/java/org/basinmc/sink/service/SinkServiceManager.java
<ide> */
<ide> @Nonnull
<ide> @SuppressWarnings("unchecked")
<del> private static <I> I createWeakProxy(@Nonnull Class<I> interfaceType, @Nonnull I implementation) {
<add> public static <I> I createWeakProxy(@Nonnull Class<I> interfaceType, @Nonnull I implementation) {
<ide> // TODO: This method is great but doesn't cover abstract classes
<ide> // TODO: For now all users are forced to provide interfaces (which is a sane concept anyways)
<ide> if (!interfaceType.isInterface()) { |
|
Java | lgpl-2.1 | d669b0eadec6a5f4d2a37a7330655854de6a6155 | 0 | exedio/copernica,exedio/copernica,exedio/copernica |
package com.exedio.cope.instrument;
import java.lang.reflect.Modifier;
public class ExampleTest extends InjectorTest
{
public ExampleTest(String name)
{
super(name, "Example.java");
}
protected void setUp() throws Exception
{
super.setUp();
}
protected void tearDown() throws Exception
{
super.tearDown();
}
public void assertInjection()
{
assertText("/*\nSome initial test comment. \n*/\n\npackage// hallo\n com.exedio.cope.instrument");
assertPackage("com.exedio.cope.instrument");
assertText(";\n\nimport java.util.*");
assertImport("java.util.*");
assertText(";\nimport java.text.Format");
assertImport("java.text.Format");
assertText(";\n\n");
assertFileDocComment("/**\n Represents an attribute or association partner of a class.\n Note: type==Model.AMIGOUS means, the attribute cannot be used in OCL due to attribute ambiguities.\n See OCL spec 5.4.1. for details.\n*/");
assertText("\npublic abstract class Example");
assertClass("Example");
assertText(" implements Runnable\n{\n ");
assertAttributeHeader("name", "String", Modifier.PRIVATE);
assertText("private String name;");
assertAttribute("name", null);
assertText("\n ");
assertAttributeHeader("type", "Integer", Modifier.PRIVATE);
assertText("private Integer type=new Integer(5);");
assertAttribute("type", null);
assertText("\n ");
assertAttributeHeader("qualifiers", "Integer[]", Modifier.PRIVATE|Modifier.VOLATILE);
assertText("private volatile Integer[] qualifiers;");
assertAttribute("qualifiers", null);
assertText("\n ");
assertAttributeHeader("hallo", "String", 0);
assertText("String hallo=\"hallo\";");
assertAttribute("hallo", null);
assertText("\n \n ");
assertDocComment("/**TestCommentCommaSeparated123*/");
assertText("\n ");
assertAttributeHeader("commaSeparated1", "int", 0);
//assertText("int commaSeparated1,commaSeparated2=0,commaSeparated3;"); TODO: where is the text of these attributes?
assertAttribute("commaSeparated1", "/**TestCommentCommaSeparated123*/");
assertAttribute("commaSeparated2", "/**TestCommentCommaSeparated123*/");
assertAttribute("commaSeparated3", "/**TestCommentCommaSeparated123*/");
assertText(" \n ");
assertDocComment("/**TestCommentCommaSeparated456*/");
assertText("\n ");
assertAttributeHeader("commaSeparated4", "int", 0);
assertAttribute("commaSeparated4", "/**TestCommentCommaSeparated456*/");
assertAttribute("commaSeparated5", "/**TestCommentCommaSeparated456*/");
assertAttribute("commaSeparated6", "/**TestCommentCommaSeparated456*/");
assertText(" \n\n // these attributes test the ability of the parser\n // to skip more complex (ugly) attribute initializers\n ");
assertAttributeHeader("uglyAttribute1", "String", 0);
assertText("String uglyAttribute1=\"some'Thing{some\\\"Thing;Else\";");
assertAttribute("uglyAttribute1", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute2", "char", 0);
assertText("char uglyAttribute2=';';");
assertAttribute("uglyAttribute2", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute3", "char", 0);
assertText("char uglyAttribute3='{';");
assertAttribute("uglyAttribute3", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute4", "char", 0);
assertText("char uglyAttribute4='\"';");
assertAttribute("uglyAttribute4", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute5", "char", 0);
assertText("char uglyAttribute5='\\\'';");
assertAttribute("uglyAttribute5", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute6", "String[]", 0);
assertText("String[] uglyAttribute6=\n {\n \"some'Thing{some\\\"Thing;Else\", // ugly ; { \" ' comment\n \"some'Thing{some\\\"Thing;Else\"\n };");
assertAttribute("uglyAttribute6", null);
assertText("\n ");
}
}
| instrument/testsrc/com/exedio/cope/instrument/ExampleTest.java |
package com.exedio.cope.instrument;
import java.lang.reflect.Modifier;
public class ExampleTest extends InjectorTest
{
public ExampleTest(String name)
{
super(name, "Example.java");
}
protected void setUp() throws Exception
{
super.setUp();
}
protected void tearDown() throws Exception
{
super.tearDown();
}
public void assertInjection()
{
assertText("/*\nSome initial test comment. \n*/\n\npackage// hallo\n com.exedio.cope.instrument");
assertPackage("com.exedio.cope.instrument");
assertText(";\n\nimport java.util.*");
assertImport("java.util.*");
assertText(";\nimport java.text.Format");
assertImport("java.text.Format");
assertText(";\n\n");
assertFileDocComment("/**\n Represents an attribute or association partner of a class.\n Note: type==Model.AMIGOUS means, the attribute cannot be used in OCL due to attribute ambiguities.\n See OCL spec 5.4.1. for details.\n*/");
assertText("\npublic abstract class Example");
assertClass("Example");
assertText(" implements Runnable\n{\n ");
assertAttributeHeader("name", "String", Modifier.PRIVATE);
assertText("private String name;");
assertAttribute("name", null);
assertText("\n ");
assertAttributeHeader("type", "Integer", Modifier.PRIVATE);
assertText("private Integer type=new Integer(5);");
assertAttribute("type", null);
assertText("\n ");
assertAttributeHeader("qualifiers", "Integer[]", Modifier.PRIVATE|Modifier.VOLATILE);
assertText("private volatile Integer[] qualifiers;");
assertAttribute("qualifiers", null);
assertText("\n ");
assertAttributeHeader("hallo", "String", 0);
assertText("String hallo=\"hallo\";");
assertAttribute("hallo", null);
assertText("\n \n ");
assertDocComment("/**TestCommentCommaSeparated123*/");
assertText("\n ");
assertAttributeHeader("commaSeparated1", "int", 0);
//assertText("int commaSeparated1,commaSeparated2=0,commaSeparated3;"); TODO: where is the text of these attributes?
assertAttribute("commaSeparated1", "/**TestCommentCommaSeparated123*/");
assertAttribute("commaSeparated2", "/**TestCommentCommaSeparated123*/");
assertAttribute("commaSeparated3", "/**TestCommentCommaSeparated123*/");
assertText(" \n ");
assertDocComment("/**TestCommentCommaSeparated456*/");
assertText("\n ");
assertAttributeHeader("commaSeparated4", "int", 0);
assertAttribute("commaSeparated4", "/**TestCommentCommaSeparated456*/");
assertAttribute("commaSeparated5", "/**TestCommentCommaSeparated456*/");
assertAttribute("commaSeparated6", "/**TestCommentCommaSeparated456*/");
assertText(" \n\n // these attributes test the ability of the parser\n // to skip more complex (ugly) attribute initializers\n ");
assertAttributeHeader("uglyAttribute1", "String", 0);
assertText("String uglyAttribute1=\"some'Thing{some\\\"Thing;Else\";");
assertAttribute("uglyAttribute1", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute2", "char", 0);
assertText("char uglyAttribute2=';';");
assertAttribute("uglyAttribute2", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute3", "char", 0);
assertText("char uglyAttribute3='{';");
assertAttribute("uglyAttribute3", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute4", "char", 0);
assertText("char uglyAttribute4='\"';");
assertAttribute("uglyAttribute4", null);
assertText("\n ");
assertAttributeHeader("uglyAttribute5", "char", 0);
assertText("char uglyAttribute5='\\\'';");
assertAttribute("uglyAttribute5", null);
assertText("\n ");
}
}
| uglyAttribute 6
git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@458 e7d4fc99-c606-0410-b9bf-843393a9eab7
| instrument/testsrc/com/exedio/cope/instrument/ExampleTest.java | uglyAttribute 6 | <ide><path>nstrument/testsrc/com/exedio/cope/instrument/ExampleTest.java
<ide> assertText("char uglyAttribute5='\\\'';");
<ide> assertAttribute("uglyAttribute5", null);
<ide> assertText("\n ");
<add>
<add> assertAttributeHeader("uglyAttribute6", "String[]", 0);
<add> assertText("String[] uglyAttribute6=\n {\n \"some'Thing{some\\\"Thing;Else\", // ugly ; { \" ' comment\n \"some'Thing{some\\\"Thing;Else\"\n };");
<add> assertAttribute("uglyAttribute6", null);
<add> assertText("\n ");
<add>
<ide> }
<ide>
<ide> } |
|
Java | lgpl-2.1 | ed3769a7d0cf774b2c75b921722ca04a7775a0ce | 0 | joansmith/orbeon-forms,wesley1001/orbeon-forms,brunobuzzi/orbeon-forms,brunobuzzi/orbeon-forms,wesley1001/orbeon-forms,orbeon/orbeon-forms,brunobuzzi/orbeon-forms,martinluther/orbeon-forms,ajw625/orbeon-forms,tanbo800/orbeon-forms,tanbo800/orbeon-forms,ajw625/orbeon-forms,wesley1001/orbeon-forms,evlist/orbeon-forms,martinluther/orbeon-forms,evlist/orbeon-forms,orbeon/orbeon-forms,ajw625/orbeon-forms,orbeon/orbeon-forms,orbeon/orbeon-forms,wesley1001/orbeon-forms,evlist/orbeon-forms,joansmith/orbeon-forms,brunobuzzi/orbeon-forms,tanbo800/orbeon-forms,martinluther/orbeon-forms,ajw625/orbeon-forms,joansmith/orbeon-forms,tanbo800/orbeon-forms,joansmith/orbeon-forms,evlist/orbeon-forms,martinluther/orbeon-forms,evlist/orbeon-forms | /**
* Copyright (C) 2010 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.xforms;
import org.dom4j.Element;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.util.IndentedLogger;
import org.orbeon.oxf.util.PropertyContext;
import org.orbeon.oxf.util.XPathCache;
import org.orbeon.oxf.xforms.control.XFormsControl;
import org.orbeon.oxf.xforms.control.XFormsControlFactory;
import org.orbeon.oxf.xforms.event.events.XFormsBindingExceptionEvent;
import org.orbeon.oxf.xforms.function.XFormsFunction;
import org.orbeon.oxf.xforms.xbl.XBLBindings;
import org.orbeon.oxf.xforms.xbl.XBLContainer;
import org.orbeon.oxf.xml.dom4j.Dom4jUtils;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.orbeon.saxon.om.Item;
import org.orbeon.saxon.om.NodeInfo;
import org.orbeon.saxon.om.ValueRepresentation;
import java.util.*;
/**
* Handle a stack of XPath evaluation context information. This is used by controls (with one stack rooted at each
* XBLContainer), models, and actions.
*/
public class XFormsContextStack {
private XBLContainer container;
private XFormsContainingDocument containingDocument;
private XFormsFunction.Context functionContext;
private BindingContext parentBindingContext;
// TODO: use ArrayStack (although that is not generic)
private Stack<BindingContext> contextStack = new Stack<BindingContext>();
// Constructor for XBLContainer
public XFormsContextStack(XBLContainer container) {
this.container = container;
this.containingDocument = this.container.getContainingDocument();
this.functionContext = new XFormsFunction.Context(container, this);
}
// Constructor for XFormsActionInterpreter
public XFormsContextStack(XBLContainer container, BindingContext parentBindingContext) {
this.container = container;
this.containingDocument = this.container.getContainingDocument();
this.functionContext = new XFormsFunction.Context(container, this);
this.parentBindingContext = parentBindingContext;
// Push a copy of the parent binding context as first element of the stack (stack cannot be initially empty)
contextStack.push(new BindingContext(parentBindingContext, parentBindingContext.model, parentBindingContext.nodeset,
parentBindingContext.position, parentBindingContext.elementId, false, parentBindingContext.controlElement,
parentBindingContext.locationData, false, parentBindingContext.contextItem, parentBindingContext.scope));
}
// Constructor for XFormsModel
public XFormsContextStack(XFormsModel containingModel) {
this.container = containingModel.getXBLContainer();
this.containingDocument = this.container.getContainingDocument();
this.functionContext = new XFormsFunction.Context(containingModel, this);
}
public void setParentBindingContext(BindingContext parentBindingContext) {
this.parentBindingContext = parentBindingContext;
}
public XFormsFunction.Context getFunctionContext(String sourceEffectiveId) {
functionContext.setSourceEffectiveId(sourceEffectiveId);
functionContext.setModel(getCurrentBindingContext().model);
return functionContext;
}
public void returnFunctionContext() {
functionContext.setSourceEffectiveId(null);
}
/**
* Reset the binding context to the root of the first model's first instance, or to the parent binding context.
*/
public void resetBindingContext(PropertyContext propertyContext) {
// Reset to default model (can be null)
resetBindingContext(propertyContext, container.getDefaultModel());
}
/**
* Reset the binding context to the root of the given model's first instance.
*/
public void resetBindingContext(PropertyContext propertyContext, XFormsModel xformsModel) {
// Clear existing stack
contextStack.clear();
if (xformsModel != null && xformsModel.getDefaultInstance() != null) {
// Push the default context if there is a model with an instance
final Item defaultNode = xformsModel.getDefaultInstance().getInstanceRootElementInfo();
final List<Item> defaultNodeset = Arrays.asList(defaultNode);
contextStack.push(new BindingContext(parentBindingContext, xformsModel, defaultNodeset, 1, null, true, null,
xformsModel.getDefaultInstance().getLocationData(), false, defaultNode, container.getResolutionScope()));
} else {
// Push empty context
final List<Item> defaultContext = containingDocument.getStaticState().DEFAULT_CONTEXT;
contextStack.push(new BindingContext(parentBindingContext, xformsModel, defaultContext, defaultContext.size(), null, true, null,
(xformsModel != null) ? xformsModel.getLocationData() : null, false, null, container.getResolutionScope()));
}
// Add model variables for default model
if (xformsModel != null) {
addModelVariables(propertyContext, xformsModel);
}
}
private void addModelVariables(PropertyContext propertyContext, XFormsModel xformsModel) {
// TODO: Check dirty flag to prevent needless re-evaluation
// All variables in the model are in scope for the nested binds and actions.
final List<Element> elements = Dom4jUtils.elements(xformsModel.getModelDocument().getRootElement(), XFormsConstants.XXFORMS_VARIABLE_NAME);
final List<BindingContext.VariableInfo> variableInfos
= addAndScopeVariables(propertyContext, xformsModel.getXBLContainer(), elements, xformsModel.getEffectiveId());
if (variableInfos != null && variableInfos.size() > 0) {
// Some variables added
final IndentedLogger indentedLogger = containingDocument.getIndentedLogger(XFormsModel.LOGGING_CATEGORY);
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug("", "evaluated model variables", "count", Integer.toString(variableInfos.size()));
}
// Remove extra bindings added
for (int i = 0; i < variableInfos.size(); i++) {
popBinding();
}
getCurrentBindingContext().setVariables(variableInfos);
}
}
public List<BindingContext.VariableInfo> addAndScopeVariables(PropertyContext propertyContext, XBLContainer container, List<Element> elements, String sourceEffectiveId) {
List<BindingContext.VariableInfo> variableInfos = null;
final XBLBindings bindings = containingDocument.getStaticState().getXBLBindings();
for (Element currentElement: elements) {
final String currentElementName = currentElement.getName();
if (currentElementName.equals(XFormsConstants.XXFORMS_VARIABLE_NAME)) {
// Create variable object
final Variable variable = new Variable(container, this, currentElement);
// Find variable scope
final XBLBindings.Scope newScope = bindings.getResolutionScopeByPrefixedId(container.getFullPrefix() + currentElement.attributeValue("id"));
// Push the variable on the context stack. Note that we do as if each variable was a "parent" of the
// following controls and variables.
// NOTE: The value is computed immediately. We should use Expression objects and do lazy evaluation
// in the future.
// NOTE: We used to simply add variables to the current bindingContext, but this could cause issues
// because getVariableValue() can itself use variables declared previously. This would work at first,
// but because BindingContext caches variables in scope, after a first request for in-scope variables,
// further variables values could not be added. The method below temporarily adds more elements on the
// stack but it is safer.
// final String tempSourceEffectiveId = functionContext.getSourceEffectiveId();
// final XFormsModel tempModel = functionContext.getModel();
// final XFormsFunction.Context functionContext = getFunctionContext(sourceEffectiveId);
getFunctionContext(sourceEffectiveId);
pushVariable(currentElement, variable.getVariableName(), variable.getVariableValue(propertyContext, sourceEffectiveId, true, true), newScope);
returnFunctionContext();
// functionContext.setModel(tempModel);
// functionContext.setSourceEffectiveId(tempSourceEffectiveId);
// Add VariableInfo created during above pushVariable(). There must be only one!
if (variableInfos == null)
variableInfos = new ArrayList<BindingContext.VariableInfo>();
assert getCurrentBindingContext().getVariables().size() == 1;
variableInfos.addAll(getCurrentBindingContext().getVariables());
}
}
return variableInfos;
}
/**
* Set the binding context to the current control.
*
* @param xformsControl control to bind
*/
public void setBinding(XFormsControl xformsControl) {
BindingContext controlBindingContext = xformsControl.getBindingContext();
// Don't do the work if the current context is already as requested
if (contextStack.size() > 0 && getCurrentBindingContext() == controlBindingContext)
return;
// Create ancestors-or-self list
final List<BindingContext> ancestorsOrSelf = new ArrayList<BindingContext>();
while (controlBindingContext != null) {
ancestorsOrSelf.add(controlBindingContext);
controlBindingContext = controlBindingContext.parent;
}
Collections.reverse(ancestorsOrSelf);
// Bind up to the specified control
contextStack.clear();
contextStack.addAll(ancestorsOrSelf);
}
public void restoreBinding(BindingContext bindingContext) {
final BindingContext currentBindingContext = getCurrentBindingContext();
if (currentBindingContext != bindingContext.parent)
throw new ValidationException("Inconsistent binding context parent.", currentBindingContext.getLocationData());
contextStack.push(bindingContext);
}
/**
* Push an element containing either single-node or nodeset binding attributes.
*
* @param propertyContext current PropertyContext
* @param bindingElement current element containing node binding attributes
* @param sourceEffectiveId effective id of source control for id resolution of models and binds
* @param scope XBL scope
*/
public void pushBinding(PropertyContext propertyContext, Element bindingElement, String sourceEffectiveId, XBLBindings.Scope scope) {
final String ref = bindingElement.attributeValue("ref");
final String context = bindingElement.attributeValue("context");
final String nodeset = bindingElement.attributeValue("nodeset");
final String model = XFormsUtils.namespaceId(containingDocument, bindingElement.attributeValue("model"));
final String bind = XFormsUtils.namespaceId(containingDocument, bindingElement.attributeValue("bind"));
final Map<String, String> bindingElementNamespaceContext = container.getNamespaceMappings(bindingElement);
pushBinding(propertyContext, ref, context, nodeset, model, bind, bindingElement, bindingElementNamespaceContext, sourceEffectiveId, scope);
}
private BindingContext getBindingContext(XBLBindings.Scope scope) {
final BindingContext currentBindingContext = getCurrentBindingContext();
if (scope == null) {
// Keep existing scope
// TODO: remove this once no caller can pass a null scope
return currentBindingContext;
} else {
// Use scope passed
BindingContext bindingContext = currentBindingContext;
while (bindingContext.scope != scope) {
bindingContext = bindingContext.parent;
// There must be a matching scope down the line
assert bindingContext != null;
}
return bindingContext;
}
}
public void pushBinding(PropertyContext propertyContext, String ref, String context, String nodeset, String modelId, String bindId,
Element bindingElement, Map<String, String> bindingElementNamespaceContext, String sourceEffectiveId, XBLBindings.Scope scope) {
// Get location data for error reporting
final LocationData locationData = (bindingElement == null)
? container.getLocationData()
: new ExtendedLocationData((LocationData) bindingElement.getData(), "pushing XForms control binding", bindingElement);
try {
try {
// Determine current context
final BindingContext currentBindingContext = getCurrentBindingContext();
// Handle scope
// The new binding evaluates against a base binding context which must be in the same scope
final BindingContext baseBindingContext = getBindingContext(scope);
final XBLBindings.Scope newScope;
if (scope == null) {
// Keep existing scope
// TODO: remove this once no caller can pass a null scope
newScope = currentBindingContext.scope;
} else {
// Use scope passed
newScope = scope;
}
// Set context
final String tempSourceEffectiveId = functionContext.getSourceEffectiveId();
if (sourceEffectiveId != null) {
functionContext.setSourceEffectiveId(sourceEffectiveId);
}
// Handle model
final XFormsModel newModel;
final boolean isNewModel;
if (modelId != null) {
final XBLContainer resolutionScopeContainer = container.findResolutionScope(scope);
final Object o = resolutionScopeContainer.resolveObjectById(sourceEffectiveId, modelId, null);
if (!(o instanceof XFormsModel)) {
// TODO: should be dispatched to element having the @model attribute
// Invalid model id
container.dispatchEvent(propertyContext, new XFormsBindingExceptionEvent(containingDocument, container));
}
newModel = (XFormsModel) o;
isNewModel = newModel != baseBindingContext.model;// don't say it's a new model unless it has really changed
} else {
newModel = baseBindingContext.model;
isNewModel = false;
}
// Handle nodeset
final boolean isNewBind;
final int newPosition;
final List<Item> newNodeset;
final boolean hasOverriddenContext;
final Item contextItem;
final boolean isPushModelVariables;
final List<BindingContext.VariableInfo> variableInfo;
{
if (bindId != null) {
// Resolve the bind id to a nodeset
// NOTE: For now, only the top-level models in a resolution scope are considered
final XBLContainer resolutionScopeContainer = container.findResolutionScope(scope);
final Object o = resolutionScopeContainer.resolveObjectById(sourceEffectiveId, bindId, baseBindingContext.getSingleItem());
if (!(o instanceof XFormsModelBinds.Bind)) {
// TODO: should be dispatched to element having the @model attribute
// There is no model in scope so the bind id is incorrect
container.dispatchEvent(propertyContext, new XFormsBindingExceptionEvent(containingDocument, container));
newNodeset = null;
hasOverriddenContext = false;
contextItem = null;
isNewBind = false;
newPosition = 0;
isPushModelVariables = false;
variableInfo = null;
} else {
newNodeset = ((XFormsModelBinds.Bind) o).getNodeset();
hasOverriddenContext = false;
contextItem = baseBindingContext.getSingleItem();
isNewBind = true;
newPosition = Math.min(newNodeset.size(), 1);
isPushModelVariables = false;
variableInfo = null;
}
} else if (ref != null || nodeset != null) {
// Check whether there is an optional context (XForms 1.1, likely generalized in XForms 1.2)
final BindingContext evaluationContextBinding;
if (context != null) {
// Push model and context
pushTemporaryContext(currentBindingContext, baseBindingContext, baseBindingContext.getSingleItem());// provide context information for the context() function
pushBinding(propertyContext, null, null, context, modelId, null, null, bindingElementNamespaceContext, sourceEffectiveId, scope);
hasOverriddenContext = true;
final BindingContext newBindingContext = getCurrentBindingContext();
contextItem = newBindingContext.getSingleItem();
variableInfo = newBindingContext.getVariables();
evaluationContextBinding = newBindingContext;
} else if (isNewModel) {
// Push model only
pushBinding(propertyContext, null, null, null, modelId, null, null, bindingElementNamespaceContext, sourceEffectiveId, scope);
hasOverriddenContext = false;
final BindingContext newBindingContext = getCurrentBindingContext();
contextItem = newBindingContext.getSingleItem();
variableInfo = newBindingContext.getVariables();
evaluationContextBinding = newBindingContext;
} else {
hasOverriddenContext = false;
contextItem = baseBindingContext.getSingleItem();
variableInfo = null;
evaluationContextBinding = baseBindingContext;
}
if (false) {
// NOTE: This is an attempt at allowing evaluating a binding even if no context is present.
// But this doesn't work properly. E.g.:
//
// <xf:group ref="()">
// <xf:input ref="."/>
//
// Above must end up with an empty binding for xf:input, while:
//
// <xf:group ref="()">
// <xf:input ref="instance('foobar')"/>
//
// Above must end up with a non-empty binding IF it was to be evaluated.
//
// Now the second condition above should not happen anyway, because the content of the group
// is non-relevant anyway. But we do have cases now where this happens, so we can't enable
// the code below naively.
//
// We could enable it if we knew statically that the expression did not depend on the
// context though, but right now we don't.
final boolean isDefaultContext;
final List<Item> evaluationNodeset;
final int evaluationPosition;
if (evaluationContextBinding.getNodeset().size() > 0) {
isDefaultContext = false;
evaluationNodeset = evaluationContextBinding.getNodeset();
evaluationPosition = evaluationContextBinding.getPosition();
} else {
isDefaultContext = true;
evaluationNodeset = containingDocument.getStaticState().DEFAULT_CONTEXT;
evaluationPosition = 1;
}
if (!isDefaultContext) {
// Provide context information for the context() function
pushTemporaryContext(currentBindingContext, evaluationContextBinding, evaluationContextBinding.getSingleItem());
}
// Use updated binding context to set model
functionContext.setModel(evaluationContextBinding.model);
newNodeset = XPathCache.evaluateKeepItems(propertyContext, evaluationNodeset, evaluationPosition,
ref != null ? ref : nodeset, bindingElementNamespaceContext, evaluationContextBinding.getInScopeVariables(), XFormsContainingDocument.getFunctionLibrary(),
functionContext, null, locationData);
if (!isDefaultContext) {
popBinding();
}
} else {
if (evaluationContextBinding.getNodeset().size() > 0) {
// Evaluate new XPath in context if the current context is not empty
// TODO: in the future, we should allow null context for expressions that do not depend on the context
// NOTE: We prevent evaluation if the context was empty. However there are cases where this
// should be allowed, if the expression does not depend on the context. Ideally, we would know
// statically whether an expression depends on the context or not, and take separate action if
// that's the case. Currently, such an expression will produce an XPathException.
// It might be the case that when we implement non-evaluation of relevant subtrees, this won't
// be an issue anymore, and we can simply allow evaluation of such expressions. Otherwise,
// static analysis of expressions might provide enough information to handle the two situations.
pushTemporaryContext(currentBindingContext, evaluationContextBinding, evaluationContextBinding.getSingleItem());// provide context information for the context() function
// Use updated binding context to set model
functionContext.setModel(evaluationContextBinding.model);
newNodeset = XPathCache.evaluateKeepItems(propertyContext, evaluationContextBinding.getNodeset(), evaluationContextBinding.getPosition(),
ref != null ? ref : nodeset, bindingElementNamespaceContext, evaluationContextBinding.getInScopeVariables(), XFormsContainingDocument.getFunctionLibrary(),
functionContext, null, locationData);
popBinding();
} else {
// Otherwise we consider we can't evaluate
newNodeset = XFormsConstants.EMPTY_ITEM_LIST;
}
}
// Restore optional context
if (context != null || isNewModel) {
popBinding();
if (context != null)
popBinding();
}
isNewBind = true;
newPosition = 1;
isPushModelVariables = false;
} else if (isNewModel && context == null) {
// Only the model has changed
final BindingContext modelBindingContext = getCurrentBindingContextForModel(newModel);
if (modelBindingContext != null) {
newNodeset = modelBindingContext.getNodeset();
newPosition = modelBindingContext.getPosition();
isPushModelVariables = false;
} else {
newNodeset = getCurrentNodeset(newModel);
newPosition = 1;
// Variables for this model are not yet on the stack
isPushModelVariables = true;
}
hasOverriddenContext = false;
contextItem = baseBindingContext.getSingleItem();
isNewBind = false;
variableInfo = null;
} else if (context != null) {
// Only the context has changed, and possibly the model
pushBinding(propertyContext, null, null, context, modelId, null, null, bindingElementNamespaceContext, sourceEffectiveId, scope);
{
newNodeset = getCurrentNodeset();
newPosition = getCurrentPosition();
isNewBind = false;
hasOverriddenContext = true;
contextItem = getCurrentSingleItem();
isPushModelVariables = false;
variableInfo = null;
}
popBinding();
} else {
// No change to anything
isNewBind = false;
newNodeset = baseBindingContext.getNodeset();
newPosition = baseBindingContext.getPosition();
isPushModelVariables = false;
variableInfo = null;
// We set a new context item as the context into which other attributes must be evaluated. E.g.:
//
// <xforms:select1 ref="type">
// <xforms:action ev:event="xforms-value-changed" if="context() = 'foobar'">
//
// In this case, you expect context() to be updated as follows.
//
hasOverriddenContext = false;
contextItem = baseBindingContext.getSingleItem();
}
}
// Push new context
final String bindingElementStaticId = (bindingElement == null) ? null : bindingElement.attributeValue("id");
contextStack.push(new BindingContext(currentBindingContext, newModel, newNodeset, newPosition, bindingElementStaticId, isNewBind,
bindingElement, locationData, hasOverriddenContext, contextItem, newScope));
// Add new model variables if needed
if (variableInfo != null) {
// In this case, we did a temporary context push with the new model, and we already gathered the new
// variables in scope. We have to set them to the newly pushed BindingContext.
getCurrentBindingContext().setVariables(variableInfo);
} else if (isPushModelVariables) {
// In this case, only the model just changed and so we gather the variables in scope for the new model
addModelVariables(propertyContext, newModel);
}
// Restore context
if (sourceEffectiveId != null) {
functionContext.setSourceEffectiveId(tempSourceEffectiveId);
}
} catch (ValidationException e) {
// Must be due to nested XFormsBindingExceptionEvent
throw e;
} catch (Throwable e) {
// TODO: should be dispatched to element having the @model attribute
// Any other exception occurring within
container.dispatchEvent(propertyContext, new XFormsBindingExceptionEvent(containingDocument, container));
}
} catch (ValidationException e) {
if (bindingElement != null) {
throw ValidationException.wrapException(e, new ExtendedLocationData(locationData, "evaluating binding expression",
bindingElement, "element", Dom4jUtils.elementToDebugString(bindingElement)));
} else {
throw ValidationException.wrapException(e, new ExtendedLocationData(locationData, "evaluating binding expression",
bindingElement, "ref", ref, "context", context, "nodeset", nodeset, "modelId", modelId, "bindId", bindId));
}
}
}
public void pushBinding(BindingContext bindingContext) {
// Don't make a copy and just relink to parent
bindingContext.updateParent(getCurrentBindingContext());
contextStack.push(bindingContext);
}
private void pushTemporaryContext(BindingContext parent, BindingContext base, Item contextItem) {
contextStack.push(new BindingContext(parent, base.model, base.getNodeset(), base.getPosition(), base.elementId,
false, base.getControlElement(), base.getLocationData(), false, contextItem, base.scope));
}
/**
* Push an iteration of the current node-set. Used for example by xforms:repeat, xforms:bind, xxforms:iterate.
*
* @param currentPosition 1-based iteration index
*/
public void pushIteration(int currentPosition) {
final BindingContext currentBindingContext = getCurrentBindingContext();
final List<Item> currentNodeset = currentBindingContext.getNodeset();
// Set a new context item, although the context() function is never called on the iteration itself
final Item newContextItem;
if (currentNodeset == null || currentNodeset.size() == 0)
newContextItem = null;
else
newContextItem = currentNodeset.get(currentPosition - 1);
contextStack.push(new BindingContext(currentBindingContext, currentBindingContext.model,
currentNodeset, currentPosition, currentBindingContext.elementId, true, null, currentBindingContext.getLocationData(),
false, newContextItem, currentBindingContext.scope));
}
/**
* Push a new variable in scope, providing its name and value.
*
* @param variableElement variable element
* @param name variable name
* @param value variable value
* @param scope XBL scope of the variable visibility
*/
public void pushVariable(Element variableElement, String name, ValueRepresentation value, XBLBindings.Scope scope) {
final LocationData locationData = new ExtendedLocationData((LocationData) variableElement.getData(), "pushing variable binding", variableElement);
contextStack.push(new BindingContext(getCurrentBindingContext(), getBindingContext(scope), variableElement, locationData, name, value, scope));
}
public BindingContext getCurrentBindingContext() {
return contextStack.peek();
}
public BindingContext popBinding() {
if (contextStack.size() == 1)
throw new OXFException("Attempt to clear context stack.");
return contextStack.pop();
}
/**
* Get the current node-set binding for the given model.
*/
public BindingContext getCurrentBindingContextForModel(XFormsModel model) {
for (int i = contextStack.size() - 1; i >= 0; i--) {
final BindingContext currentBindingContext = contextStack.get(i);
if (model == currentBindingContext.model)
return currentBindingContext;
}
return null;
}
/**
* Get the current node-set binding for the given model.
*/
public List<Item> getCurrentNodeset(XFormsModel model) {
final BindingContext bindingContext = getCurrentBindingContextForModel(model);
// If a context exists, return its node-set
if (bindingContext != null)
return bindingContext.getNodeset();
// If there is no default instance, return an empty node-set
final XFormsInstance defaultInstance = model.getDefaultInstance();
if (defaultInstance == null)
return XFormsConstants.EMPTY_ITEM_LIST;
// If not found, return the document element of the model's default instance
try {
return Collections.singletonList((Item) defaultInstance.getInstanceRootElementInfo());
} catch (Exception e) {
throw new OXFException(e);
}
}
/**
* Get the current single item, if any.
*/
public Item getCurrentSingleItem() {
return getCurrentBindingContext().getSingleItem();
}
/**
* Get the context item, whether in-scope or overridden.
*/
public Item getContextItem() {
return getCurrentBindingContext().getContextItem();
}
/**
* Return whether there is an overridden context, whether empty or not.
*/
public boolean hasOverriddenContext() {
return getCurrentBindingContext().hasOverriddenContext();
}
/**
* Get the current nodeset binding, if any.
*/
public List<Item> getCurrentNodeset() {
return getCurrentBindingContext().getNodeset();
}
/**
* Get the current position in current nodeset binding.
*/
public int getCurrentPosition() {
return getCurrentBindingContext().getPosition();
}
/**
* Return a Map of the current variables in scope.
*
* @return Map<String, List> of variable name to value
*/
public Map<String, ValueRepresentation> getCurrentVariables() {
return getCurrentBindingContext().getInScopeVariables();
}
/**
* Return the single item associated with the iteration of the repeat specified. If a null
* repeat id is passed, return the single item associated with the closest enclosing repeat
* iteration.
*
* NOTE: Use getContextForId() instead.
*
* @param repeatId enclosing repeat id, or null
* @return the single item
*/
public Item getRepeatCurrentSingleNode(String repeatId) {
BindingContext currentBindingContext = getCurrentBindingContext();
do {
if (isRepeatIterationBindingContext(currentBindingContext) && (repeatId == null || currentBindingContext.parent.elementId.equals(repeatId))) {
// Found binding context for relevant repeat iteration
return currentBindingContext.getSingleItem();
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
// It is required that there is a relevant enclosing xforms:repeat
if (repeatId == null)
throw new ValidationException("No enclosing xforms:repeat found.", getCurrentBindingContext().getLocationData());
else
throw new ValidationException("No enclosing xforms:repeat found for repeat id: " + repeatId, getCurrentBindingContext().getLocationData());
}
private boolean isRepeatIterationBindingContext(BindingContext bindingContext) {
// First, we need a parent
final BindingContext parent = bindingContext.parent;
if (parent == null)
return false;
// We don't have a bound element, but the parent is bound to xforms:repeat
final Element bindingElement = bindingContext.getControlElement();
final Element parentBindingElement = parent.getControlElement();
return (bindingElement == null) && (parentBindingElement != null) && parentBindingElement.getName().equals("repeat");
}
private boolean isRepeatBindingContext(BindingContext bindingContext) {
final Element bindingElement = bindingContext.getControlElement();
return bindingElement != null && bindingElement.getName().equals("repeat");
}
/**
* Return the closest enclosing repeat id.
*
* @return repeat id, throw if not found
*/
public String getEnclosingRepeatId() {
BindingContext currentBindingContext = getCurrentBindingContext();
do {
// Handle case where we are within a repeat iteration, as well as case where we are directly within the
// repeat container object.
if (isRepeatIterationBindingContext(currentBindingContext) || isRepeatBindingContext(currentBindingContext)) {
// Found binding context for relevant repeat iteration
return currentBindingContext.parent.elementId;
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
// It is required that there is an enclosing xforms:repeat
throw new ValidationException("Enclosing xforms:repeat not found.", getCurrentBindingContext().getLocationData());
}
/**
* Obtain the single-node binding for an enclosing xforms:group, xforms:repeat, or xforms:switch. It takes one
* mandatory string parameter containing the id of an enclosing grouping XForms control. For xforms:repeat, the
* context returned is the context of the current iteration.
*
* @param contextId enclosing context id
* @return the item
*/
public Item getContextForId(String contextId) {
BindingContext currentBindingContext = getCurrentBindingContext();
do {
final Element bindingElement = currentBindingContext.getControlElement();
if (bindingElement != null && XFormsControlFactory.isContainerControl(bindingElement.getNamespaceURI(), bindingElement.getName())) {
// We are a grouping control
final String elementId = currentBindingContext.elementId;
if (contextId.equals(elementId)) {
// Found matching binding context for regular grouping control
return currentBindingContext.getSingleItem();
}
} else if (bindingElement == null) {
// We a likely repeat iteration
if (isRepeatIterationBindingContext(currentBindingContext) && currentBindingContext.parent.elementId.equals(contextId)) {
// Found matching repeat iteration
return currentBindingContext.getSingleItem();
}
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
// It is required that there is an enclosing container control
throw new ValidationException("No enclosing container XForms control found for id: " + contextId, getCurrentBindingContext().getLocationData());
}
/**
* Get the current node-set for the given repeat id.
*
* @param repeatId existing repeat id
* @return node-set
*/
public List getRepeatNodeset(String repeatId) {
BindingContext currentBindingContext = getCurrentBindingContext();
do {
final Element bindingElement = currentBindingContext.getControlElement();
final String elementId = currentBindingContext.elementId;
if (repeatId.equals(elementId) && bindingElement != null && bindingElement.getName().equals("repeat")) {
// Found repeat, return associated node-set
return currentBindingContext.getNodeset();
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
// It is required that there is an enclosing xforms:repeat
throw new ValidationException("No enclosing xforms:repeat found for id: " + repeatId, getCurrentBindingContext().getLocationData());
}
/**
* Return the current model for the current nodeset binding.
*/
public XFormsModel getCurrentModel() {
return getCurrentBindingContext().model;
}
public static class BindingContext {
public BindingContext parent;
public final XFormsModel model;
public final List<Item> nodeset;
public final int position;
public final String elementId;
public final boolean newBind;
public final Element controlElement;
public final LocationData locationData;
public final boolean hasOverriddenContext;
public final Item contextItem;
public final XBLBindings.Scope scope;
private List<VariableInfo> variables;
private Map<String, ValueRepresentation> inScopeVariablesMap; // cached variable map
public BindingContext(BindingContext parent, XFormsModel model, List<Item> nodeSet, int position, String elementId,
boolean newBind, Element controlElement, LocationData locationData, boolean hasOverriddenContext,
Item contextItem, XBLBindings.Scope scope) {
assert scope != null;
this.parent = parent;
this.model = model;
this.nodeset = nodeSet;
this.position = position;
this.elementId = elementId;
this.newBind = newBind;
this.controlElement = controlElement;
this.locationData = (locationData != null) ? locationData : (controlElement != null) ? (LocationData) controlElement.getData() : null;
this.hasOverriddenContext = hasOverriddenContext;
this.contextItem = contextItem;
this.scope = scope; // XBL scope of the variable visibility
// if (nodeset != null && nodeset.size() > 0) {
// // TODO: PERF: This seems to take some significant time
// for (Iterator i = nodeset.iterator(); i.hasNext();) {
// final Object currentItem = i.next();
// if (!(currentItem instanceof NodeInfo))
// throw new ValidationException("A reference to a node (such as element, attribute, or text) is required in a binding. Attempted to bind to the invalid item type: " + currentItem.getClass(), this.locationData);
// }
// }
}
public void updateParent(BindingContext parent) {
this.parent = parent;
}
public BindingContext(BindingContext parent, BindingContext base, Element controlElement, LocationData locationData, String variableName,
ValueRepresentation variableValue, XBLBindings.Scope scope) {
this(parent, base.model, base.getNodeset(), base.getPosition(), base.elementId, false,
controlElement, locationData, false, base.getContextItem(), scope);
variables = new ArrayList<VariableInfo>();
variables.add(new VariableInfo(variableName, variableValue));
}
public List<Item> getNodeset() {
return nodeset;
}
public int getPosition() {
return position;
}
public boolean isNewBind() {
return newBind;
}
public Element getControlElement() {
return controlElement;
}
public Item getContextItem() {
return contextItem;
}
public boolean hasOverriddenContext() {
return hasOverriddenContext;
}
/**
* Convenience method returning the location data associated with the XForms element (typically, a control)
* associated with the binding. If location data was passed during construction, pass that, otherwise try to
* get location data from passed element.
*
* @return LocationData object, or null if not found
*/
public LocationData getLocationData() {
return locationData;
}
/**
* Get the current single item, if any.
*/
public Item getSingleItem() {
if (nodeset == null || nodeset.size() == 0)
return null;
return nodeset.get(position - 1);
}
public void setVariables(List<VariableInfo> variableInfo) {
this.variables = variableInfo;
this.inScopeVariablesMap = null;
}
public List<VariableInfo> getVariables() {
return variables;
}
/**
* Return a Map of the variables in scope.
*
* @return map of variable name to value
*/
public Map<String, ValueRepresentation> getInScopeVariables() {
return getInScopeVariables(true);
}
public Map<String, ValueRepresentation> getInScopeVariables(boolean useCache) {
// TODO: Variables in scope in the view must not include the variables defined in another model, but must include all view variables.
if (inScopeVariablesMap == null || !useCache) {
final Map<String, ValueRepresentation> tempVariablesMap = new HashMap<String, ValueRepresentation>();
BindingContext currentBindingContext = this; // start with current BindingContext
do {
if (currentBindingContext.scope == scope) { // consider only BindingContext with same scope and skip others
final List<VariableInfo> currentInfo = currentBindingContext.variables;
if (currentInfo != null) {
for (VariableInfo variableInfo: currentInfo) {
final String currentName = variableInfo.variableName;
if (currentName != null && tempVariablesMap.get(currentName) == null) {
// The binding defines a variable and there is not already a variable with that name
tempVariablesMap.put(variableInfo.variableName, variableInfo.variableValue);
}
}
}
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
if (!useCache)
return tempVariablesMap;
inScopeVariablesMap = tempVariablesMap;
}
return inScopeVariablesMap;
}
public static class VariableInfo {
private String variableName;
private ValueRepresentation variableValue;
private VariableInfo(String variableName, ValueRepresentation variableValue) {
this.variableName = variableName;
this.variableValue = variableValue;
}
}
public XFormsInstance getInstance() {
// NOTE: This is as of 2009-09-17 used only to determine the submission instance based on a submission node.
// May return null
final Item currentNode = getSingleItem();
return (currentNode instanceof NodeInfo) ? model.getContainingDocument().getInstanceForNode((NodeInfo) currentNode) : null;
}
}
}
| src/java/org/orbeon/oxf/xforms/XFormsContextStack.java | /**
* Copyright (C) 2010 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.xforms;
import org.dom4j.Element;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.util.IndentedLogger;
import org.orbeon.oxf.util.PropertyContext;
import org.orbeon.oxf.util.XPathCache;
import org.orbeon.oxf.xforms.control.XFormsControl;
import org.orbeon.oxf.xforms.control.XFormsControlFactory;
import org.orbeon.oxf.xforms.event.events.XFormsBindingExceptionEvent;
import org.orbeon.oxf.xforms.function.XFormsFunction;
import org.orbeon.oxf.xforms.xbl.XBLBindings;
import org.orbeon.oxf.xforms.xbl.XBLContainer;
import org.orbeon.oxf.xml.dom4j.Dom4jUtils;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.orbeon.saxon.om.Item;
import org.orbeon.saxon.om.NodeInfo;
import org.orbeon.saxon.om.ValueRepresentation;
import java.util.*;
/**
* Handle a stack of XPath evaluation context information. This is used by controls (with one stack rooted at each
* XBLContainer), models, and actions.
*/
public class XFormsContextStack {
private XBLContainer container;
private XFormsContainingDocument containingDocument;
private XFormsFunction.Context functionContext;
private BindingContext parentBindingContext;
// TODO: use ArrayStack (although that is not generic)
private Stack<BindingContext> contextStack = new Stack<BindingContext>();
// Constructor for XBLContainer
public XFormsContextStack(XBLContainer container) {
this.container = container;
this.containingDocument = this.container.getContainingDocument();
this.functionContext = new XFormsFunction.Context(container, this);
}
// Constructor for XFormsActionInterpreter
public XFormsContextStack(XBLContainer container, BindingContext parentBindingContext) {
this.container = container;
this.containingDocument = this.container.getContainingDocument();
this.functionContext = new XFormsFunction.Context(container, this);
this.parentBindingContext = parentBindingContext;
// Push a copy of the parent binding context as first element of the stack (stack cannot be initially empty)
contextStack.push(new BindingContext(parentBindingContext, parentBindingContext.model, parentBindingContext.nodeset,
parentBindingContext.position, parentBindingContext.elementId, false, parentBindingContext.controlElement,
parentBindingContext.locationData, false, parentBindingContext.contextItem, parentBindingContext.scope));
}
// Constructor for XFormsModel
public XFormsContextStack(XFormsModel containingModel) {
this.container = containingModel.getXBLContainer();
this.containingDocument = this.container.getContainingDocument();
this.functionContext = new XFormsFunction.Context(containingModel, this);
}
public void setParentBindingContext(BindingContext parentBindingContext) {
this.parentBindingContext = parentBindingContext;
}
public XFormsFunction.Context getFunctionContext(String sourceEffectiveId) {
functionContext.setSourceEffectiveId(sourceEffectiveId);
functionContext.setModel(getCurrentBindingContext().model);
return functionContext;
}
public void returnFunctionContext() {
functionContext.setSourceEffectiveId(null);
}
/**
* Reset the binding context to the root of the first model's first instance, or to the parent binding context.
*/
public void resetBindingContext(PropertyContext propertyContext) {
// Reset to default model (can be null)
resetBindingContext(propertyContext, container.getDefaultModel());
}
/**
* Reset the binding context to the root of the given model's first instance.
*/
public void resetBindingContext(PropertyContext propertyContext, XFormsModel xformsModel) {
// Clear existing stack
contextStack.clear();
if (xformsModel != null && xformsModel.getDefaultInstance() != null) {
// Push the default context if there is a model with an instance
final Item defaultNode = xformsModel.getDefaultInstance().getInstanceRootElementInfo();
final List<Item> defaultNodeset = Arrays.asList(defaultNode);
contextStack.push(new BindingContext(parentBindingContext, xformsModel, defaultNodeset, 1, null, true, null,
xformsModel.getDefaultInstance().getLocationData(), false, defaultNode, container.getResolutionScope()));
} else {
// Push empty context
final List<Item> defaultContext = containingDocument.getStaticState().DEFAULT_CONTEXT;
contextStack.push(new BindingContext(parentBindingContext, xformsModel, defaultContext, defaultContext.size(), null, true, null,
(xformsModel != null) ? xformsModel.getLocationData() : null, false, null, container.getResolutionScope()));
}
// Add model variables for default model
if (xformsModel != null) {
addModelVariables(propertyContext, xformsModel);
}
}
private void addModelVariables(PropertyContext propertyContext, XFormsModel xformsModel) {
// TODO: Check dirty flag to prevent needless re-evaluation
// All variables in the model are in scope for the nested binds and actions.
final List<Element> elements = Dom4jUtils.elements(xformsModel.getModelDocument().getRootElement(), XFormsConstants.XXFORMS_VARIABLE_NAME);
final List<BindingContext.VariableInfo> variableInfos
= addAndScopeVariables(propertyContext, xformsModel.getXBLContainer(), elements, xformsModel.getEffectiveId());
if (variableInfos != null && variableInfos.size() > 0) {
// Some variables added
final IndentedLogger indentedLogger = containingDocument.getIndentedLogger(XFormsModel.LOGGING_CATEGORY);
if (indentedLogger.isDebugEnabled()) {
indentedLogger.logDebug("", "evaluated model variables", "count", Integer.toString(variableInfos.size()));
}
// Remove extra bindings added
for (int i = 0; i < variableInfos.size(); i++) {
popBinding();
}
getCurrentBindingContext().setVariables(variableInfos);
}
}
public List<BindingContext.VariableInfo> addAndScopeVariables(PropertyContext propertyContext, XBLContainer container, List<Element> elements, String sourceEffectiveId) {
List<BindingContext.VariableInfo> variableInfos = null;
final XBLBindings bindings = containingDocument.getStaticState().getXBLBindings();
for (Element currentElement: elements) {
final String currentElementName = currentElement.getName();
if (currentElementName.equals(XFormsConstants.XXFORMS_VARIABLE_NAME)) {
// Create variable object
final Variable variable = new Variable(container, this, currentElement);
// Find variable scope
final XBLBindings.Scope newScope = bindings.getResolutionScopeByPrefixedId(container.getFullPrefix() + currentElement.attributeValue("id"));
// Push the variable on the context stack. Note that we do as if each variable was a "parent" of the
// following controls and variables.
// NOTE: The value is computed immediately. We should use Expression objects and do lazy evaluation
// in the future.
// NOTE: We used to simply add variables to the current bindingContext, but this could cause issues
// because getVariableValue() can itself use variables declared previously. This would work at first,
// but because BindingContext caches variables in scope, after a first request for in-scope variables,
// further variables values could not be added. The method below temporarily adds more elements on the
// stack but it is safer.
// final String tempSourceEffectiveId = functionContext.getSourceEffectiveId();
// final XFormsModel tempModel = functionContext.getModel();
// final XFormsFunction.Context functionContext = getFunctionContext(sourceEffectiveId);
getFunctionContext(sourceEffectiveId);
pushVariable(currentElement, variable.getVariableName(), variable.getVariableValue(propertyContext, sourceEffectiveId, true, true), newScope);
returnFunctionContext();
// functionContext.setModel(tempModel);
// functionContext.setSourceEffectiveId(tempSourceEffectiveId);
// Add VariableInfo created during above pushVariable(). There must be only one!
if (variableInfos == null)
variableInfos = new ArrayList<BindingContext.VariableInfo>();
assert getCurrentBindingContext().getVariables().size() == 1;
variableInfos.addAll(getCurrentBindingContext().getVariables());
}
}
return variableInfos;
}
/**
* Set the binding context to the current control.
*
* @param xformsControl control to bind
*/
public void setBinding(XFormsControl xformsControl) {
BindingContext controlBindingContext = xformsControl.getBindingContext();
// Don't do the work if the current context is already as requested
if (contextStack.size() > 0 && getCurrentBindingContext() == controlBindingContext)
return;
// Create ancestors-or-self list
final List<BindingContext> ancestorsOrSelf = new ArrayList<BindingContext>();
while (controlBindingContext != null) {
ancestorsOrSelf.add(controlBindingContext);
controlBindingContext = controlBindingContext.parent;
}
Collections.reverse(ancestorsOrSelf);
// Bind up to the specified control
contextStack.clear();
contextStack.addAll(ancestorsOrSelf);
}
public void restoreBinding(BindingContext bindingContext) {
final BindingContext currentBindingContext = getCurrentBindingContext();
if (currentBindingContext != bindingContext.parent)
throw new ValidationException("Inconsistent binding context parent.", currentBindingContext.getLocationData());
contextStack.push(bindingContext);
}
/**
* Push an element containing either single-node or nodeset binding attributes.
*
* @param propertyContext current PropertyContext
* @param bindingElement current element containing node binding attributes
* @param sourceEffectiveId effective id of source control for id resolution of models and binds
* @param scope XBL scope
*/
public void pushBinding(PropertyContext propertyContext, Element bindingElement, String sourceEffectiveId, XBLBindings.Scope scope) {
final String ref = bindingElement.attributeValue("ref");
final String context = bindingElement.attributeValue("context");
final String nodeset = bindingElement.attributeValue("nodeset");
final String model = XFormsUtils.namespaceId(containingDocument, bindingElement.attributeValue("model"));
final String bind = XFormsUtils.namespaceId(containingDocument, bindingElement.attributeValue("bind"));
final Map<String, String> bindingElementNamespaceContext = container.getNamespaceMappings(bindingElement);
pushBinding(propertyContext, ref, context, nodeset, model, bind, bindingElement, bindingElementNamespaceContext, sourceEffectiveId, scope);
}
private BindingContext getBindingContext(XBLBindings.Scope scope) {
final BindingContext currentBindingContext = getCurrentBindingContext();
if (scope == null) {
// Keep existing scope
// TODO: remove this once no caller can pass a null scope
return currentBindingContext;
} else {
// Use scope passed
BindingContext bindingContext = currentBindingContext;
while (bindingContext.scope != scope) {
bindingContext = bindingContext.parent;
// There must be a matching scope down the line
assert bindingContext != null;
}
return bindingContext;
}
}
public void pushBinding(PropertyContext propertyContext, String ref, String context, String nodeset, String modelId, String bindId,
Element bindingElement, Map<String, String> bindingElementNamespaceContext, String sourceEffectiveId, XBLBindings.Scope scope) {
// Get location data for error reporting
final LocationData locationData = (bindingElement == null)
? container.getLocationData()
: new ExtendedLocationData((LocationData) bindingElement.getData(), "pushing XForms control binding", bindingElement);
try {
try {
// Determine current context
final BindingContext currentBindingContext = getCurrentBindingContext();
// Handle scope
// The new binding evaluates against a base binding context which must be in the same scope
final BindingContext baseBindingContext = getBindingContext(scope);
final XBLBindings.Scope newScope;
if (scope == null) {
// Keep existing scope
// TODO: remove this once no caller can pass a null scope
newScope = currentBindingContext.scope;
} else {
// Use scope passed
newScope = scope;
}
// Set context
final String tempSourceEffectiveId = functionContext.getSourceEffectiveId();
if (sourceEffectiveId != null) {
functionContext.setSourceEffectiveId(sourceEffectiveId);
}
// Handle model
final XFormsModel newModel;
final boolean isNewModel;
if (modelId != null) {
final XBLContainer resolutionScopeContainer = container.findResolutionScope(scope);
final Object o = resolutionScopeContainer.resolveObjectById(sourceEffectiveId, modelId, null);
if (!(o instanceof XFormsModel)) {
// TODO: should be dispatched to element having the @model attribute
// Invalid model id
container.dispatchEvent(propertyContext, new XFormsBindingExceptionEvent(containingDocument, container));
}
newModel = (XFormsModel) o;
isNewModel = newModel != baseBindingContext.model;// don't say it's a new model unless it has really changed
} else {
newModel = baseBindingContext.model;
isNewModel = false;
}
// Handle nodeset
final boolean isNewBind;
final int newPosition;
final List<Item> newNodeset;
final boolean hasOverriddenContext;
final Item contextItem;
final boolean isPushModelVariables;
final List<BindingContext.VariableInfo> variableInfo;
{
if (bindId != null) {
// Resolve the bind id to a nodeset
// NOTE: For now, only the top-level models in a resolution scope are considered
final XBLContainer resolutionScopeContainer = container.findResolutionScope(scope);
final Object o = resolutionScopeContainer.resolveObjectById(sourceEffectiveId, bindId, baseBindingContext.getSingleItem());
if (!(o instanceof XFormsModelBinds.Bind)) {
// TODO: should be dispatched to element having the @model attribute
// There is no model in scope so the bind id is incorrect
container.dispatchEvent(propertyContext, new XFormsBindingExceptionEvent(containingDocument, container));
newNodeset = null;
hasOverriddenContext = false;
contextItem = null;
isNewBind = false;
newPosition = 0;
isPushModelVariables = false;
variableInfo = null;
} else {
newNodeset = ((XFormsModelBinds.Bind) o).getNodeset();
hasOverriddenContext = false;
contextItem = baseBindingContext.getSingleItem();
isNewBind = true;
newPosition = Math.min(newNodeset.size(), 1);
isPushModelVariables = false;
variableInfo = null;
}
} else if (ref != null || nodeset != null) {
// Check whether there is an optional context (XForms 1.1, likely generalized in XForms 1.2)
final BindingContext evaluationContextBinding;
if (context != null) {
// Push model and context
pushTemporaryContext(currentBindingContext, baseBindingContext, baseBindingContext.getSingleItem());// provide context information for the context() function
pushBinding(propertyContext, null, null, context, modelId, null, null, bindingElementNamespaceContext, sourceEffectiveId, scope);
hasOverriddenContext = true;
final BindingContext newBindingContext = getCurrentBindingContext();
contextItem = newBindingContext.getSingleItem();
variableInfo = newBindingContext.getVariables();
evaluationContextBinding = newBindingContext;
} else if (isNewModel) {
// Push model only
pushBinding(propertyContext, null, null, null, modelId, null, null, bindingElementNamespaceContext, sourceEffectiveId, scope);
hasOverriddenContext = false;
final BindingContext newBindingContext = getCurrentBindingContext();
contextItem = newBindingContext.getSingleItem();
variableInfo = newBindingContext.getVariables();
evaluationContextBinding = newBindingContext;
} else {
hasOverriddenContext = false;
contextItem = baseBindingContext.getSingleItem();
variableInfo = null;
evaluationContextBinding = baseBindingContext;
}
if (false) {
// NOTE: This is an attempt at allowing evaluating a binding even if no context is present.
// But this doesn't work properly. E.g.:
//
// <xf:group ref="()">
// <xf:input ref="."/>
//
// Above must end up with an empty binding for xf:input, while:
//
// <xf:group ref="()">
// <xf:input ref="instance('foobar')"/>
//
// Above must end up with a non-empty binding IF it was to be evaluated.
//
// Now the second condition above should not happen anyway, because the content of the group
// is non-relevant anyway. But we do have cases now where this happens, so we can't enable
// the code below naively.
//
// We could enable it if we knew statically that the expression did not depend on the
// context though, but right now we don't.
final boolean isDefaultContext;
final List<Item> evaluationNodeset;
final int evaluationPosition;
if (evaluationContextBinding.getNodeset().size() > 0) {
isDefaultContext = false;
evaluationNodeset = evaluationContextBinding.getNodeset();
evaluationPosition = evaluationContextBinding.getPosition();
} else {
isDefaultContext = true;
evaluationNodeset = containingDocument.getStaticState().DEFAULT_CONTEXT;
evaluationPosition = 1;
}
if (!isDefaultContext) {
// Provide context information for the context() function
pushTemporaryContext(currentBindingContext, evaluationContextBinding, evaluationContextBinding.getSingleItem());
}
// Use updated binding context to set model
functionContext.setModel(evaluationContextBinding.model);
newNodeset = XPathCache.evaluateKeepItems(propertyContext, evaluationNodeset, evaluationPosition,
ref != null ? ref : nodeset, bindingElementNamespaceContext, evaluationContextBinding.getInScopeVariables(), XFormsContainingDocument.getFunctionLibrary(),
functionContext, null, locationData);
if (!isDefaultContext) {
popBinding();
}
} else {
if (evaluationContextBinding.getNodeset().size() > 0) {
// Evaluate new XPath in context if the current context is not empty
// TODO: in the future, we should allow null context for expressions that do not depend on the context
// NOTE: We prevent evaluation if the context was empty. However there are cases where this
// should be allowed, if the expression does not depend on the context. Ideally, we would know
// statically whether an expression depends on the context or not, and take separate action if
// that's the case. Currently, such an expression will produce an XPathException.
// It might be the case that when we implement non-evaluation of relevant subtrees, this won't
// be an issue anymore, and we can simply allow evaluation of such expressions. Otherwise,
// static analysis of expressions might provide enough information to handle the two situations.
pushTemporaryContext(currentBindingContext, evaluationContextBinding, evaluationContextBinding.getSingleItem());// provide context information for the context() function
// Use updated binding context to set model
functionContext.setModel(evaluationContextBinding.model);
newNodeset = XPathCache.evaluateKeepItems(propertyContext, evaluationContextBinding.getNodeset(), evaluationContextBinding.getPosition(),
ref != null ? ref : nodeset, bindingElementNamespaceContext, evaluationContextBinding.getInScopeVariables(), XFormsContainingDocument.getFunctionLibrary(),
functionContext, null, locationData);
popBinding();
} else {
// Otherwise we consider we can't evaluate
newNodeset = XFormsConstants.EMPTY_ITEM_LIST;
}
}
// Restore optional context
if (context != null || isNewModel) {
popBinding();
if (context != null)
popBinding();
}
isNewBind = true;
newPosition = 1;
isPushModelVariables = false;
} else if (isNewModel && context == null) {
// Only the model has changed
final BindingContext modelBindingContext = getCurrentBindingContextForModel(newModel);
if (modelBindingContext != null) {
newNodeset = modelBindingContext.getNodeset();
newPosition = modelBindingContext.getPosition();
isPushModelVariables = false;
} else {
newNodeset = getCurrentNodeset(newModel);
newPosition = 1;
// Variables for this model are not yet on the stack
isPushModelVariables = true;
}
hasOverriddenContext = false;
contextItem = baseBindingContext.getSingleItem();
isNewBind = false;
variableInfo = null;
} else if (context != null) {
// Only the context has changed, and possibly the model
pushBinding(propertyContext, null, null, context, modelId, null, null, bindingElementNamespaceContext, sourceEffectiveId, scope);
{
newNodeset = getCurrentNodeset();
newPosition = getCurrentPosition();
isNewBind = false;
hasOverriddenContext = true;
contextItem = getCurrentSingleItem();
isPushModelVariables = false;
variableInfo = null;
}
popBinding();
} else {
// No change to anything
isNewBind = false;
newNodeset = baseBindingContext.getNodeset();
newPosition = baseBindingContext.getPosition();
isPushModelVariables = false;
variableInfo = null;
// We set a new context item as the context into which other attributes must be evaluated. E.g.:
//
// <xforms:select1 ref="type">
// <xforms:action ev:event="xforms-value-changed" if="context() = 'foobar'">
//
// In this case, you expect context() to be updated as follows.
//
hasOverriddenContext = false;
contextItem = baseBindingContext.getSingleItem();
}
}
// Push new context
final String bindingElementStaticId = (bindingElement == null) ? null : bindingElement.attributeValue("id");
contextStack.push(new BindingContext(currentBindingContext, newModel, newNodeset, newPosition, bindingElementStaticId, isNewBind,
bindingElement, locationData, hasOverriddenContext, contextItem, newScope));
// Add new model variables if needed
if (variableInfo != null) {
// In this case, we did a temporary context push with the new model, and we already gathered the new
// variables in scope. We have to set them to the newly pushed BindingContext.
getCurrentBindingContext().setVariables(variableInfo);
} else if (isPushModelVariables) {
// In this case, only the model just changed and so we gather the variables in scope for the new model
addModelVariables(propertyContext, newModel);
}
// Restore context
if (sourceEffectiveId != null) {
functionContext.setSourceEffectiveId(tempSourceEffectiveId);
}
} catch (ValidationException e) {
// Must be due to nested XFormsBindingExceptionEvent
throw e;
} catch (Throwable e) {
// TODO: should be dispatched to element having the @model attribute
// Any other exception occurring within
container.dispatchEvent(propertyContext, new XFormsBindingExceptionEvent(containingDocument, container));
}
} catch (ValidationException e) {
if (bindingElement != null) {
throw ValidationException.wrapException(e, new ExtendedLocationData(locationData, "evaluating binding expression",
bindingElement, "element", Dom4jUtils.elementToDebugString(bindingElement)));
} else {
throw ValidationException.wrapException(e, new ExtendedLocationData(locationData, "evaluating binding expression",
bindingElement, "ref", ref, "context", context, "nodeset", nodeset, "modelId", modelId, "bindId", bindId));
}
}
}
public void pushBinding(BindingContext bindingContext) {
// NOTE: would be nice not to have to make a copy and just relink to parent
contextStack.push(new BindingContext(getCurrentBindingContext(), bindingContext.model, bindingContext.getNodeset(),
bindingContext.getPosition(), bindingContext.elementId, bindingContext.newBind, bindingContext.getControlElement(),
bindingContext.getLocationData(), bindingContext.hasOverriddenContext, bindingContext.contextItem, bindingContext.scope));
}
private void pushTemporaryContext(BindingContext parent, BindingContext base, Item contextItem) {
contextStack.push(new BindingContext(parent, base.model, base.getNodeset(), base.getPosition(), base.elementId,
false, base.getControlElement(), base.getLocationData(), false, contextItem, base.scope));
}
/**
* Push an iteration of the current node-set. Used for example by xforms:repeat, xforms:bind, xxforms:iterate.
*
* @param currentPosition 1-based iteration index
*/
public void pushIteration(int currentPosition) {
final BindingContext currentBindingContext = getCurrentBindingContext();
final List<Item> currentNodeset = currentBindingContext.getNodeset();
// Set a new context item, although the context() function is never called on the iteration itself
final Item newContextItem;
if (currentNodeset == null || currentNodeset.size() == 0)
newContextItem = null;
else
newContextItem = currentNodeset.get(currentPosition - 1);
contextStack.push(new BindingContext(currentBindingContext, currentBindingContext.model,
currentNodeset, currentPosition, currentBindingContext.elementId, true, null, currentBindingContext.getLocationData(),
false, newContextItem, currentBindingContext.scope));
}
/**
* Push a new variable in scope, providing its name and value.
*
* @param variableElement variable element
* @param name variable name
* @param value variable value
* @param scope XBL scope of the variable visibility
*/
public void pushVariable(Element variableElement, String name, ValueRepresentation value, XBLBindings.Scope scope) {
final LocationData locationData = new ExtendedLocationData((LocationData) variableElement.getData(), "pushing variable binding", variableElement);
contextStack.push(new BindingContext(getCurrentBindingContext(), getBindingContext(scope), variableElement, locationData, name, value, scope));
}
public BindingContext getCurrentBindingContext() {
return contextStack.peek();
}
public BindingContext popBinding() {
if (contextStack.size() == 1)
throw new OXFException("Attempt to clear context stack.");
return contextStack.pop();
}
/**
* Get the current node-set binding for the given model.
*/
public BindingContext getCurrentBindingContextForModel(XFormsModel model) {
for (int i = contextStack.size() - 1; i >= 0; i--) {
final BindingContext currentBindingContext = contextStack.get(i);
if (model == currentBindingContext.model)
return currentBindingContext;
}
return null;
}
/**
* Get the current node-set binding for the given model.
*/
public List<Item> getCurrentNodeset(XFormsModel model) {
final BindingContext bindingContext = getCurrentBindingContextForModel(model);
// If a context exists, return its node-set
if (bindingContext != null)
return bindingContext.getNodeset();
// If there is no default instance, return an empty node-set
final XFormsInstance defaultInstance = model.getDefaultInstance();
if (defaultInstance == null)
return XFormsConstants.EMPTY_ITEM_LIST;
// If not found, return the document element of the model's default instance
try {
return Collections.singletonList((Item) defaultInstance.getInstanceRootElementInfo());
} catch (Exception e) {
throw new OXFException(e);
}
}
/**
* Get the current single item, if any.
*/
public Item getCurrentSingleItem() {
return getCurrentBindingContext().getSingleItem();
}
/**
* Get the context item, whether in-scope or overridden.
*/
public Item getContextItem() {
return getCurrentBindingContext().getContextItem();
}
/**
* Return whether there is an overridden context, whether empty or not.
*/
public boolean hasOverriddenContext() {
return getCurrentBindingContext().hasOverriddenContext();
}
/**
* Get the current nodeset binding, if any.
*/
public List<Item> getCurrentNodeset() {
return getCurrentBindingContext().getNodeset();
}
/**
* Get the current position in current nodeset binding.
*/
public int getCurrentPosition() {
return getCurrentBindingContext().getPosition();
}
/**
* Return a Map of the current variables in scope.
*
* @return Map<String, List> of variable name to value
*/
public Map<String, ValueRepresentation> getCurrentVariables() {
return getCurrentBindingContext().getInScopeVariables();
}
/**
* Return the single item associated with the iteration of the repeat specified. If a null
* repeat id is passed, return the single item associated with the closest enclosing repeat
* iteration.
*
* NOTE: Use getContextForId() instead.
*
* @param repeatId enclosing repeat id, or null
* @return the single item
*/
public Item getRepeatCurrentSingleNode(String repeatId) {
BindingContext currentBindingContext = getCurrentBindingContext();
do {
if (isRepeatIterationBindingContext(currentBindingContext) && (repeatId == null || currentBindingContext.parent.elementId.equals(repeatId))) {
// Found binding context for relevant repeat iteration
return currentBindingContext.getSingleItem();
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
// It is required that there is a relevant enclosing xforms:repeat
if (repeatId == null)
throw new ValidationException("No enclosing xforms:repeat found.", getCurrentBindingContext().getLocationData());
else
throw new ValidationException("No enclosing xforms:repeat found for repeat id: " + repeatId, getCurrentBindingContext().getLocationData());
}
private boolean isRepeatIterationBindingContext(BindingContext bindingContext) {
// First, we need a parent
final BindingContext parent = bindingContext.parent;
if (parent == null)
return false;
// We don't have a bound element, but the parent is bound to xforms:repeat
final Element bindingElement = bindingContext.getControlElement();
final Element parentBindingElement = parent.getControlElement();
return (bindingElement == null) && (parentBindingElement != null) && parentBindingElement.getName().equals("repeat");
}
private boolean isRepeatBindingContext(BindingContext bindingContext) {
final Element bindingElement = bindingContext.getControlElement();
return bindingElement != null && bindingElement.getName().equals("repeat");
}
/**
* Return the closest enclosing repeat id.
*
* @return repeat id, throw if not found
*/
public String getEnclosingRepeatId() {
BindingContext currentBindingContext = getCurrentBindingContext();
do {
// Handle case where we are within a repeat iteration, as well as case where we are directly within the
// repeat container object.
if (isRepeatIterationBindingContext(currentBindingContext) || isRepeatBindingContext(currentBindingContext)) {
// Found binding context for relevant repeat iteration
return currentBindingContext.parent.elementId;
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
// It is required that there is an enclosing xforms:repeat
throw new ValidationException("Enclosing xforms:repeat not found.", getCurrentBindingContext().getLocationData());
}
/**
* Obtain the single-node binding for an enclosing xforms:group, xforms:repeat, or xforms:switch. It takes one
* mandatory string parameter containing the id of an enclosing grouping XForms control. For xforms:repeat, the
* context returned is the context of the current iteration.
*
* @param contextId enclosing context id
* @return the item
*/
public Item getContextForId(String contextId) {
BindingContext currentBindingContext = getCurrentBindingContext();
do {
final Element bindingElement = currentBindingContext.getControlElement();
if (bindingElement != null && XFormsControlFactory.isContainerControl(bindingElement.getNamespaceURI(), bindingElement.getName())) {
// We are a grouping control
final String elementId = currentBindingContext.elementId;
if (contextId.equals(elementId)) {
// Found matching binding context for regular grouping control
return currentBindingContext.getSingleItem();
}
} else if (bindingElement == null) {
// We a likely repeat iteration
if (isRepeatIterationBindingContext(currentBindingContext) && currentBindingContext.parent.elementId.equals(contextId)) {
// Found matching repeat iteration
return currentBindingContext.getSingleItem();
}
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
// It is required that there is an enclosing container control
throw new ValidationException("No enclosing container XForms control found for id: " + contextId, getCurrentBindingContext().getLocationData());
}
/**
* Get the current node-set for the given repeat id.
*
* @param repeatId existing repeat id
* @return node-set
*/
public List getRepeatNodeset(String repeatId) {
BindingContext currentBindingContext = getCurrentBindingContext();
do {
final Element bindingElement = currentBindingContext.getControlElement();
final String elementId = currentBindingContext.elementId;
if (repeatId.equals(elementId) && bindingElement != null && bindingElement.getName().equals("repeat")) {
// Found repeat, return associated node-set
return currentBindingContext.getNodeset();
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
// It is required that there is an enclosing xforms:repeat
throw new ValidationException("No enclosing xforms:repeat found for id: " + repeatId, getCurrentBindingContext().getLocationData());
}
/**
* Return the current model for the current nodeset binding.
*/
public XFormsModel getCurrentModel() {
return getCurrentBindingContext().model;
}
public static class BindingContext {
public final BindingContext parent;
public final XFormsModel model;
public final List<Item> nodeset;
public final int position;
public final String elementId;
public final boolean newBind;
public final Element controlElement;
public final LocationData locationData;
public final boolean hasOverriddenContext;
public final Item contextItem;
public final XBLBindings.Scope scope;
private List<VariableInfo> variables;
private Map<String, ValueRepresentation> inScopeVariablesMap; // cached variable map
public BindingContext(BindingContext parent, XFormsModel model, List<Item> nodeSet, int position, String elementId,
boolean newBind, Element controlElement, LocationData locationData, boolean hasOverriddenContext,
Item contextItem, XBLBindings.Scope scope) {
assert scope != null;
this.parent = parent;
this.model = model;
this.nodeset = nodeSet;
this.position = position;
this.elementId = elementId;
this.newBind = newBind;
this.controlElement = controlElement;
this.locationData = (locationData != null) ? locationData : (controlElement != null) ? (LocationData) controlElement.getData() : null;
this.hasOverriddenContext = hasOverriddenContext;
this.contextItem = contextItem;
this.scope = scope; // XBL scope of the variable visibility
// if (nodeset != null && nodeset.size() > 0) {
// // TODO: PERF: This seems to take some significant time
// for (Iterator i = nodeset.iterator(); i.hasNext();) {
// final Object currentItem = i.next();
// if (!(currentItem instanceof NodeInfo))
// throw new ValidationException("A reference to a node (such as element, attribute, or text) is required in a binding. Attempted to bind to the invalid item type: " + currentItem.getClass(), this.locationData);
// }
// }
}
public BindingContext(BindingContext parent, BindingContext base, Element controlElement, LocationData locationData, String variableName,
ValueRepresentation variableValue, XBLBindings.Scope scope) {
this(parent, base.model, base.getNodeset(), base.getPosition(), base.elementId, false,
controlElement, locationData, false, base.getContextItem(), scope);
variables = new ArrayList<VariableInfo>();
variables.add(new VariableInfo(variableName, variableValue));
}
public List<Item> getNodeset() {
return nodeset;
}
public int getPosition() {
return position;
}
public boolean isNewBind() {
return newBind;
}
public Element getControlElement() {
return controlElement;
}
public Item getContextItem() {
return contextItem;
}
public boolean hasOverriddenContext() {
return hasOverriddenContext;
}
/**
* Convenience method returning the location data associated with the XForms element (typically, a control)
* associated with the binding. If location data was passed during construction, pass that, otherwise try to
* get location data from passed element.
*
* @return LocationData object, or null if not found
*/
public LocationData getLocationData() {
return locationData;
}
/**
* Get the current single item, if any.
*/
public Item getSingleItem() {
if (nodeset == null || nodeset.size() == 0)
return null;
return nodeset.get(position - 1);
}
public void setVariables(List<VariableInfo> variableInfo) {
this.variables = variableInfo;
this.inScopeVariablesMap = null;
}
public List<VariableInfo> getVariables() {
return variables;
}
/**
* Return a Map of the variables in scope.
*
* @return map of variable name to value
*/
public Map<String, ValueRepresentation> getInScopeVariables() {
return getInScopeVariables(true);
}
public Map<String, ValueRepresentation> getInScopeVariables(boolean useCache) {
// TODO: Variables in scope in the view must not include the variables defined in another model, but must include all view variables.
if (inScopeVariablesMap == null || !useCache) {
final Map<String, ValueRepresentation> tempVariablesMap = new HashMap<String, ValueRepresentation>();
BindingContext currentBindingContext = this; // start with current BindingContext
do {
if (currentBindingContext.scope == scope) { // consider only BindingContext with same scope and skip others
final List<VariableInfo> currentInfo = currentBindingContext.variables;
if (currentInfo != null) {
for (VariableInfo variableInfo: currentInfo) {
final String currentName = variableInfo.variableName;
if (currentName != null && tempVariablesMap.get(currentName) == null) {
// The binding defines a variable and there is not already a variable with that name
tempVariablesMap.put(variableInfo.variableName, variableInfo.variableValue);
}
}
}
}
currentBindingContext = currentBindingContext.parent;
} while (currentBindingContext != null);
if (!useCache)
return tempVariablesMap;
inScopeVariablesMap = tempVariablesMap;
}
return inScopeVariablesMap;
}
public static class VariableInfo {
private String variableName;
private ValueRepresentation variableValue;
private VariableInfo(String variableName, ValueRepresentation variableValue) {
this.variableName = variableName;
this.variableValue = variableValue;
}
}
public XFormsInstance getInstance() {
// NOTE: This is as of 2009-09-17 used only to determine the submission instance based on a submission node.
// May return null
final Item currentNode = getSingleItem();
return (currentNode instanceof NodeInfo) ? model.getContainingDocument().getInstanceForNode((NodeInfo) currentNode) : null;
}
}
}
| UI dependencies: fixed bug where variables were not copied if binding did not require update.
| src/java/org/orbeon/oxf/xforms/XFormsContextStack.java | UI dependencies: fixed bug where variables were not copied if binding did not require update. | <ide><path>rc/java/org/orbeon/oxf/xforms/XFormsContextStack.java
<ide> }
<ide>
<ide> public void pushBinding(BindingContext bindingContext) {
<del> // NOTE: would be nice not to have to make a copy and just relink to parent
<del> contextStack.push(new BindingContext(getCurrentBindingContext(), bindingContext.model, bindingContext.getNodeset(),
<del> bindingContext.getPosition(), bindingContext.elementId, bindingContext.newBind, bindingContext.getControlElement(),
<del> bindingContext.getLocationData(), bindingContext.hasOverriddenContext, bindingContext.contextItem, bindingContext.scope));
<add> // Don't make a copy and just relink to parent
<add> bindingContext.updateParent(getCurrentBindingContext());
<add> contextStack.push(bindingContext);
<ide> }
<ide>
<ide> private void pushTemporaryContext(BindingContext parent, BindingContext base, Item contextItem) {
<ide> }
<ide>
<ide> public static class BindingContext {
<del> public final BindingContext parent;
<add> public BindingContext parent;
<ide> public final XFormsModel model;
<ide> public final List<Item> nodeset;
<ide> public final int position;
<ide> // throw new ValidationException("A reference to a node (such as element, attribute, or text) is required in a binding. Attempted to bind to the invalid item type: " + currentItem.getClass(), this.locationData);
<ide> // }
<ide> // }
<add> }
<add>
<add> public void updateParent(BindingContext parent) {
<add> this.parent = parent;
<ide> }
<ide>
<ide> public BindingContext(BindingContext parent, BindingContext base, Element controlElement, LocationData locationData, String variableName, |
|
Java | agpl-3.0 | 7a45c8bcc723a30c21e76a619b0e41e0b2ed544f | 0 | almerm/sw2017-xp3,almerm/sw2017-xp3 | package at.sw2017xp3.regionalo;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import at.sw2017xp3.regionalo.model.Core;
import at.sw2017xp3.regionalo.util.Security;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private ArrayList<View> list_of_elements = new ArrayList<>();
private String phpurl;
private static String logged_user_id;
public static Boolean loggedIn_ = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
list_of_elements.addAll(Arrays.asList(
findViewById(R.id.buttonRegister),
findViewById(R.id.buttonLogin)));
for (int i = 0; i < list_of_elements.size(); i++) {
list_of_elements.get(i).setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
Button clickedButton = (Button) v;
switch (clickedButton.getId()) {
case R.id.buttonLogin:
checkLogin();
break;
case R.id.buttonRegister:
Intent myIntent = new Intent(this, RegisterActivity.class);
startActivity(myIntent);
break;
}
}
public void checkLogin() {
if (((TextView) findViewById(R.id.textViewEmail)).getText().toString().isEmpty() ||
((TextView) findViewById(R.id.textViewPassword)).getText().toString().isEmpty()) {
((TextView) findViewById(R.id.textView_ID_LoginErrors)).setText(getString(R.string.missingPW_Email));
return;
}
final String email = ((TextView) findViewById(R.id.textViewEmail)).getText().toString();
final String password = Security.SHA1(((TextView) findViewById(R.id.textViewPassword)).getText().toString());
new AsyncLogin().execute(email, password);
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(LoginActivity.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage(getString(R.string.loading));
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
String ret = "";
try {
ret = Core.getInstance().getUsers().LogInUser(params[0], params[1]);
if (!ret.equals("false"))
setLoggedUserId(ret);
} catch (Exception ex) {
return "false";
}
return ret;
}
@Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
String some = getString(R.string.falseStatement);
if (logged_user_id.equals(getString(R.string.falseStatement))) {
setWrongUsernamePasswordTextView();
return;
}
if(result.equalsIgnoreCase(logged_user_id)) {
loggedIn_ = true;
Intent intent = new Intent(LoginActivity.this, ReleaseAdActivity.class);
intent.putExtra(getString(R.string.loggedUserId), logged_user_id);
startActivity(intent);
LoginActivity.this.finish();
}
}
}
public void setLoggedUserId(String value) {
logged_user_id = value;
}
public static String getLoggedUserId() {
return logged_user_id;
}
public void setWrongUsernamePasswordTextView() {
((TextView) findViewById(R.id.textView_ID_LoginErrors)).setText(getString(R.string.missingPW_Email));
}
} | app/src/main/java/at/sw2017xp3/regionalo/LoginActivity.java | package at.sw2017xp3.regionalo;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import at.sw2017xp3.regionalo.model.Core;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private ArrayList<View> list_of_elements = new ArrayList<>();
private String phpurl;
private static String logged_user_id;
public static Boolean loggedIn_ = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
list_of_elements.addAll(Arrays.asList(
findViewById(R.id.buttonRegister),
findViewById(R.id.buttonLogin)));
for (int i = 0; i < list_of_elements.size(); i++) {
list_of_elements.get(i).setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
Button clickedButton = (Button) v;
switch (clickedButton.getId()) {
case R.id.buttonLogin:
checkLogin();
break;
case R.id.buttonRegister:
Intent myIntent = new Intent(this, RegisterActivity.class);
startActivity(myIntent);
break;
}
}
public void checkLogin() {
if (((TextView) findViewById(R.id.textViewEmail)).getText().toString().isEmpty() ||
((TextView) findViewById(R.id.textViewPassword)).getText().toString().isEmpty()) {
((TextView) findViewById(R.id.textView_ID_LoginErrors)).setText(getString(R.string.missingPW_Email));
return;
}
final String email = ((TextView) findViewById(R.id.textViewEmail)).getText().toString();
final String password = ((TextView) findViewById(R.id.textViewPassword)).getText().toString();
new AsyncLogin().execute(email, password);
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(LoginActivity.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage(getString(R.string.loading));
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
String ret = "";
try {
ret = Core.getInstance().getUsers().LogInUser(params[0], params[1]);
if (!ret.equals("false"))
setLoggedUserId(ret);
} catch (Exception ex) {
return "false";
}
return ret;
}
@Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
String some = getString(R.string.falseStatement);
if (logged_user_id.equals(getString(R.string.falseStatement))) {
setWrongUsernamePasswordTextView();
return;
}
if(result.equalsIgnoreCase(logged_user_id)) {
loggedIn_ = true;
Intent intent = new Intent(LoginActivity.this, ReleaseAdActivity.class);
intent.putExtra(getString(R.string.loggedUserId), logged_user_id);
startActivity(intent);
LoginActivity.this.finish();
}
}
}
public void setLoggedUserId(String value) {
logged_user_id = value;
}
public static String getLoggedUserId() {
return logged_user_id;
}
public void setWrongUsernamePasswordTextView() {
((TextView) findViewById(R.id.textView_ID_LoginErrors)).setText(getString(R.string.missingPW_Email));
}
} | [MA,LH] login fix
| app/src/main/java/at/sw2017xp3/regionalo/LoginActivity.java | [MA,LH] login fix | <ide><path>pp/src/main/java/at/sw2017xp3/regionalo/LoginActivity.java
<ide> import android.support.v7.app.AppCompatActivity;
<ide> import android.view.View;
<ide> import android.widget.Button;
<add>import android.widget.EditText;
<ide> import android.widget.TextView;
<ide> import android.widget.Toast;
<ide>
<ide> import java.util.Arrays;
<ide>
<ide> import at.sw2017xp3.regionalo.model.Core;
<add>import at.sw2017xp3.regionalo.util.Security;
<ide>
<ide>
<ide> public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
<ide> }
<ide>
<ide> final String email = ((TextView) findViewById(R.id.textViewEmail)).getText().toString();
<del> final String password = ((TextView) findViewById(R.id.textViewPassword)).getText().toString();
<add> final String password = Security.SHA1(((TextView) findViewById(R.id.textViewPassword)).getText().toString());
<ide>
<ide> new AsyncLogin().execute(email, password);
<ide> } |
|
Java | apache-2.0 | 7397fa907bc0d60e9660271f48a6e159d62c1866 | 0 | researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds | package won.cryptography.service;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.PrivateKeyStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.crypto.Cipher;
import javax.net.ssl.SSLContext;
import java.lang.invoke.MethodHandles;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Supplier;
/**
* User: fsalcher Date: 12.06.2014
*/
public class CryptographyUtils {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final Ehcache ehcache;
static {
CacheManager manager = CacheManager.getInstance();
ehcache = new Cache("sslContextCache", 100, false, false, 3600, 600);
manager.addCache(ehcache);
}
public static boolean checkForUnlimitedSecurityPolicy() {
try {
int size = Cipher.getMaxAllowedKeyLength("RC5");
System.out.println("max allowed key size: " + size);
return size < 256;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static SSLContext getSSLContext(final KeyStore keyStore, final String ksPass,
final PrivateKeyStrategy keyStrategy, final KeyStore trustStore, TrustStrategy trustStrategy,
boolean allowCached) throws Exception {
if (allowCached) {
return getCachedSslContextForKeystore(keyStore,
makeCacheKey(keyStore, keyStrategy, trustStore, trustStrategy), () -> {
try {
return createSSLContextBuilder(keyStore, ksPass, keyStrategy, trustStore,
trustStrategy)
.build();
} catch (Exception exception) {
logger.error("Error creating ssl context", exception);
}
return null;
});
} else {
return createSSLContextBuilder(keyStore, ksPass, keyStrategy, trustStore, trustStrategy).build();
}
}
private static String makeCacheKey(KeyStore keyStore,
PrivateKeyStrategy keyStrategy, KeyStore trustStore, TrustStrategy trustStrategy) {
return keyStore.hashCode()
+ "-" + keyStrategy.hashCode()
+ "-" + trustStore.hashCode()
+ "-" + trustStrategy.hashCode();
}
private static SSLContext getCachedSslContextForKeystore(final KeyStore keyStore, String cacheKey,
Supplier<SSLContext> sslContextSupplier) throws Exception {
Instant start = Instant.now();
logger.debug("Creating or obtaining cached SSL context");
Element cacheElement = ehcache.get(cacheKey);
SSLContext sslContext;
if (cacheElement != null) {
// check the size of the keystore - if it has changed, reload
if (keyStoreHasChanged(keyStore, cacheElement)) {
ehcache.remove(cacheElement);
cacheElement = null;
} else {
if (logger.isDebugEnabled()) {
logger.debug("Obtaining cached SSL context took {} millis",
Duration.between(start, Instant.now()).toMillis());
}
}
}
if (cacheElement == null) {
if (logger.isDebugEnabled()) {
logger.debug("Creating new SSL context and caching it...");
}
// we want to avoid creating the sslContext multiple times, so we snychronize on
// an object shared by all threads:
synchronized (ehcache) {
if (logger.isDebugEnabled()) {
logger.debug("Inside critical section, {} millis since method start",
Duration.between(start, Instant.now()).toMillis());
}
// now we have to check again (maybe we're in the thread that had to wait - in
// that case, the
// sslContext has been created already
cacheElement = ehcache.get(cacheKey);
if (logger.isDebugEnabled()) {
logger.debug("cached element found: {} ", (cacheElement != null));
if (cacheElement != null) {
logger.debug("current keystore size: {}, size of cached keystore:{}", keyStore.size(),
((CacheEntry) cacheElement.getObjectValue()).keystoreSize);
}
}
if (cacheElement == null || keyStoreHasChanged(keyStore, cacheElement)) {
sslContext = sslContextSupplier.get();
cacheElement = new Element(cacheKey, new CacheEntry(sslContext, keyStore.size()));
ehcache.put(cacheElement);
if (logger.isDebugEnabled()) {
logger.debug("new SSL Context created, {} millis since method start",
Duration.between(start, Instant.now()).toMillis());
}
}
}
}
return ((CacheEntry) cacheElement.getObjectValue()).getSslContext();
}
private static boolean keyStoreHasChanged(KeyStore keyStore, Element cacheElement) throws KeyStoreException {
return ((CacheEntry) cacheElement.getObjectValue()).keystoreSize != keyStore.size();
}
private static SSLContextBuilder createSSLContextBuilder(final KeyStore keyStore, final String ksPass,
final PrivateKeyStrategy keyStrategy, final KeyStore trustStore, TrustStrategy trustStrategy)
throws Exception {
Instant start = Instant.now();
SSLContextBuilder contextBuilder = SSLContexts.custom();
contextBuilder.loadKeyMaterial(keyStore, ksPass.toCharArray(), keyStrategy);
// if trustStore is null, default CAs trust store is used
contextBuilder.loadTrustMaterial(trustStore, trustStrategy);
if (logger.isDebugEnabled()) {
logger.debug("Loaded key material in {} millis", Duration.between(start, Instant.now()).toMillis());
}
return contextBuilder;
}
public static RestTemplate createSslRestTemplate(final KeyStore keyStore, final String ksPass,
final PrivateKeyStrategy keyStrategy, final KeyStore trustStore, TrustStrategy trustStrategy,
final Integer readTimeout, final Integer connectionTimeout, final boolean allowCached)
throws Exception {
SSLContext sslContext = getSSLContext(keyStore, ksPass, keyStrategy, trustStore, trustStrategy, allowCached);
// here in the constructor, also hostname verifier, protocol version, cipher
// suits, etc. can be specified
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
HttpClient httpClient = HttpClients.custom()// .useSystemProperties()
.setSSLSocketFactory(sslConnectionSocketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
if (readTimeout != null) {
requestFactory.setReadTimeout(readTimeout);
}
if (connectionTimeout != null) {
requestFactory.setConnectTimeout(connectionTimeout);
}
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
public static RestTemplate createSslRestTemplate(TrustStrategy trustStrategy, final Integer readTimeout,
final Integer connectionTimeout) throws Exception {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, // if
// trustStore is null, default CAs trust store is used
trustStrategy).build();
// here in the constructor, also hostname verifier, protocol version, cipher
// suits, etc. can be specified
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
HttpClient httpClient = HttpClients.custom()// .useSystemProperties()
.setSSLSocketFactory(sslConnectionSocketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
if (readTimeout != null) {
requestFactory.setReadTimeout(readTimeout);
}
if (connectionTimeout != null) {
requestFactory.setConnectTimeout(connectionTimeout);
}
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
private static class CacheEntry {
private SSLContext sslContext;
private int keystoreSize;
public CacheEntry(SSLContext sslContext, int keystoreSize) {
this.sslContext = sslContext;
this.keystoreSize = keystoreSize;
}
public SSLContext getSslContext() {
return sslContext;
}
public int getKeystoreSize() {
return keystoreSize;
}
}
}
| webofneeds/won-core/src/main/java/won/cryptography/service/CryptographyUtils.java | package won.cryptography.service;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.PrivateKeyStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import javax.crypto.Cipher;
import javax.net.ssl.SSLContext;
import java.lang.invoke.MethodHandles;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.function.Supplier;
/**
* User: fsalcher Date: 12.06.2014
*/
public class CryptographyUtils {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final Ehcache ehcache;
static {
CacheManager manager = CacheManager.getInstance();
ehcache = new Cache("sslContextCache", 100, false, false, 3600, 600);
manager.addCache(ehcache);
}
public static boolean checkForUnlimitedSecurityPolicy() {
try {
int size = Cipher.getMaxAllowedKeyLength("RC5");
System.out.println("max allowed key size: " + size);
return size < 256;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static SSLContext getSSLContext(final KeyStore keyStore, final String ksPass,
final PrivateKeyStrategy keyStrategy, final KeyStore trustStore, TrustStrategy trustStrategy,
boolean allowCached) throws Exception {
if (allowCached) {
return getCachedSslContextForKeystore(keyStore,
makeCacheKey(keyStore, keyStrategy, trustStore, trustStrategy), () -> {
try {
return createSSLContextBuilder(keyStore, ksPass, keyStrategy, trustStore,
trustStrategy)
.build();
} catch (Exception exception) {
logger.error("Error creating ssl context", exception);
}
return null;
});
} else {
return createSSLContextBuilder(keyStore, ksPass, keyStrategy, trustStore, trustStrategy).build();
}
}
private static String makeCacheKey(KeyStore keyStore,
PrivateKeyStrategy keyStrategy, KeyStore trustStore, TrustStrategy trustStrategy) {
return keyStore.hashCode()
+ "-" + keyStrategy.hashCode()
+ "-" + trustStore.hashCode()
+ "-" + trustStrategy.hashCode();
}
private static SSLContext getCachedSslContextForKeystore(final KeyStore keyStore, String cacheKey,
Supplier<SSLContext> sslContextSupplier) throws Exception {
Element cacheElement = ehcache.get(cacheKey);
SSLContext sslContext;
if (cacheElement != null) {
// check the size of the keystore - if it has changed, reload
if (keyStoreHasChanged(keyStore, cacheElement)) {
ehcache.remove(cacheElement);
cacheElement = null;
}
}
if (cacheElement == null) {
// we want to avoid creating the sslContext multiple times, so we snychronize on
// an object shared by all threads:
synchronized (ehcache) {
// now we have to check again (maybe we're in the thread that had to wait - in
// that case, the
// sslContext has been created already
cacheElement = ehcache.get(cacheKey);
if (cacheElement == null || keyStoreHasChanged(keyStore, cacheElement)) {
sslContext = sslContextSupplier.get();
cacheElement = new Element(cacheKey, new CacheEntry(sslContext, keyStore.size()));
ehcache.put(cacheElement);
}
}
}
return ((CacheEntry) cacheElement.getObjectValue()).getSslContext();
}
private static boolean keyStoreHasChanged(KeyStore keyStore, Element cacheElement) throws KeyStoreException {
return ((CacheEntry) cacheElement.getObjectValue()).keystoreSize != keyStore.size();
}
private static SSLContextBuilder createSSLContextBuilder(final KeyStore keyStore, final String ksPass,
final PrivateKeyStrategy keyStrategy, final KeyStore trustStore, TrustStrategy trustStrategy)
throws Exception {
SSLContextBuilder contextBuilder = SSLContexts.custom();
contextBuilder.loadKeyMaterial(keyStore, ksPass.toCharArray(), keyStrategy);
// if trustStore is null, default CAs trust store is used
contextBuilder.loadTrustMaterial(trustStore, trustStrategy);
return contextBuilder;
}
public static RestTemplate createSslRestTemplate(final KeyStore keyStore, final String ksPass,
final PrivateKeyStrategy keyStrategy, final KeyStore trustStore, TrustStrategy trustStrategy,
final Integer readTimeout, final Integer connectionTimeout, final boolean allowCached)
throws Exception {
SSLContext sslContext = getSSLContext(keyStore, ksPass, keyStrategy, trustStore, trustStrategy, allowCached);
// here in the constructor, also hostname verifier, protocol version, cipher
// suits, etc. can be specified
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
HttpClient httpClient = HttpClients.custom()// .useSystemProperties()
.setSSLSocketFactory(sslConnectionSocketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
if (readTimeout != null) {
requestFactory.setReadTimeout(readTimeout);
}
if (connectionTimeout != null) {
requestFactory.setConnectTimeout(connectionTimeout);
}
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
public static RestTemplate createSslRestTemplate(TrustStrategy trustStrategy, final Integer readTimeout,
final Integer connectionTimeout) throws Exception {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, // if
// trustStore is null, default CAs trust store is used
trustStrategy).build();
// here in the constructor, also hostname verifier, protocol version, cipher
// suits, etc. can be specified
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
HttpClient httpClient = HttpClients.custom()// .useSystemProperties()
.setSSLSocketFactory(sslConnectionSocketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
if (readTimeout != null) {
requestFactory.setReadTimeout(readTimeout);
}
if (connectionTimeout != null) {
requestFactory.setConnectTimeout(connectionTimeout);
}
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
private static class CacheEntry {
private SSLContext sslContext;
private int keystoreSize;
public CacheEntry(SSLContext sslContext, int keystoreSize) {
this.sslContext = sslContext;
this.keystoreSize = keystoreSize;
}
public SSLContext getSslContext() {
return sslContext;
}
public int getKeystoreSize() {
return keystoreSize;
}
}
}
| Add timing code
| webofneeds/won-core/src/main/java/won/cryptography/service/CryptographyUtils.java | Add timing code | <ide><path>ebofneeds/won-core/src/main/java/won/cryptography/service/CryptographyUtils.java
<ide> import java.lang.invoke.MethodHandles;
<ide> import java.security.KeyStore;
<ide> import java.security.KeyStoreException;
<add>import java.time.Duration;
<add>import java.time.Instant;
<ide> import java.util.function.Supplier;
<ide>
<ide> /**
<ide>
<ide> private static SSLContext getCachedSslContextForKeystore(final KeyStore keyStore, String cacheKey,
<ide> Supplier<SSLContext> sslContextSupplier) throws Exception {
<add> Instant start = Instant.now();
<add> logger.debug("Creating or obtaining cached SSL context");
<ide> Element cacheElement = ehcache.get(cacheKey);
<ide> SSLContext sslContext;
<ide> if (cacheElement != null) {
<ide> if (keyStoreHasChanged(keyStore, cacheElement)) {
<ide> ehcache.remove(cacheElement);
<ide> cacheElement = null;
<add> } else {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Obtaining cached SSL context took {} millis",
<add> Duration.between(start, Instant.now()).toMillis());
<add> }
<ide> }
<ide> }
<ide> if (cacheElement == null) {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Creating new SSL context and caching it...");
<add> }
<ide> // we want to avoid creating the sslContext multiple times, so we snychronize on
<ide> // an object shared by all threads:
<ide> synchronized (ehcache) {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Inside critical section, {} millis since method start",
<add> Duration.between(start, Instant.now()).toMillis());
<add> }
<ide> // now we have to check again (maybe we're in the thread that had to wait - in
<ide> // that case, the
<ide> // sslContext has been created already
<ide> cacheElement = ehcache.get(cacheKey);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("cached element found: {} ", (cacheElement != null));
<add> if (cacheElement != null) {
<add> logger.debug("current keystore size: {}, size of cached keystore:{}", keyStore.size(),
<add> ((CacheEntry) cacheElement.getObjectValue()).keystoreSize);
<add> }
<add> }
<ide> if (cacheElement == null || keyStoreHasChanged(keyStore, cacheElement)) {
<ide> sslContext = sslContextSupplier.get();
<ide> cacheElement = new Element(cacheKey, new CacheEntry(sslContext, keyStore.size()));
<ide> ehcache.put(cacheElement);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("new SSL Context created, {} millis since method start",
<add> Duration.between(start, Instant.now()).toMillis());
<add> }
<ide> }
<ide> }
<ide> }
<ide> private static SSLContextBuilder createSSLContextBuilder(final KeyStore keyStore, final String ksPass,
<ide> final PrivateKeyStrategy keyStrategy, final KeyStore trustStore, TrustStrategy trustStrategy)
<ide> throws Exception {
<add> Instant start = Instant.now();
<ide> SSLContextBuilder contextBuilder = SSLContexts.custom();
<ide> contextBuilder.loadKeyMaterial(keyStore, ksPass.toCharArray(), keyStrategy);
<ide> // if trustStore is null, default CAs trust store is used
<ide> contextBuilder.loadTrustMaterial(trustStore, trustStrategy);
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Loaded key material in {} millis", Duration.between(start, Instant.now()).toMillis());
<add> }
<ide> return contextBuilder;
<ide> }
<ide> |
|
Java | agpl-3.0 | e519c4070406c842819bacef94c1dea3c6cc1903 | 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 | 5f1a345a-2e60-11e5-9284-b827eb9e62be | hello.java | 5f14b674-2e60-11e5-9284-b827eb9e62be | 5f1a345a-2e60-11e5-9284-b827eb9e62be | hello.java | 5f1a345a-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>5f14b674-2e60-11e5-9284-b827eb9e62be
<add>5f1a345a-2e60-11e5-9284-b827eb9e62be |
|
Java | mit | cd7c9d2e8881746a9eb5e1eac6788c6e0c9c5a71 | 0 | joshvinson/regexerator | package rxr;
import java.awt.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.Highlighter.HighlightPainter;
import rxr.RegexEventListener.Type;
import rxr.ext.*;
/**
* RegexFieldListener listens for changes in a Document, and reapplies a regular
* expression whenever a change occurs.
*
*/
class RegexFieldListener implements DocumentListener
{
protected JTextField source;
protected JTextPane target;
protected JTextField replaceSource;
protected JTextPane replaceTarget;
protected HashSet<RegexEventListener> listeners;
protected Color highlightColor = new Color(255, 230, 0, 128);
protected Color selectColor = new Color(128, 0, 255, 128);
protected ArrayList<int[]> matches;
protected ArrayList<int[][]> groups;
protected ArrayList<Color[]> groupColors;
protected boolean autoRecalc = true;
boolean doReplace = false;
protected Object selectHighlightHandle;
/**
* Creates a RegexFieldListener that takes a regex from source, and applies
* it to target.
*
* @param source
* the component to get the regex string from
* @param target
* the component to apply the regex to
*/
public RegexFieldListener(JTextField source, JTextPane target, JTextField replaceSource, JTextPane replaceTarget)
{
this.source = source;
this.target = target;
this.replaceSource = replaceSource;
this.replaceTarget = replaceTarget;
listeners = new HashSet<RegexEventListener>();
}
/**
* Grabs a regex string from the source component, attempts to compile it,
* and call recalcTarget(). At least regex events will be sent to listeners
* during the execution of this method: RECALC_START at the beginning, and
* either BAD_PATTERN or RECALC_COMPLETE depending on the result.
*/
public void regex()
{
fireRegexEvent(Type.RECALC_START);
final String regex = source.getText();
if(regex.equals(""))
{
//reset target
recalcTarget(null);
//not doing any matching, but we know the result of the replace, so just do that.
replaceTarget.setText(target.getText());
return;
}
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(target.getDocument().getText(0, target.getDocument().getLength()));
recalcTarget(m);
}
catch(Exception e)
{
recalcTarget(null);
replaceTarget.setText(target.getText());
fireRegexEvent(Type.BAD_PATTERN);
return;
}
}
});
}
/**
* Changes the specific highlight on the target document. This will show up
* as a different color than the highlighting for each match.
*
* @param start
* the start index in the target document
* @param end
* the end index in the target document
*/
public void setOutlineRange(int start, int end)
{
Highlighter h = target.getHighlighter();
if(selectHighlightHandle == null)
{
//HighlightPainter ohp = new OutlineHighlighter(Color.BLACK).getPainter();
HighlightPainter hp = new DefaultHighlighter.DefaultHighlightPainter(selectColor);
try
{
selectHighlightHandle = h.addHighlight(start, end, hp);
}
catch(Exception e)
{
//
}
}
else
{
try
{
h.changeHighlight(selectHighlightHandle, start, end);
}
catch(Exception e)
{
//
}
}
}
/**
* Recalculate the matches, groups, and groupColors lists based on the data
* in m. Matches and groups are calculated from m by removing group 0 and
* making that the match for that match number. The groups list is
* zero-indexed, starting with the 1st, not 0th group.
*
* @param m
* the Matcher object to get match and group data from
*/
protected void recalcTarget(Matcher m)
{
selectHighlightHandle = null;
Highlighter h = target.getHighlighter();
//remove formatting
try
{
h.removeAllHighlights();
}
catch(Exception e)
{
return;
}
if(m == null)
{
fireRegexEvent(Type.RECALC_COMPLETE);
return;
}
matches = new ArrayList<int[]>();
groups = new ArrayList<int[][]>();
groupColors = new ArrayList<Color[]>();
StringBuffer replaceSB = new StringBuffer();
String replaceStr = replaceSource.getText();
while(m.find())
{
int groupCount = m.groupCount();
//grab 0th group (whole match)
matches.add(new int[] {m.start(), m.end()});
int[][] current = new int[groupCount][];
Color[] ccolors = new Color[groupCount];
for(int i = 0; i < groupCount; i++)
{
ccolors[i] = Color.getHSBColor(i / (float)groupCount, 1f, 1f);
current[i] = new int[] {m.start(i + 1), m.end(i + 1)};
}
groups.add(current);
groupColors.add(ccolors);
if(doReplace)
{
m.appendReplacement(replaceSB, replaceStr);
}
}
m.appendTail(replaceSB);
replaceTarget.setText(replaceSB.toString());
doHighlight();
fireRegexEvent(Type.RECALC_COMPLETE);
}
/**
* Applies the match and group data from matches, groups, and groupColors to
* the target document.
*/
private void doHighlight()
{
Highlighter h = target.getHighlighter();
HighlightPainter hp = new DefaultHighlighter.DefaultHighlightPainter(highlightColor);
for(int i = 0; i < matches.size(); i++)
{
int[][] gs = groups.get(i);
Color[] cs = groupColors.get(i);
for(int j = 0; j < gs.length; j++)
{
try
{
HighlightPainter ghp = new UnderlineHighlighter(cs[j]).getPainter();
h.addHighlight(gs[j][0], gs[j][1], ghp);
}
catch(Exception e)
{
e.printStackTrace();
return;
}
}
try
{
h.addHighlight(matches.get(i)[0], matches.get(i)[1], hp);
}
catch(Exception e)
{
e.printStackTrace();
return;
}
}
}
/**
* Notifies all listeners of a regex event.
*
* @param t
* the type of regex event to send
*/
protected void fireRegexEvent(RegexEventListener.Type t)
{
for(RegexEventListener rel : listeners)
{
rel.regexEvent(t);
}
}
@Override
public void changedUpdate(DocumentEvent e)
{
//do nothing
}
@Override
public void insertUpdate(DocumentEvent e)
{
if(autoRecalc)
{
regex();
}
}
@Override
public void removeUpdate(DocumentEvent e)
{
if(autoRecalc)
{
regex();
}
}
/**
* @return the source component
*/
public JTextField getSource()
{
return source;
}
public void setSource(JTextField source)
{
this.source = source;
}
/**
* @return the target component
*/
public JTextPane getTarget()
{
return target;
}
public void setTarget(JTextPane target)
{
this.target = target;
}
/**
* @return if the regex is automatically reapplied on changes to the regex
* or target document
*/
public boolean isAutoRecalc()
{
return autoRecalc;
}
public void setAutoRecalc(boolean autoRecalc)
{
this.autoRecalc = autoRecalc;
}
/**
* @return a list of whole regex matches from the last calculated match
*/
public ArrayList<int[]> getMatches()
{
return matches;
}
/**
* @return a list of each set of groups from the last calculated match
*/
public ArrayList<int[][]> getGroups()
{
return groups;
}
/**
* @return a list of each set of colors used for each group
*/
public ArrayList<Color[]> getGroupColors()
{
return groupColors;
}
public boolean addListener(RegexEventListener e)
{
return listeners.add(e);
}
public boolean removeListener(RegexEventListener e)
{
return listeners.remove(e);
}
public JTextPane getReplaceTarget()
{
return replaceTarget;
}
public void setReplaceTarget(JTextPane replaceTarget)
{
this.replaceTarget = replaceTarget;
}
public boolean isDoReplace()
{
return doReplace;
}
public void setDoReplace(boolean doReplace)
{
this.doReplace = doReplace;
}
} | src/rxr/RegexFieldListener.java | package rxr;
import java.awt.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.Highlighter.HighlightPainter;
import rxr.RegexEventListener.Type;
import rxr.ext.*;
/**
* RegexFieldListener listens for changes in a Document, and reapplies a regular
* expression whenever a change occurs.
*
*/
class RegexFieldListener implements DocumentListener
{
protected JTextField source;
protected JTextPane target;
protected JTextField replaceSource;
protected JTextPane replaceTarget;
protected HashSet<RegexEventListener> listeners;
protected Color highlightColor = new Color(255, 230, 0, 128);
protected Color selectColor = new Color(128, 0, 255, 128);
protected ArrayList<int[]> matches;
protected ArrayList<int[][]> groups;
protected ArrayList<Color[]> groupColors;
protected boolean autoRecalc = true;
boolean doReplace = false;
protected Object selectHighlightHandle;
/**
* Creates a RegexFieldListener that takes a regex from source, and applies
* it to target.
*
* @param source
* the component to get the regex string from
* @param target
* the component to apply the regex to
*/
public RegexFieldListener(JTextField source, JTextPane target, JTextField replaceSource, JTextPane replaceTarget)
{
this.source = source;
this.target = target;
this.replaceSource = replaceSource;
this.replaceTarget = replaceTarget;
listeners = new HashSet<RegexEventListener>();
}
/**
* Grabs a regex string from the source component, attempts to compile it,
* and call recalcTarget(). At least regex events will be sent to listeners
* during the execution of this method: RECALC_START at the beginning, and
* either BAD_PATTERN or RECALC_COMPLETE depending on the result.
*/
public void regex()
{
fireRegexEvent(Type.RECALC_START);
final String regex = source.getText();
if(regex.equals(""))
{
//reset target
recalcTarget(null);
//not doing any matching, but we know the result of the replace, so just do that.
replaceTarget.setText(target.getText());
return;
}
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(target.getDocument().getText(0, target.getDocument().getLength()));
recalcTarget(m);
}
catch(Exception e)
{
recalcTarget(null);
fireRegexEvent(Type.BAD_PATTERN);
return;
}
}
});
}
/**
* Changes the specific highlight on the target document. This will show up
* as a different color than the highlighting for each match.
*
* @param start
* the start index in the target document
* @param end
* the end index in the target document
*/
public void setOutlineRange(int start, int end)
{
Highlighter h = target.getHighlighter();
if(selectHighlightHandle == null)
{
//HighlightPainter ohp = new OutlineHighlighter(Color.BLACK).getPainter();
HighlightPainter hp = new DefaultHighlighter.DefaultHighlightPainter(selectColor);
try
{
selectHighlightHandle = h.addHighlight(start, end, hp);
}
catch(Exception e)
{
//
}
}
else
{
try
{
h.changeHighlight(selectHighlightHandle, start, end);
}
catch(Exception e)
{
//
}
}
}
/**
* Recalculate the matches, groups, and groupColors lists based on the data
* in m. Matches and groups are calculated from m by removing group 0 and
* making that the match for that match number. The groups list is
* zero-indexed, starting with the 1st, not 0th group.
*
* @param m
* the Matcher object to get match and group data from
*/
protected void recalcTarget(Matcher m)
{
selectHighlightHandle = null;
Highlighter h = target.getHighlighter();
//remove formatting
try
{
h.removeAllHighlights();
}
catch(Exception e)
{
return;
}
if(m == null)
{
fireRegexEvent(Type.RECALC_COMPLETE);
return;
}
matches = new ArrayList<int[]>();
groups = new ArrayList<int[][]>();
groupColors = new ArrayList<Color[]>();
StringBuffer replaceSB = new StringBuffer();
String replaceStr = replaceSource.getText();
while(m.find())
{
int groupCount = m.groupCount();
//grab 0th group (whole match)
matches.add(new int[] {m.start(), m.end()});
int[][] current = new int[groupCount][];
Color[] ccolors = new Color[groupCount];
for(int i = 0; i < groupCount; i++)
{
ccolors[i] = Color.getHSBColor(i / (float)groupCount, 1f, 1f);
current[i] = new int[] {m.start(i + 1), m.end(i + 1)};
}
groups.add(current);
groupColors.add(ccolors);
if(doReplace)
{
m.appendReplacement(replaceSB, replaceStr);
}
}
m.appendTail(replaceSB);
replaceTarget.setText(replaceSB.toString());
doHighlight();
fireRegexEvent(Type.RECALC_COMPLETE);
}
/**
* Applies the match and group data from matches, groups, and groupColors to
* the target document.
*/
private void doHighlight()
{
Highlighter h = target.getHighlighter();
HighlightPainter hp = new DefaultHighlighter.DefaultHighlightPainter(highlightColor);
for(int i = 0; i < matches.size(); i++)
{
int[][] gs = groups.get(i);
Color[] cs = groupColors.get(i);
for(int j = 0; j < gs.length; j++)
{
try
{
HighlightPainter ghp = new UnderlineHighlighter(cs[j]).getPainter();
h.addHighlight(gs[j][0], gs[j][1], ghp);
}
catch(Exception e)
{
e.printStackTrace();
return;
}
}
try
{
h.addHighlight(matches.get(i)[0], matches.get(i)[1], hp);
}
catch(Exception e)
{
e.printStackTrace();
return;
}
}
}
/**
* Notifies all listeners of a regex event.
*
* @param t
* the type of regex event to send
*/
protected void fireRegexEvent(RegexEventListener.Type t)
{
for(RegexEventListener rel : listeners)
{
rel.regexEvent(t);
}
}
@Override
public void changedUpdate(DocumentEvent e)
{
//do nothing
}
@Override
public void insertUpdate(DocumentEvent e)
{
if(autoRecalc)
{
regex();
}
}
@Override
public void removeUpdate(DocumentEvent e)
{
if(autoRecalc)
{
regex();
}
}
/**
* @return the source component
*/
public JTextField getSource()
{
return source;
}
public void setSource(JTextField source)
{
this.source = source;
}
/**
* @return the target component
*/
public JTextPane getTarget()
{
return target;
}
public void setTarget(JTextPane target)
{
this.target = target;
}
/**
* @return if the regex is automatically reapplied on changes to the regex
* or target document
*/
public boolean isAutoRecalc()
{
return autoRecalc;
}
public void setAutoRecalc(boolean autoRecalc)
{
this.autoRecalc = autoRecalc;
}
/**
* @return a list of whole regex matches from the last calculated match
*/
public ArrayList<int[]> getMatches()
{
return matches;
}
/**
* @return a list of each set of groups from the last calculated match
*/
public ArrayList<int[][]> getGroups()
{
return groups;
}
/**
* @return a list of each set of colors used for each group
*/
public ArrayList<Color[]> getGroupColors()
{
return groupColors;
}
public boolean addListener(RegexEventListener e)
{
return listeners.add(e);
}
public boolean removeListener(RegexEventListener e)
{
return listeners.remove(e);
}
public JTextPane getReplaceTarget()
{
return replaceTarget;
}
public void setReplaceTarget(JTextPane replaceTarget)
{
this.replaceTarget = replaceTarget;
}
public boolean isDoReplace()
{
return doReplace;
}
public void setDoReplace(boolean doReplace)
{
this.doReplace = doReplace;
}
} | minor bug fixes with replace
| src/rxr/RegexFieldListener.java | minor bug fixes with replace | <ide><path>rc/rxr/RegexFieldListener.java
<ide> catch(Exception e)
<ide> {
<ide> recalcTarget(null);
<add> replaceTarget.setText(target.getText());
<ide> fireRegexEvent(Type.BAD_PATTERN);
<ide> return;
<ide> } |
|
Java | bsd-3-clause | 862b20675eb1f9acb4d517f3c090954cfd2a6384 | 0 | bhomberg/frc-2010-1100,mbh1100/frc-2010-1100 |
package team1100.season2010.robot;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.PIDController;
/**
*
* @author mark
*/
public class SteeringPID {
final double kLinearPct = 2.0;
final double kPidI = 0.01;
final double kPidD = 0.0;
final int kOperatingRangePct = 20;
final int kCenterPct = 50;
final double kInChannelMin = 0.0;
final double kInChannelMax = 1000.0;
final double kInWidth = kInChannelMax - kInChannelMin;
final double kOutChannelMin = -1.0;
final double kOutChannelMax = 1.0;
PIDSource m_in;
PIDOutput m_out;
PIDController m_pid;
PIDOutput m_scaledOut;
int m_opRangePct = 20;
double m_operatingRange;
double m_rangeCenterPct = 50.0;
double m_rangeCenter;
double m_linearPct;
double m_PidP;
boolean m_running = false;
double m_PidI = kPidI;
double m_PidD = kPidD;
/**
* Construct a SteeringPID using default module slots
* @param inputChannel - channel on the default analog input module
* connected to the sensing potentiometer for this device.
* @param outputChannel - channel on the default digital output module
* connected to the motor controller for this device.
* @param invertOutput - invert the polarity of the output value.
*/
public SteeringPID(int inputChannel, int outputChannel, boolean invertOutput)
{
this(AnalogChannel.getDefaultAnalogModule(), inputChannel,
Jaguar.getDefaultDigitalModule(), outputChannel,
invertOutput);
}
/**
* Construct a SteeringPID
* @param inputSlot - cRIO slot hosting the analog input module used for
* this device.
* @param inputChannel - channel on the selected analog module connected to
* the sensing potentiometer for this device.
* @param outputSlot - cRIO slot hosting the digital output module used for
* this device.
* @param outputChannel - channel on the selected digital module connected
* to the motor controller for this device.
* @param invertOutput - invert the polarity of the output value.
*/
public SteeringPID(int inputSlot, int inputChannel,
int outputSlot, int outputChannel, boolean invertOutput)
{
m_in = new AnalogChannel(inputSlot, inputChannel);
m_out = new Jaguar(outputSlot, outputChannel);
m_scaledOut = new PIDOutputInverter(m_out, invertOutput);
m_pid = new PIDController(m_PidP, m_PidI, m_PidD, m_in, m_scaledOut);
m_pid.setOutputRange(kOutChannelMin, kOutChannelMax);
setOperatingRangePct(kOperatingRangePct);
setCenterPct(kCenterPct);
setLinearPct(kLinearPct);
}
/**
* Specify the portion of the input range where the PIDController operates
* in a linear (output not clipped) fashion. This is a percentage of the
* entire range of input values; it is not affected by changes to the
* operating range.
*/
public void setLinearPct(double pct)
{
m_linearPct = pct/100;
// initially compute P so the motor input is linear over the whole input range
m_PidP = (kOutChannelMax - kOutChannelMin)/(kInChannelMax - kInChannelMin);
// increase P so the motor input reaches its limit at m_linearPct/2 from the center
m_PidP /= m_linearPct;
// update the PIDController
m_pid.setPID(m_PidP, m_PidI, m_PidD);
}
/**
* Specify the portion of the input range in use.
* @param width - percent of input range to use
*/
public void setOperatingRangePct(int widthPct)
{
// ignore invalid input
if (widthPct > 100 || widthPct < 0) return;
if (m_rangeCenterPct + widthPct/2 > 100) return;
if (m_rangeCenterPct - widthPct/2 < 0) return;
m_opRangePct = widthPct;
m_operatingRange = kInWidth * widthPct / 100;
}
/**
* Specify the midpoint of the operating range as a percent of the input range.
* @param centerPct - the target value, as a percent of the input range, when
* the direction is centered (direction is 0);
*
*/
public void setCenterPct(double centerPct)
{
// ignore invalid input
if (centerPct > 100 || centerPct < 0) return;
if (centerPct + m_opRangePct/2 > 100) return;
if (centerPct - m_opRangePct/2 < 0) return;
m_rangeCenterPct = centerPct;
m_rangeCenter = kInWidth * centerPct / 100.0;
}
public void setI(double i)
{
m_PidI = i;
m_pid.setPID(m_PidP, m_PidI, m_PidD);
}
public void setD(double d)
{
m_PidD = d;
m_pid.setPID(m_PidP, m_PidI, m_PidD);
}
/**
* Set the steering direction. The direction input is mapped onto the
* operating range of the steering device. When the specified direction
* is zero, the steering device will find the specified center.
* @param Desired steering direction, range is -1.0 to +1.0
*/
public void setDirection(double direction)
{
m_pid.setSetpoint((direction * m_operatingRange/2) + m_rangeCenter);
if (!m_running)
{
m_pid.enable();
m_running = true;
}
/*
/ System.out.println("PID Error: " + m_pid.getError() +
"; Result: " + m_pid.get() +
"; Setpoint: " + m_pid.getSetpoint() +
"; Joystick: " + direction +
"; Input: " + m_in.pidGet() +
"; P: " + m_pid.getP() +
"; I: " + m_pid.getI() +
"; D: " + m_pid.getD() +
"; width: " + m_operatingRange +
"; center: " + m_rangeCenter);
*
*/
}
}
| src/team1100/season2010/robot/SteeringPID.java |
package team1100.season2010.robot;
import edu.wpi.first.wpilibj.AnalogChannel;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.PIDController;
/**
*
* @author mark
*/
public class SteeringPID {
final double kLinearPct = 2.0;
final double kPidI = 0.001;
final double kPidD = 0.0;
final int kOperatingRangePct = 20;
final int kCenterPct = 50;
final double kInChannelMin = 0.0;
final double kInChannelMax = 1000.0;
final double kInWidth = kInChannelMax - kInChannelMin;
final double kOutChannelMin = -1.0;
final double kOutChannelMax = 1.0;
PIDSource m_in;
PIDOutput m_out;
PIDController m_pid;
PIDOutput m_scaledOut;
int m_opRangePct = 20;
double m_operatingRange;
int m_rangeCenterPct = 50;
double m_rangeCenter;
double m_linearPct;
double m_PidP;
boolean m_running = false;
double m_PidI = kPidI;
double m_PidD = kPidD;
/**
* Construct a SteeringPID using default module slots
* @param inputChannel - channel on the default analog input module
* connected to the sensing potentiometer for this device.
* @param outputChannel - channel on the default digital output module
* connected to the motor controller for this device.
* @param invertOutput - invert the polarity of the output value.
*/
public SteeringPID(int inputChannel, int outputChannel, boolean invertOutput)
{
this(AnalogChannel.getDefaultAnalogModule(), inputChannel,
Jaguar.getDefaultDigitalModule(), outputChannel,
invertOutput);
}
/**
* Construct a SteeringPID
* @param inputSlot - cRIO slot hosting the analog input module used for
* this device.
* @param inputChannel - channel on the selected analog module connected to
* the sensing potentiometer for this device.
* @param outputSlot - cRIO slot hosting the digital output module used for
* this device.
* @param outputChannel - channel on the selected digital module connected
* to the motor controller for this device.
* @param invertOutput - invert the polarity of the output value.
*/
public SteeringPID(int inputSlot, int inputChannel,
int outputSlot, int outputChannel, boolean invertOutput)
{
m_in = new AnalogChannel(inputSlot, inputChannel);
m_out = new Jaguar(outputSlot, outputChannel);
m_scaledOut = new PIDOutputInverter(m_out, invertOutput);
m_pid = new PIDController(m_PidP, m_PidI, m_PidD, m_in, m_scaledOut);
m_pid.setOutputRange(kOutChannelMin, kOutChannelMax);
setOperatingRangePct(kOperatingRangePct);
setCenterPct(kCenterPct);
setLinearPct(kLinearPct);
}
/**
* Specify the portion of the input range where the PIDController operates
* in a linear (output not clipped) fashion. This is a percentage of the
* entire range of input values; it is not affected by changes to the
* operating range.
*/
public void setLinearPct(double pct)
{
m_linearPct = pct/100;
// initially compute P so the motor input is linear over the whole input range
m_PidP = (kOutChannelMax - kOutChannelMin)/(kInChannelMax - kInChannelMin);
// increase P so the motor input reaches its limit at m_linearPct/2 from the center
m_PidP /= m_linearPct;
// update the PIDController
m_pid.setPID(m_PidP, m_PidI, m_PidD);
}
/**
* Specify the portion of the input range in use.
* @param width - percent of input range to use
*/
public void setOperatingRangePct(int widthPct)
{
// ignore invalid input
if (widthPct > 100 || widthPct < 0) return;
if (m_rangeCenterPct + widthPct/2 > 100) return;
if (m_rangeCenterPct - widthPct/2 < 0) return;
m_opRangePct = widthPct;
m_operatingRange = kInWidth * widthPct / 100;
}
/**
* Specify the midpoint of the operating range as a percent of the input range.
* @param centerPct - the target value, as a percent of the input range, when
* the direction is centered (direction is 0);
*
*/
public void setCenterPct(int centerPct)
{
// ignore invalid input
if (centerPct > 100 || centerPct < 0) return;
if (centerPct + m_opRangePct/2 > 100) return;
if (centerPct - m_opRangePct/2 < 0) return;
m_rangeCenterPct = centerPct;
m_rangeCenter = kInWidth * centerPct / 100;
}
public void setI(double i)
{
m_PidI = i;
m_pid.setPID(m_PidP, m_PidI, m_PidD);
}
public void setD(double d)
{
m_PidD = d;
m_pid.setPID(m_PidP, m_PidI, m_PidD);
}
/**
* Set the steering direction. The direction input is mapped onto the
* operating range of the steering device. When the specified direction
* is zero, the steering device will find the specified center.
* @param Desired steering direction, range is -1.0 to +1.0
*/
public void setDirection(double direction)
{
m_pid.setSetpoint((direction * m_operatingRange/2) + m_rangeCenter);
if (!m_running)
{
m_pid.enable();
m_running = true;
}
System.out.println("PID Error: " + m_pid.getError() +
"; Result: " + m_pid.get() +
"; Setpoint: " + m_pid.getSetpoint() +
"; Joystick: " + direction +
"; Input: " + m_in.pidGet() +
"; P: " + m_pid.getP() +
"; I: " + m_pid.getI() +
"; D: " + m_pid.getD() +
"; width: " + m_operatingRange +
"; center: " + m_rangeCenter);
}
}
| centerPct is now double, I defaults to .01 | src/team1100/season2010/robot/SteeringPID.java | centerPct is now double, I defaults to .01 | <ide><path>rc/team1100/season2010/robot/SteeringPID.java
<ide> public class SteeringPID {
<ide>
<ide> final double kLinearPct = 2.0;
<del> final double kPidI = 0.001;
<add> final double kPidI = 0.01;
<ide> final double kPidD = 0.0;
<ide> final int kOperatingRangePct = 20;
<ide> final int kCenterPct = 50;
<ide>
<ide> int m_opRangePct = 20;
<ide> double m_operatingRange;
<del> int m_rangeCenterPct = 50;
<add> double m_rangeCenterPct = 50.0;
<ide> double m_rangeCenter;
<ide> double m_linearPct;
<ide> double m_PidP;
<ide> * the direction is centered (direction is 0);
<ide> *
<ide> */
<del> public void setCenterPct(int centerPct)
<add> public void setCenterPct(double centerPct)
<ide> {
<ide> // ignore invalid input
<ide> if (centerPct > 100 || centerPct < 0) return;
<ide> if (centerPct - m_opRangePct/2 < 0) return;
<ide>
<ide> m_rangeCenterPct = centerPct;
<del> m_rangeCenter = kInWidth * centerPct / 100;
<add> m_rangeCenter = kInWidth * centerPct / 100.0;
<ide> }
<ide>
<ide> public void setI(double i)
<ide> m_running = true;
<ide> }
<ide>
<del> System.out.println("PID Error: " + m_pid.getError() +
<add> /*
<add> / System.out.println("PID Error: " + m_pid.getError() +
<ide> "; Result: " + m_pid.get() +
<ide> "; Setpoint: " + m_pid.getSetpoint() +
<ide> "; Joystick: " + direction +
<ide> "; D: " + m_pid.getD() +
<ide> "; width: " + m_operatingRange +
<ide> "; center: " + m_rangeCenter);
<add> *
<add> */
<ide>
<ide> }
<ide> } |
|
Java | agpl-3.0 | 9b212ff1717530090c5172858efd9d331ed919da | 0 | The4thLaw/demyo,The4thLaw/demyo,The4thLaw/demyo,The4thLaw/demyo | package org.demyo.desktop;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.h2.engine.ConnectionInfo;
import org.h2.engine.Constants;
import org.h2.jdbc.JdbcConnection;
import org.h2.util.IOUtils;
import org.h2.util.StringUtils;
import org.demyo.common.config.SystemConfiguration;
import org.demyo.common.exception.DemyoErrorCode;
import org.demyo.common.exception.DemyoRuntimeException;
/**
* Heavily inspired by {@link org.h2.tools.Upgrade}, but relying on a local repository of libraries instead, and solving
* some file access lock issues.
* <p>
* The base Upgrade tool is Copyright 2004-2022 H2 Group. Multiple-Licensed under the MPL 2.0, and the EPL 1.0
* (https://h2database.com/html/license.html).
* </p>
*/
public class H2LocalUpgrade {
/**
* Performs database upgrade from an older version of H2.
*
* @param url the JDBC connection URL
* @param info the connection properties ("user", "password", etc).
* @param version the old version of H2
* @return {@code true} on success, {@code false} if URL is a remote or in-memory URL
* @throws SQLException on failure
* @throws IOException on failure
* @throws ReflectiveOperationException on failure
*/
public static boolean upgrade(String url, Properties info, int version)
throws SQLException, IOException, ReflectiveOperationException {
Properties oldInfo = new Properties();
oldInfo.putAll(info);
Object password = info.get("password");
if (password instanceof char[]) {
oldInfo.put("password", ((char[]) password).clone());
}
ConnectionInfo ci = new ConnectionInfo(url, info, null, null);
if (!ci.isPersistent() || ci.isRemote()) {
return false;
}
String name = ci.getName();
// Copy the database to work on a specific version: file locks will sometimes not be released, causing migration
// issues
String workingCopyName = ci.getName() + "-migration";
copy(name, workingCopyName);
String script = name + ".script.sql";
StringBuilder oldUrl = new StringBuilder("jdbc:h2:").append(workingCopyName).append(";ACCESS_MODE_DATA=r");
copyProperty(ci, oldUrl, "FILE_LOCK");
copyProperty(ci, oldUrl, "MV_STORE");
String cipher = copyProperty(ci, oldUrl, "CIPHER");
String scriptCommandSuffix = cipher == null ? "" : " CIPHER AES PASSWORD '" + UUID.randomUUID() + "' --hide--";
java.sql.Driver driver = loadH2(version);
try (Connection conn = driver.connect(oldUrl.toString(), oldInfo); Statement stmt = conn.createStatement()) {
stmt.execute(StringUtils.quoteStringSQL(new StringBuilder("SCRIPT TO "), script)
.append(scriptCommandSuffix).toString());
} finally {
unloadH2(driver);
}
rename(name, false);
try (JdbcConnection conn = new JdbcConnection(url, info, null, null, false);
Statement stmt = conn.createStatement()) {
StringBuilder builder = StringUtils.quoteStringSQL(new StringBuilder("RUNSCRIPT FROM "), script)
.append(scriptCommandSuffix);
if (version <= 200) {
builder.append(" FROM_1X");
}
stmt.execute(builder.toString());
} catch (Throwable t) {
rename(name, true);
throw t;
} finally {
Files.deleteIfExists(Paths.get(script));
// We delete the working copy but keep the backup just in case
Path workingMv = Path.of(workingCopyName + Constants.SUFFIX_MV_FILE);
Path workingLob = Path.of(workingCopyName + ".lobs.db");
try {
Files.deleteIfExists(workingMv);
Files.deleteIfExists(workingLob);
} catch (IOException e) {
// Do nothing, it's not a big deal
workingMv.toFile().deleteOnExit();
workingLob.toFile().deleteOnExit();
}
}
return true;
}
private static void rename(String name, boolean back) throws IOException {
rename(name, Constants.SUFFIX_MV_FILE, back);
rename(name, ".lobs.db", back);
}
private static void rename(String name, String suffix, boolean back) throws IOException {
String source = name + suffix;
String target = source + ".bak";
if (back) {
String t = source;
source = target;
target = t;
}
Path p = Paths.get(source);
if (Files.exists(p)) {
Files.move(p, Paths.get(target), StandardCopyOption.ATOMIC_MOVE);
}
}
private static void copy(String source, String target) throws IOException {
copy(source, target, Constants.SUFFIX_MV_FILE);
copy(source, target, ".lobs.db");
}
private static void copy(String source, String target, String suffix) throws IOException {
Path sourcePath = Path.of(source + suffix);
Path targetPath = Path.of(target + suffix);
if (Files.exists(sourcePath)) {
Files.copy(sourcePath, targetPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
}
}
private static String copyProperty(ConnectionInfo ci, StringBuilder oldUrl, String name) {
try {
String value = ci.getProperty(name, null);
if (value != null) {
oldUrl.append(';').append(name).append('=').append(value);
}
return value;
} catch (Exception e) {
return null;
}
}
/**
* Loads the specified version of H2 in a separate class loader.
*
* @param version the version to load
* @return the driver of the specified version
* @throws IOException on I/O exception
* @throws ReflectiveOperationException on exception during initialization of the driver
*/
public static java.sql.Driver loadH2(int version) throws IOException, ReflectiveOperationException {
String prefix;
if (version >= 201) {
if ((version & 1) != 0 || version > Constants.BUILD_ID) {
throw new IllegalArgumentException("version=" + version);
}
prefix = "2.0.";
} else if (version >= 177) {
prefix = "1.4.";
} else if (version >= 146 && version != 147) {
prefix = "1.3.";
} else if (version >= 120) {
prefix = "1.2.";
} else {
throw new IllegalArgumentException("version=" + version);
}
String fullVersion = prefix + version;
byte[] data = loadFromDisk(fullVersion);
ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(data));
HashMap<String, byte[]> map = new HashMap<>(version >= 198 ? 2048 : 1024);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (ZipEntry ze; (ze = is.getNextEntry()) != null;) {
if (ze.isDirectory()) {
continue;
}
IOUtils.copy(is, baos);
map.put(ze.getName(), baos.toByteArray());
baos.reset();
}
ClassLoader cl = new ClassLoader(null) {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String resourceName = name.replace('.', '/') + ".class";
byte[] b = map.get(resourceName);
if (b == null) {
return ClassLoader.getSystemClassLoader().loadClass(name);
}
return defineClass(name, b, 0, b.length);
}
@Override
public InputStream getResourceAsStream(String name) {
byte[] b = map.get(name);
return b != null ? new ByteArrayInputStream(b) : null;
}
};
return (java.sql.Driver) cl.loadClass("org.h2.Driver").getDeclaredMethod("load").invoke(null);
}
private static byte[] loadFromDisk(String fullVersion) {
String h2cacheProperty = System.getProperty("demyo.h2.cacheDirectoryName", "legacy-h2-versions");
Path h2CacheDirectory = SystemConfiguration.getInstance().getApplicationDirectory()
.resolve(h2cacheProperty);
Path h2Jar = h2CacheDirectory.resolve("h2-" + fullVersion + ".jar");
if (!Files.isReadable(h2Jar)) {
throw new DemyoRuntimeException(DemyoErrorCode.SYS_MISSING_H2_FOR_MIGRATION, "No file at " + h2Jar);
}
try {
return Files.readAllBytes(h2Jar);
} catch (IOException e) {
throw new DemyoRuntimeException(DemyoErrorCode.SYS_MISSING_H2_FOR_MIGRATION, e,
"Failed to read the file at " + h2Jar);
}
}
/**
* Unloads the specified driver of H2.
*
* @param driver the driver to unload
* @throws ReflectiveOperationException on exception
*/
public static void unloadH2(java.sql.Driver driver) throws ReflectiveOperationException {
driver.getClass().getDeclaredMethod("unload").invoke(null);
}
private H2LocalUpgrade() {
}
}
| source/demyo-app/src/main/java/org/demyo/desktop/H2LocalUpgrade.java | package org.demyo.desktop;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.h2.engine.ConnectionInfo;
import org.h2.engine.Constants;
import org.h2.jdbc.JdbcConnection;
import org.h2.util.IOUtils;
import org.h2.util.StringUtils;
import org.demyo.common.config.SystemConfiguration;
import org.demyo.common.exception.DemyoErrorCode;
import org.demyo.common.exception.DemyoRuntimeException;
/**
* Heavily inspired by {@link org.h2.tools.Upgrade}, but relying on a local repository of libraries instead, and solving
* some file access lock issues.
* <p>
* The base Upgrade tool is Copyright 2004-2022 H2 Group. Multiple-Licensed under the MPL 2.0, and the EPL 1.0
* (https://h2database.com/html/license.html).
* </p>
*/
public class H2LocalUpgrade {
/**
* Performs database upgrade from an older version of H2.
*
* @param url the JDBC connection URL
* @param info the connection properties ("user", "password", etc).
* @param version the old version of H2
* @return {@code true} on success, {@code false} if URL is a remote or in-memory URL
* @throws SQLException on failure
* @throws IOException on failure
* @throws ReflectiveOperationException on failure
*/
public static boolean upgrade(String url, Properties info, int version)
throws SQLException, IOException, ReflectiveOperationException {
Properties oldInfo = new Properties();
oldInfo.putAll(info);
Object password = info.get("password");
if (password instanceof char[]) {
oldInfo.put("password", ((char[]) password).clone());
}
ConnectionInfo ci = new ConnectionInfo(url, info, null, null);
if (!ci.isPersistent() || ci.isRemote()) {
return false;
}
String name = ci.getName();
// Copy the database to work on a specific version: file locks will sometimes not be released, causing migration
// issues
String workingCopyName = ci.getName() + "-migration";
copy(name, workingCopyName);
String script = name + ".script.sql";
StringBuilder oldUrl = new StringBuilder("jdbc:h2:").append(workingCopyName).append(";ACCESS_MODE_DATA=r");
copyProperty(ci, oldUrl, "FILE_LOCK");
copyProperty(ci, oldUrl, "MV_STORE");
String cipher = copyProperty(ci, oldUrl, "CIPHER");
String scriptCommandSuffix = cipher == null ? "" : " CIPHER AES PASSWORD '" + UUID.randomUUID() + "' --hide--";
java.sql.Driver driver = loadH2(version);
try (Connection conn = driver.connect(oldUrl.toString(), oldInfo)) {
conn.createStatement().execute(StringUtils.quoteStringSQL(new StringBuilder("SCRIPT TO "), script)
.append(scriptCommandSuffix).toString());
} finally {
unloadH2(driver);
}
rename(name, false);
try (JdbcConnection conn = new JdbcConnection(url, info, null, null, false)) {
StringBuilder builder = StringUtils.quoteStringSQL(new StringBuilder("RUNSCRIPT FROM "), script)
.append(scriptCommandSuffix);
if (version <= 200) {
builder.append(" FROM_1X");
}
conn.createStatement().execute(builder.toString());
} catch (Throwable t) {
rename(name, true);
throw t;
} finally {
Files.deleteIfExists(Paths.get(script));
// We delete the working copy but keep the backup just in case
Path workingMv = Path.of(workingCopyName + Constants.SUFFIX_MV_FILE);
Path workingLob = Path.of(workingCopyName + ".lobs.db");
try {
Files.deleteIfExists(workingMv);
Files.deleteIfExists(workingLob);
} catch (IOException e) {
// Do nothing, it's not a big deal
workingMv.toFile().deleteOnExit();
workingLob.toFile().deleteOnExit();
}
}
return true;
}
private static void rename(String name, boolean back) throws IOException {
rename(name, Constants.SUFFIX_MV_FILE, back);
rename(name, ".lobs.db", back);
}
private static void rename(String name, String suffix, boolean back) throws IOException {
String source = name + suffix;
String target = source + ".bak";
if (back) {
String t = source;
source = target;
target = t;
}
Path p = Paths.get(source);
if (Files.exists(p)) {
Files.move(p, Paths.get(target), StandardCopyOption.ATOMIC_MOVE);
}
}
private static void copy(String source, String target) throws IOException {
copy(source, target, Constants.SUFFIX_MV_FILE);
copy(source, target, ".lobs.db");
}
private static void copy(String source, String target, String suffix) throws IOException {
Path sourcePath = Path.of(source + suffix);
Path targetPath = Path.of(target + suffix);
if (Files.exists(sourcePath)) {
Files.copy(sourcePath, targetPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
}
}
private static String copyProperty(ConnectionInfo ci, StringBuilder oldUrl, String name) {
try {
String value = ci.getProperty(name, null);
if (value != null) {
oldUrl.append(';').append(name).append('=').append(value);
}
return value;
} catch (Exception e) {
return null;
}
}
/**
* Loads the specified version of H2 in a separate class loader.
*
* @param version the version to load
* @return the driver of the specified version
* @throws IOException on I/O exception
* @throws ReflectiveOperationException on exception during initialization of the driver
*/
public static java.sql.Driver loadH2(int version) throws IOException, ReflectiveOperationException {
String prefix;
if (version >= 201) {
if ((version & 1) != 0 || version > Constants.BUILD_ID) {
throw new IllegalArgumentException("version=" + version);
}
prefix = "2.0.";
} else if (version >= 177) {
prefix = "1.4.";
} else if (version >= 146 && version != 147) {
prefix = "1.3.";
} else if (version >= 120) {
prefix = "1.2.";
} else {
throw new IllegalArgumentException("version=" + version);
}
String fullVersion = prefix + version;
byte[] data = loadFromDisk(fullVersion);
ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(data));
HashMap<String, byte[]> map = new HashMap<>(version >= 198 ? 2048 : 1024);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (ZipEntry ze; (ze = is.getNextEntry()) != null;) {
if (ze.isDirectory()) {
continue;
}
IOUtils.copy(is, baos);
map.put(ze.getName(), baos.toByteArray());
baos.reset();
}
ClassLoader cl = new ClassLoader(null) {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String resourceName = name.replace('.', '/') + ".class";
byte[] b = map.get(resourceName);
if (b == null) {
return ClassLoader.getSystemClassLoader().loadClass(name);
}
return defineClass(name, b, 0, b.length);
}
@Override
public InputStream getResourceAsStream(String name) {
byte[] b = map.get(name);
return b != null ? new ByteArrayInputStream(b) : null;
}
};
return (java.sql.Driver) cl.loadClass("org.h2.Driver").getDeclaredMethod("load").invoke(null);
}
private static byte[] loadFromDisk(String fullVersion) {
String h2cacheProperty = System.getProperty("demyo.h2.cacheDirectoryName", "legacy-h2-versions");
Path h2CacheDirectory = SystemConfiguration.getInstance().getApplicationDirectory()
.resolve(h2cacheProperty);
Path h2Jar = h2CacheDirectory.resolve("h2-" + fullVersion + ".jar");
if (!Files.isReadable(h2Jar)) {
throw new DemyoRuntimeException(DemyoErrorCode.SYS_MISSING_H2_FOR_MIGRATION, "No file at " + h2Jar);
}
try {
return Files.readAllBytes(h2Jar);
} catch (IOException e) {
throw new DemyoRuntimeException(DemyoErrorCode.SYS_MISSING_H2_FOR_MIGRATION, e,
"Failed to read the file at " + h2Jar);
}
}
/**
* Unloads the specified driver of H2.
*
* @param driver the driver to unload
* @throws ReflectiveOperationException on exception
*/
public static void unloadH2(java.sql.Driver driver) throws ReflectiveOperationException {
driver.getClass().getDeclaredMethod("unload").invoke(null);
}
private H2LocalUpgrade() {
}
}
| Don't forget to close statements.
Refs #90.
| source/demyo-app/src/main/java/org/demyo/desktop/H2LocalUpgrade.java | Don't forget to close statements. | <ide><path>ource/demyo-app/src/main/java/org/demyo/desktop/H2LocalUpgrade.java
<ide> import java.nio.file.StandardCopyOption;
<ide> import java.sql.Connection;
<ide> import java.sql.SQLException;
<add>import java.sql.Statement;
<ide> import java.util.HashMap;
<ide> import java.util.Properties;
<ide> import java.util.UUID;
<ide> String cipher = copyProperty(ci, oldUrl, "CIPHER");
<ide> String scriptCommandSuffix = cipher == null ? "" : " CIPHER AES PASSWORD '" + UUID.randomUUID() + "' --hide--";
<ide> java.sql.Driver driver = loadH2(version);
<del> try (Connection conn = driver.connect(oldUrl.toString(), oldInfo)) {
<del> conn.createStatement().execute(StringUtils.quoteStringSQL(new StringBuilder("SCRIPT TO "), script)
<add> try (Connection conn = driver.connect(oldUrl.toString(), oldInfo); Statement stmt = conn.createStatement()) {
<add> stmt.execute(StringUtils.quoteStringSQL(new StringBuilder("SCRIPT TO "), script)
<ide> .append(scriptCommandSuffix).toString());
<ide> } finally {
<ide> unloadH2(driver);
<ide> }
<ide> rename(name, false);
<del> try (JdbcConnection conn = new JdbcConnection(url, info, null, null, false)) {
<add> try (JdbcConnection conn = new JdbcConnection(url, info, null, null, false);
<add> Statement stmt = conn.createStatement()) {
<ide> StringBuilder builder = StringUtils.quoteStringSQL(new StringBuilder("RUNSCRIPT FROM "), script)
<ide> .append(scriptCommandSuffix);
<ide> if (version <= 200) {
<ide> builder.append(" FROM_1X");
<ide> }
<del> conn.createStatement().execute(builder.toString());
<add> stmt.execute(builder.toString());
<ide> } catch (Throwable t) {
<ide> rename(name, true);
<ide> throw t; |
|
Java | apache-2.0 | f00727177e69f31dbef15af598764d8f72e94b1f | 0 | JNOSQL/diana | /*
*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*
*/
package org.jnosql.diana.api.column;
import org.jnosql.diana.api.Value;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ColumnEntityTest {
@Test
public void shouldReturnErrorWhenNameIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> ColumnEntity.of(null));
}
@Test
public void shouldReturnErrorWhenColumnsIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> ColumnEntity.of("entity", null));
}
@Test
public void shouldReturnOneColumn() {
ColumnEntity entity = ColumnEntity.of("entity");
assertEquals(Integer.valueOf(0), Integer.valueOf(entity.size()));
assertTrue(entity.isEmpty());
entity.add(Column.of("name", "name"));
entity.add(Column.of("name2", Value.of("name2")));
assertFalse(entity.isEmpty());
assertEquals(Integer.valueOf(2), Integer.valueOf(entity.size()));
assertFalse(ColumnEntity.of("entity", singletonList(Column.of("name", "name"))).isEmpty());
}
@Test
public void shouldDoCopy() {
ColumnEntity entity = ColumnEntity.of("entity", singletonList(Column.of("name", "name")));
ColumnEntity copy = entity.copy();
assertFalse(entity == copy);
assertEquals(entity, copy);
}
@Test
public void shouldFindColumn() {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(column));
Optional<Column> name = entity.find("name");
Optional<Column> notfound = entity.find("not_found");
assertTrue(name.isPresent());
assertFalse(notfound.isPresent());
assertEquals(column, name.get());
}
@Test
public void shouldReturnErroWhenFindCoumnIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(column));
entity.find(null);
});
}
@Test
public void shouldRemoveColumn() {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(column));
assertTrue(entity.remove("name"));
assertTrue(entity.isEmpty());
}
@Test
public void shouldConvertToMap() {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(column));
Map<String, Object> result = entity.toMap();
assertFalse(result.isEmpty());
assertEquals(Integer.valueOf(1), Integer.valueOf(result.size()));
assertEquals(column.getName(), result.keySet().stream().findAny().get());
}
@Test
public void shouldConvertSubColumn() {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(Column.of("sub", column)));
Map<String, Object> result = entity.toMap();
assertFalse(result.isEmpty());
assertEquals(Integer.valueOf(1), Integer.valueOf(result.size()));
Map<String, Object> map = (Map<String, Object>) result.get("sub");
assertEquals("name", map.get("name"));
}
@Test
public void shouldCreateANewInstance() {
String name = "name";
ColumnEntity entity = new DefaultColumnEntity(name);
assertEquals(name, entity.getName());
}
@Test
public void shouldCreateAnEmptyEntity() {
ColumnEntity entity = new DefaultColumnEntity("name");
assertTrue(entity.isEmpty());
}
@Test
public void shouldReturnAnErrorWhenAddANullColumn() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.add(null);
});
}
@Test
public void shouldAddANewColumn() {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.add(Column.of("column", 12));
assertFalse(entity.isEmpty());
assertEquals(1, entity.size());
}
@Test
public void shouldReturnErrorWhenAddAnNullIterable() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.addAll(null);
});
}
@Test
public void shouldAddAllColumns() {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.addAll(Arrays.asList(Column.of("name", 12), Column.of("value", "value")));
assertFalse(entity.isEmpty());
assertEquals(2, entity.size());
}
@Test
public void shouldNotFindColumn() {
ColumnEntity entity = new DefaultColumnEntity("name");
Optional<Column> column = entity.find("name");
assertFalse(column.isPresent());
}
@Test
public void shouldRemoveByName() {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.add(Column.of("value", 32D));
assertTrue(entity.remove("value"));
assertTrue(entity.isEmpty());
}
@Test
public void shouldReturnErrorWhenRemovedNameIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.remove(null);
});
}
@Test
public void shouldNotRemoveByName() {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.add(Column.of("value", 32D));
assertFalse(entity.remove("value1"));
assertFalse(entity.isEmpty());
}
@Test
public void shouldReturnErrorWhenRemoveByNameIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.remove(null);
});
}
@Test
public void shouldAddColumnAsNameAndObject() {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add("name", 10);
assertEquals(1, entity.size());
Optional<Column> name = entity.find("name");
assertTrue(name.isPresent());
assertEquals(10, name.get().get());
}
@Test
public void shouldAddColumnAsNameAndValue() {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add("name", Value.of(10));
assertEquals(1, entity.size());
Optional<Column> name = entity.find("name");
assertTrue(name.isPresent());
assertEquals(10, name.get().get());
}
@Test
public void shouldReturnErrorWhenAddColumnasObjectWhenHasNullObject() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add("name", null);
});
}
@Test
public void shouldReturnErrorWhenAddColumnasObjectWhenHasNullColumnName() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add(null, 10);
});
}
@Test
public void shouldReturnErrorWhenAddColumnasValueWhenHasNullColumnName() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add(null, Value.of(12));
});
}
@Test
public void shouldAvoidDuplicatedColumn() {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add("name", 10);
entity.add("name", 13);
assertEquals(1, entity.size());
Optional<Column> column = entity.find("name");
assertEquals(Column.of("name", 13), column.get());
}
@Test
public void shouldAvoidDuplicatedColumnWhenAddList() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name", 13));
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.addAll(columns);
assertEquals(1, entity.size());
assertEquals(1, ColumnEntity.of("columnFamily", columns).size());
}
@Test
public void shouldReturnsTheColumnNames() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertThat(columnFamily.getColumnNames(), containsInAnyOrder("name", "name2", "name3", "name4", "name5"));
}
@Test
public void shouldReturnsTheColumnValues() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertThat(columnFamily.getValues(), containsInAnyOrder(Value.of(10), Value.of(11), Value.of(12),
Value.of(13), Value.of(16)));
}
@Test
public void shouldReturnTrueWhenContainsElement() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertTrue(columnFamily.contains("name"));
assertTrue(columnFamily.contains("name2"));
assertTrue(columnFamily.contains("name3"));
assertTrue(columnFamily.contains("name4"));
assertTrue(columnFamily.contains("name5"));
}
@Test
public void shouldReturnFalseWhenDoesNotContainElement() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertFalse(columnFamily.contains("name6"));
assertFalse(columnFamily.contains("name7"));
assertFalse(columnFamily.contains("name8"));
assertFalse(columnFamily.contains("name9"));
assertFalse(columnFamily.contains("name10"));
}
@Test
public void shouldRemoveAllElementsWhenUseClearMethod() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertFalse(columnFamily.isEmpty());
columnFamily.clear();
assertTrue(columnFamily.isEmpty());
}
} | diana-column/src/test/java/org/jnosql/diana/api/column/ColumnEntityTest.java | /*
*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*
*/
package org.jnosql.diana.api.column;
import org.jnosql.diana.api.Value;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ColumnEntityTest {
@Test
public void shouldReturnErrorWhenNameIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> ColumnEntity.of(null));
}
@Test
public void shouldReturnErrorWhenColumnsIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> ColumnEntity.of("entity", null));
}
@Test
public void shouldReturnOneColumn() {
ColumnEntity entity = ColumnEntity.of("entity");
assertEquals(Integer.valueOf(0), Integer.valueOf(entity.size()));
assertTrue(entity.isEmpty());
entity.add(Column.of("name", "name"));
entity.add(Column.of("name2", Value.of("name2")));
assertFalse(entity.isEmpty());
assertEquals(Integer.valueOf(2), Integer.valueOf(entity.size()));
assertFalse(ColumnEntity.of("entity", singletonList(Column.of("name", "name"))).isEmpty());
}
@Test
public void shouldDoCopy() {
ColumnEntity entity = ColumnEntity.of("entity", singletonList(Column.of("name", "name")));
ColumnEntity copy = entity.copy();
assertFalse(entity == copy);
assertEquals(entity, copy);
}
@Test
public void shouldFindColumn() {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(column));
Optional<Column> name = entity.find("name");
Optional<Column> notfound = entity.find("not_found");
assertTrue(name.isPresent());
assertFalse(notfound.isPresent());
assertEquals(column, name.get());
}
@Test
public void shouldReturnErroWhenFindCoumnIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(column));
entity.find(null);
});
}
@Test
public void shouldRemoveColumn() {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(column));
assertTrue(entity.remove("name"));
assertTrue(entity.isEmpty());
}
@Test
public void shouldConvertToMap() {
Column column = Column.of("name", "name");
ColumnEntity entity = ColumnEntity.of("entity", singletonList(column));
Map<String, Object> result = entity.toMap();
assertFalse(result.isEmpty());
assertEquals(Integer.valueOf(1), Integer.valueOf(result.size()));
assertEquals(column.getName(), result.keySet().stream().findAny().get());
}
@Test
public void shouldCreateANewInstance() {
String name = "name";
ColumnEntity entity = new DefaultColumnEntity(name);
assertEquals(name, entity.getName());
}
@Test
public void shouldCreateAnEmptyEntity() {
ColumnEntity entity = new DefaultColumnEntity("name");
assertTrue(entity.isEmpty());
}
@Test
public void shouldReturnAnErrorWhenAddANullColumn() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.add(null);
});
}
@Test
public void shouldAddANewColumn() {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.add(Column.of("column", 12));
assertFalse(entity.isEmpty());
assertEquals(1, entity.size());
}
@Test
public void shouldReturnErrorWhenAddAnNullIterable() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.addAll(null);
});
}
@Test
public void shouldAddAllColumns() {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.addAll(Arrays.asList(Column.of("name", 12), Column.of("value", "value")));
assertFalse(entity.isEmpty());
assertEquals(2, entity.size());
}
@Test
public void shouldNotFindColumn() {
ColumnEntity entity = new DefaultColumnEntity("name");
Optional<Column> column = entity.find("name");
assertFalse(column.isPresent());
}
@Test
public void shouldRemoveByName() {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.add(Column.of("value", 32D));
assertTrue(entity.remove("value"));
assertTrue(entity.isEmpty());
}
@Test
public void shouldReturnErrorWhenRemovedNameIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.remove(null);
});
}
@Test
public void shouldNotRemoveByName() {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.add(Column.of("value", 32D));
assertFalse(entity.remove("value1"));
assertFalse(entity.isEmpty());
}
@Test
public void shouldReturnErrorWhenRemoveByNameIsNull() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("name");
entity.remove(null);
});
}
@Test
public void shouldAddColumnAsNameAndObject() {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add("name", 10);
assertEquals(1, entity.size());
Optional<Column> name = entity.find("name");
assertTrue(name.isPresent());
assertEquals(10, name.get().get());
}
@Test
public void shouldAddColumnAsNameAndValue() {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add("name", Value.of(10));
assertEquals(1, entity.size());
Optional<Column> name = entity.find("name");
assertTrue(name.isPresent());
assertEquals(10, name.get().get());
}
@Test
public void shouldReturnErrorWhenAddColumnasObjectWhenHasNullObject() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add("name", null);
});
}
@Test
public void shouldReturnErrorWhenAddColumnasObjectWhenHasNullColumnName() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add(null, 10);
});
}
@Test
public void shouldReturnErrorWhenAddColumnasValueWhenHasNullColumnName() {
Assertions.assertThrows(NullPointerException.class, () -> {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add(null, Value.of(12));
});
}
@Test
public void shouldAvoidDuplicatedColumn() {
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.add("name", 10);
entity.add("name", 13);
assertEquals(1, entity.size());
Optional<Column> column = entity.find("name");
assertEquals(Column.of("name", 13), column.get());
}
@Test
public void shouldAvoidDuplicatedColumnWhenAddList() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name", 13));
ColumnEntity entity = new DefaultColumnEntity("columnFamily");
entity.addAll(columns);
assertEquals(1, entity.size());
assertEquals(1, ColumnEntity.of("columnFamily", columns).size());
}
@Test
public void shouldReturnsTheColumnNames() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertThat(columnFamily.getColumnNames(), containsInAnyOrder("name", "name2", "name3", "name4", "name5"));
}
@Test
public void shouldReturnsTheColumnValues() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertThat(columnFamily.getValues(), containsInAnyOrder(Value.of(10), Value.of(11), Value.of(12),
Value.of(13), Value.of(16)));
}
@Test
public void shouldReturnTrueWhenContainsElement() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertTrue(columnFamily.contains("name"));
assertTrue(columnFamily.contains("name2"));
assertTrue(columnFamily.contains("name3"));
assertTrue(columnFamily.contains("name4"));
assertTrue(columnFamily.contains("name5"));
}
@Test
public void shouldReturnFalseWhenDoesNotContainElement() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertFalse(columnFamily.contains("name6"));
assertFalse(columnFamily.contains("name7"));
assertFalse(columnFamily.contains("name8"));
assertFalse(columnFamily.contains("name9"));
assertFalse(columnFamily.contains("name10"));
}
@Test
public void shouldRemoveAllElementsWhenUseClearMethod() {
List<Column> columns = asList(Column.of("name", 10), Column.of("name2", 11),
Column.of("name3", 12), Column.of("name4", 13),
Column.of("name5", 14), Column.of("name5", 16));
ColumnEntity columnFamily = ColumnEntity.of("columnFamily", columns);
assertFalse(columnFamily.isEmpty());
columnFamily.clear();
assertTrue(columnFamily.isEmpty());
}
} | adds tests to column entity
| diana-column/src/test/java/org/jnosql/diana/api/column/ColumnEntityTest.java | adds tests to column entity | <ide><path>iana-column/src/test/java/org/jnosql/diana/api/column/ColumnEntityTest.java
<ide> assertFalse(result.isEmpty());
<ide> assertEquals(Integer.valueOf(1), Integer.valueOf(result.size()));
<ide> assertEquals(column.getName(), result.keySet().stream().findAny().get());
<del>
<add> }
<add>
<add> @Test
<add> public void shouldConvertSubColumn() {
<add> Column column = Column.of("name", "name");
<add> ColumnEntity entity = ColumnEntity.of("entity", singletonList(Column.of("sub", column)));
<add> Map<String, Object> result = entity.toMap();
<add> assertFalse(result.isEmpty());
<add> assertEquals(Integer.valueOf(1), Integer.valueOf(result.size()));
<add> Map<String, Object> map = (Map<String, Object>) result.get("sub");
<add> assertEquals("name", map.get("name"));
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | 2445166b177ce42e2d40a277fa30fc71839c4660 | 0 | MovingBlocks/TeraNUI | /*
* Copyright 2014 MovingBlocks
*
* 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.terasology.nui;
import com.google.common.base.Preconditions;
import org.joml.Math;
import org.joml.Vector3fc;
import org.joml.Vector3ic;
import org.joml.Vector4fc;
import org.joml.Vector4ic;
import org.terasology.module.sandbox.API;
import java.nio.ByteBuffer;
import java.util.Locale;
import java.util.Objects;
/**
* Color is a representation of a RGBA color. Color components can be set and accessed via floats ranging from 0-1, or ints ranging from 0-255.
* Color is immutable and thread safe.
* <br><br>
* There are a plethora of Color classes, but none that are quite suitable IMO:
* <ul>
* <li>vecmaths - doesn't access with r/g/b/a, separation by representation is awkward, feature bland.</li>
* <li>Slick2D - ideally will lose dependency on slick utils. Also ties to lwjgl</li>
* <li>Lwjgl - don't want to be graphics implementation dependant</li>
* <li>javafx - ew</li>
* <li>com.sun.prism - double ew. Shouldn't use com.sun classes at all</li>
* <li>awt - tempting, certainly feature-rich. Has some strange awt-specific functionality though (createContext) and native links</li>
* </ul>
*
*/
@API
public class Color implements Colorc{
@Deprecated
public static final Color BLACK = new Color(0x000000FF);
@Deprecated
public static final Color WHITE = new Color(0xFFFFFFFF);
@Deprecated
public static final Color BLUE = new Color(0x0000FFFF);
@Deprecated
public static final Color GREEN = new Color(0x00FF00FF);
@Deprecated
public static final Color RED = new Color(0xFF0000FF);
@Deprecated
public static final Color GREY = new Color(0x888888FF);
@Deprecated
public static final Color TRANSPARENT = new Color(0x00000000);
@Deprecated
public static final Color YELLOW = new Color(0xFFFF00FF);
@Deprecated
public static final Color CYAN = new Color(0x00FFFFFF);
@Deprecated
public static final Color MAGENTA = new Color(0xFF00FFFF);
public static final Colorc black = new Color(0x000000FF);
public static final Colorc white = new Color(0xFFFFFFFF);
public static final Colorc blue = new Color(0x0000FFFF);
public static final Colorc green = new Color(0x00FF00FF);
public static final Colorc red = new Color(0xFF0000FF);
public static final Colorc grey = new Color(0x888888FF);
public static final Colorc transparent = new Color(0x00000000);
public static final Colorc yellow = new Color(0xFFFF00FF);
public static final Colorc cyan = new Color(0x00FFFFFF);
public static final Colorc magenta = new Color(0xFF00FFFF);
private static final int MAX = 255;
private static final int RED_OFFSET = 24;
private static final int GREEN_OFFSET = 16;
private static final int BLUE_OFFSET = 8;
private static final int RED_FILTER = 0x00FFFFFF;
private static final int GREEN_FILTER = 0xFF00FFFF;
private static final int BLUE_FILTER = 0xFFFF00FF;
private static final int ALPHA_FILTER = 0xFFFFFF00;
private int representation;
/**
* Creates a color that is black with full alpha.
*/
public Color() {
representation = 0x000000FF;
}
/**
* range between 0x00000000 to 0xFFFFFFFF
* @param representation color in hex format
*/
public Color(int representation) {
this.representation = representation;
}
/**
* set the color source
* @param src color source
*/
public Color(Colorc src) {
this.set(src.rgba());
}
/**
* Create a color with the given red/green/blue values. Alpha is initialised as max.
*
* @param r red in the range of 0.0f to 1.0f
* @param g green in the range of 0.0f to 1.0f
* @param b blue in the range of 0.0f to 1.0f
*/
public Color(float r, float g, float b) {
this((byte) (r * MAX), (byte) (g * MAX), (byte) (b * MAX));
}
/**
* Creates a color with the given red/green/blue/alpha values.
*
* @param r red in the range of 0.0f to 1.0f
* @param g green in the range of 0.0f to 1.0f
* @param b blue in the range of 0.0f to 1.0f
* @param a alpha in the range of 0.0f to 1.0f
*/
public Color(float r, float g, float b, float a) {
this((byte) (r * MAX), (byte) (g * MAX), (byte) (b * MAX), (byte) (a * MAX));
}
/**
* Creates a color with the given red/green/blue values. Alpha is initialised as max.
*
* @param r red in the range of 0.0f to 1.0f
* @param g green in the range of 0.0f to 1.0f
* @param b blue in the range of 0.0f to 1.0f
*/
public Color(int r, int g, int b) {
this.set(r, g, b);
}
/**
* Creates a color with the given red/green/blue/alpha values.
*
* @param r red in the range of 0 to 255
* @param g green in the range of 0 to 255
* @param b blue in the range of 0 to 255
* @param a alpha in the range of 0 to 255
*/
public Color(int r, int g, int b, int a) {
this.set(r, g, b, a);
}
@Override
public int r() {
return (representation >> RED_OFFSET) & MAX;
}
@Override
public int g() {
return (representation >> GREEN_OFFSET) & MAX;
}
@Override
public int b() {
return (representation >> BLUE_OFFSET) & MAX;
}
@Override
public int a() {
return representation & MAX;
}
@Override
public float rf() {
return r() / 255.f;
}
@Override
public float bf() {
return b() / 255.f;
}
@Override
public float gf() {
return g() / 255.f;
}
@Override
public float af() {
return a() / 255.f;
}
public Color set(Vector3ic representation) {
return this.set((byte) representation.x(),
(byte) representation.y(),
(byte) representation.z());
}
public Color set(Vector3fc representation) {
return this.set((byte) (representation.x() * MAX),
(byte) (representation.y() * MAX),
(byte) (representation.z() * MAX));
}
public Color set(Vector4fc representation) {
return this.set((byte) (representation.x() * MAX),
(byte) (representation.y() * MAX),
(byte) (representation.z() * MAX),
(byte) (representation.w() * MAX));
}
public Color set(Vector4ic representation) {
return this.set((byte) representation.x(),
(byte) representation.y(),
(byte) representation.z(),
(byte) representation.w());
}
public Color set(int representation){
this.representation = representation;
return this;
}
public Color set(int r, int g, int b, int a) {
return this.set(Math.clamp(0, 255, r) << RED_OFFSET |
Math.clamp(0, 255, g) << GREEN_OFFSET |
Math.clamp(0, 255, b) << BLUE_OFFSET |
Math.clamp(0, 255, a));
}
public Color set(int r, int g, int b) {
return this.set(r, g, b, 0xFF);
}
/**
* set the value of the red channel
* @param value color range between 0-255
* @return this
*/
public Color setRed(int value) {
return this.set(Math.clamp(0, 255, value) << RED_OFFSET | (representation & RED_FILTER));
}
/**
* set the value of the red channel
* @param value color range between 0.0f to 1.0f
* @return this
*/
public Color setRed(float value) {
return setRed(value * MAX);
}
/**
* set the value of the green channel
* @param value color range between 0-255
* @return this
*/
public Color setGreen(int value) {
return this.set(Math.clamp(0, 255, value) << GREEN_OFFSET | (representation & GREEN_FILTER));
}
/**
* set the value of the green channel
* @param value color range between 0.0f to 1.0f
* @return this
*/
public Color setGreen(float value) {
return setGreen(value * MAX);
}
/**
* set the value of the blue channel
* @param value blue range between 0-255
* @return this
*/
public Color setBlue(int value) {
return this.set(Math.clamp(0, 255, value) << BLUE_OFFSET | (representation & BLUE_FILTER));
}
/**
* set the value of the blue channel
* @param value blue range between 0.0f to 1.0f
* @return this
*/
public Color setBlue(float value) {
return setBlue(value * MAX);
}
/**
* set the value of the alpha channel
* @param value alpha range between 0-255
* @return this
*/
public Color setAlpha(int value) {
return this.set(Math.clamp(0, 255, value) | (representation & ALPHA_FILTER));
}
/**
* set the value of the alpha channel
* @param value alpha range between 0.0f to 1.0f
* @return this
*/
public Color setAlpha(float value) {
return setAlpha(value * MAX);
}
/**
*
* @param value
* @return
* @deprecated use {@link #setRed(int)} instead
*/
@Deprecated
public Color alterRed(int value) {
Preconditions.checkArgument(value >= 0 && value <= MAX, "Color values must be in range 0-255");
return new Color(value << RED_OFFSET | (representation & RED_FILTER));
}
/**
*
* @param value
* @return
* @deprecated use {@link #setBlue(int)} instead
*/
@Deprecated
public Color alterBlue(int value) {
Preconditions.checkArgument(value >= 0 && value <= MAX, "Color values must be in range 0-255");
return new Color(value << BLUE_OFFSET | (representation & BLUE_FILTER));
}
/**
*
* @param value
* @return
* @deprecated use {@link #setBlue(int)} instead
*/
@Deprecated
public Color alterGreen(int value) {
Preconditions.checkArgument(value >= 0 && value <= MAX, "Color values must be in range 0-255");
return new Color(value << GREEN_OFFSET | (representation & GREEN_FILTER));
}
/**
* @param value
* @return
* @deprecated use {@link #setAlpha(int)} instead
*/
@Deprecated
public Color alterAlpha(int value) {
Preconditions.checkArgument(value >= 0 && value <= MAX, "Color values must be in range 0-255");
return new Color(value | (representation & ALPHA_FILTER));
}
/**
* 255 Subtract from all components except alpha
* @return new instance of inverted {@link Color}
* @deprecated use {@link #invert()} instead
*/
@Deprecated
public Color inverse() {
return new Color((~representation & ALPHA_FILTER) | a());
}
/**
* 255 Subtract from all components except alpha;
* @return this
*/
public Color invert() {
return this.set((~representation & ALPHA_FILTER) | a());
}
@Override
public int rgba() {
return representation;
}
@Override
public int rgb() {
return (representation & ALPHA_FILTER) | 0xFF;
}
/**
* write color to ByteBuffer as int.
*
* @param buffer The ByteBuffer
*/
public void addToBuffer(ByteBuffer buffer) {
buffer.putInt(representation);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Color) {
Color other = (Color) obj;
return representation == other.representation;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(representation);
}
@Override
public String toHex() {
StringBuilder builder = new StringBuilder();
String hexString = Integer.toHexString(representation);
for (int i = 0; i < 8 - hexString.length(); ++i) {
builder.append('0');
}
builder.append(hexString.toUpperCase(Locale.ENGLISH));
return builder.toString();
}
@Override
public String toString() {
return toHex();
}
/**
* @deprecated use {@link #rgba()} instead
*/
@Deprecated
public int getRepresentation() {
return representation;
}
}
| nui/src/main/java/org/terasology/nui/Color.java | /*
* Copyright 2014 MovingBlocks
*
* 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.terasology.nui;
import com.google.common.base.Preconditions;
import org.joml.Math;
import org.joml.Vector3fc;
import org.joml.Vector3ic;
import org.joml.Vector4fc;
import org.joml.Vector4ic;
import org.terasology.module.sandbox.API;
import java.nio.ByteBuffer;
import java.util.Locale;
import java.util.Objects;
/**
* Color is a representation of a RGBA color. Color components can be set and accessed via floats ranging from 0-1, or ints ranging from 0-255.
* Color is immutable and thread safe.
* <br><br>
* There are a plethora of Color classes, but none that are quite suitable IMO:
* <ul>
* <li>vecmaths - doesn't access with r/g/b/a, separation by representation is awkward, feature bland.</li>
* <li>Slick2D - ideally will lose dependency on slick utils. Also ties to lwjgl</li>
* <li>Lwjgl - don't want to be graphics implementation dependant</li>
* <li>javafx - ew</li>
* <li>com.sun.prism - double ew. Shouldn't use com.sun classes at all</li>
* <li>awt - tempting, certainly feature-rich. Has some strange awt-specific functionality though (createContext) and native links</li>
* </ul>
*
*/
@API
public class Color implements Colorc{
@Deprecated
public static final Color BLACK = new Color(0x000000FF);
@Deprecated
public static final Color WHITE = new Color(0xFFFFFFFF);
@Deprecated
public static final Color BLUE = new Color(0x0000FFFF);
@Deprecated
public static final Color GREEN = new Color(0x00FF00FF);
@Deprecated
public static final Color RED = new Color(0xFF0000FF);
@Deprecated
public static final Color GREY = new Color(0x888888FF);
@Deprecated
public static final Color TRANSPARENT = new Color(0x00000000);
@Deprecated
public static final Color YELLOW = new Color(0xFFFF00FF);
@Deprecated
public static final Color CYAN = new Color(0x00FFFFFF);
@Deprecated
public static final Color MAGENTA = new Color(0xFF00FFFF);
public static final Colorc black = new Color(0x000000FF);
public static final Colorc white = new Color(0xFFFFFFFF);
public static final Colorc blue = new Color(0x0000FFFF);
public static final Colorc green = new Color(0x00FF00FF);
public static final Colorc red = new Color(0xFF0000FF);
public static final Colorc grey = new Color(0x888888FF);
public static final Colorc transparent = new Color(0x00000000);
public static final Colorc yellow = new Color(0xFFFF00FF);
public static final Colorc cyan = new Color(0x00FFFFFF);
public static final Colorc magenta = new Color(0xFF00FFFF);
private static final int MAX = 255;
private static final int RED_OFFSET = 24;
private static final int GREEN_OFFSET = 16;
private static final int BLUE_OFFSET = 8;
private static final int RED_FILTER = 0x00FFFFFF;
private static final int GREEN_FILTER = 0xFF00FFFF;
private static final int BLUE_FILTER = 0xFFFF00FF;
private static final int ALPHA_FILTER = 0xFFFFFF00;
private int representation;
/**
* Creates a color that is black with full alpha.
*/
public Color() {
representation = 0x000000FF;
}
/**
* range between 0x00000000 to 0xFFFFFFFF
* @param representation color in hex format
*/
public Color(int representation) {
this.representation = representation;
}
/**
* set the color source
* @param src color source
*/
public Color(Colorc src) {
this.set(src.rgba());
}
/**
* Create a color with the given red/green/blue values. Alpha is initialised as max.
*
* @param r red in the range of 0.0f to 1.0f
* @param g green in the range of 0.0f to 1.0f
* @param b blue in the range of 0.0f to 1.0f
*/
public Color(float r, float g, float b) {
this((byte) (r * MAX), (byte) (g * MAX), (byte) (b * MAX));
}
/**
* Creates a color with the given red/green/blue/alpha values.
*
* @param r red in the range of 0.0f to 1.0f
* @param g green in the range of 0.0f to 1.0f
* @param b blue in the range of 0.0f to 1.0f
* @param a alpha in the range of 0.0f to 1.0f
*/
public Color(float r, float g, float b, float a) {
this((byte) (r * MAX), (byte) (g * MAX), (byte) (b * MAX), (byte) (a * MAX));
}
/**
* Creates a color with the given red/green/blue values. Alpha is initialised as max.
*
* @param r red in the range of 0.0f to 1.0f
* @param g green in the range of 0.0f to 1.0f
* @param b blue in the range of 0.0f to 1.0f
*/
public Color(int r, int g, int b) {
this.set(r, g, b);
}
/**
* Creates a color with the given red/green/blue/alpha values.
*
* @param r red in the range of 0 to 255
* @param g green in the range of 0 to 255
* @param b blue in the range of 0 to 255
* @param a alpha in the range of 0 to 255
*/
public Color(int r, int g, int b, int a) {
this.set(r, g, b, a);
}
@Override
public int r() {
return (representation >> RED_OFFSET) & MAX;
}
@Override
public int g() {
return (representation >> GREEN_OFFSET) & MAX;
}
@Override
public int b() {
return (representation >> BLUE_OFFSET) & MAX;
}
@Override
public int a() {
return representation & MAX;
}
@Override
public float rf() {
return r() / 255.f;
}
@Override
public float bf() {
return b() / 255.f;
}
@Override
public float gf() {
return g() / 255.f;
}
@Override
public float af() {
return a() / 255.f;
}
public Color set(Vector3ic representation) {
return this.set((byte) representation.x(),
(byte) representation.y(),
(byte) representation.z());
}
public Color set(Vector3fc representation) {
return this.set((byte) (representation.x() * MAX),
(byte) (representation.y() * MAX),
(byte) (representation.z() * MAX));
}
public Color set(Vector4fc representation) {
return this.set((byte) (representation.x() * MAX),
(byte) (representation.y() * MAX),
(byte) (representation.z() * MAX),
(byte) (representation.w() * MAX));
}
public Color set(Vector4ic representation) {
return this.set((byte) representation.x(),
(byte) representation.y(),
(byte) representation.z(),
(byte) representation.w());
}
public Color set(int representation){
this.representation = representation;
return this;
}
public Color set(int r, int g, int b, int a) {
return this.set(Math.clamp(0, 255, r) << RED_OFFSET |
Math.clamp(0, 255, g) << GREEN_OFFSET |
Math.clamp(0, 255, b) << BLUE_OFFSET |
Math.clamp(0, 255, a));
}
public Color set(int r, int g, int b) {
return this.set(r, g, b, 0xFF);
}
/**
* set the value of the red channel
* @param value color range between 0-255
* @return this
*/
public Color setRed(int value) {
return this.set(value << RED_OFFSET | (representation & RED_FILTER));
}
/**
* set the value of the red channel
* @param value color range between 0.0f to 1.0f
* @return this
*/
public Color setRed(float value) {
return setRed((byte) (value * MAX));
}
/**
* set the value of the green channel
* @param value color range between 0-255
* @return this
*/
public Color setGreen(int value) {
return this.set(value << GREEN_OFFSET | (representation & GREEN_FILTER));
}
/**
* set the value of the green channel
* @param value color range between 0.0f to 1.0f
* @return this
*/
public Color setGreen(float value) {
return setGreen((byte) (value * MAX));
}
/**
* set the value of the blue channel
* @param value blue range between 0-255
* @return this
*/
public Color setBlue(int value) {
return this.set(value << BLUE_OFFSET | (representation & BLUE_FILTER));
}
/**
* set the value of the blue channel
* @param value blue range between 0.0f to 1.0f
* @return this
*/
public Color setBlue(float value) {
return setBlue((byte) (value * MAX));
}
/**
* set the value of the alpha channel
* @param value alpha range between 0-255
* @return this
*/
public Color setAlpha(int value) {
return this.set(value | (representation & ALPHA_FILTER));
}
/**
* set the value of the alpha channel
* @param value alpha range between 0.0f to 1.0f
* @return this
*/
public Color setAlpha(float value) {
return setAlpha((byte) (value * MAX));
}
/**
*
* @param value
* @return
* @deprecated use {@link #setRed(int)} instead
*/
@Deprecated
public Color alterRed(int value) {
Preconditions.checkArgument(value >= 0 && value <= MAX, "Color values must be in range 0-255");
return new Color(value << RED_OFFSET | (representation & RED_FILTER));
}
/**
*
* @param value
* @return
* @deprecated use {@link #setBlue(int)} instead
*/
@Deprecated
public Color alterBlue(int value) {
Preconditions.checkArgument(value >= 0 && value <= MAX, "Color values must be in range 0-255");
return new Color(value << BLUE_OFFSET | (representation & BLUE_FILTER));
}
/**
*
* @param value
* @return
* @deprecated use {@link #setBlue(int)} instead
*/
@Deprecated
public Color alterGreen(int value) {
Preconditions.checkArgument(value >= 0 && value <= MAX, "Color values must be in range 0-255");
return new Color(value << GREEN_OFFSET | (representation & GREEN_FILTER));
}
/**
* @param value
* @return
* @deprecated use {@link #setAlpha(int)} instead
*/
@Deprecated
public Color alterAlpha(int value) {
Preconditions.checkArgument(value >= 0 && value <= MAX, "Color values must be in range 0-255");
return new Color(value | (representation & ALPHA_FILTER));
}
/**
* 255 Subtract from all components except alpha
* @return new instance of inverted {@link Color}
* @deprecated use {@link #invert()} instead
*/
@Deprecated
public Color inverse() {
return new Color((~representation & ALPHA_FILTER) | a());
}
/**
* 255 Subtract from all components except alpha;
* @return this
*/
public Color invert() {
return this.set((~representation & ALPHA_FILTER) | a());
}
@Override
public int rgba() {
return representation;
}
@Override
public int rgb() {
return (representation & ALPHA_FILTER) | 0xFF;
}
/**
* write color to ByteBuffer as int.
*
* @param buffer The ByteBuffer
*/
public void addToBuffer(ByteBuffer buffer) {
buffer.putInt(representation);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Color) {
Color other = (Color) obj;
return representation == other.representation;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(representation);
}
@Override
public String toHex() {
StringBuilder builder = new StringBuilder();
String hexString = Integer.toHexString(representation);
for (int i = 0; i < 8 - hexString.length(); ++i) {
builder.append('0');
}
builder.append(hexString.toUpperCase(Locale.ENGLISH));
return builder.toString();
}
@Override
public String toString() {
return toHex();
}
/**
* @deprecated use {@link #rgba()} instead
*/
@Deprecated
public int getRepresentation() {
return representation;
}
}
| add missing clamp to Color#set*
| nui/src/main/java/org/terasology/nui/Color.java | add missing clamp to Color#set* | <ide><path>ui/src/main/java/org/terasology/nui/Color.java
<ide> * @return this
<ide> */
<ide> public Color setRed(int value) {
<del> return this.set(value << RED_OFFSET | (representation & RED_FILTER));
<add> return this.set(Math.clamp(0, 255, value) << RED_OFFSET | (representation & RED_FILTER));
<ide> }
<ide>
<ide> /**
<ide> * @return this
<ide> */
<ide> public Color setRed(float value) {
<del> return setRed((byte) (value * MAX));
<add> return setRed(value * MAX);
<ide> }
<ide>
<ide> /**
<ide> * @return this
<ide> */
<ide> public Color setGreen(int value) {
<del> return this.set(value << GREEN_OFFSET | (representation & GREEN_FILTER));
<add> return this.set(Math.clamp(0, 255, value) << GREEN_OFFSET | (representation & GREEN_FILTER));
<ide> }
<ide>
<ide>
<ide> * @return this
<ide> */
<ide> public Color setGreen(float value) {
<del> return setGreen((byte) (value * MAX));
<add> return setGreen(value * MAX);
<ide> }
<ide>
<ide>
<ide> * @return this
<ide> */
<ide> public Color setBlue(int value) {
<del> return this.set(value << BLUE_OFFSET | (representation & BLUE_FILTER));
<add> return this.set(Math.clamp(0, 255, value) << BLUE_OFFSET | (representation & BLUE_FILTER));
<ide> }
<ide>
<ide> /**
<ide> * @return this
<ide> */
<ide> public Color setBlue(float value) {
<del> return setBlue((byte) (value * MAX));
<add> return setBlue(value * MAX);
<ide> }
<ide>
<ide> /**
<ide> * @return this
<ide> */
<ide> public Color setAlpha(int value) {
<del> return this.set(value | (representation & ALPHA_FILTER));
<add> return this.set(Math.clamp(0, 255, value) | (representation & ALPHA_FILTER));
<ide> }
<ide>
<ide> /**
<ide> * @return this
<ide> */
<ide> public Color setAlpha(float value) {
<del> return setAlpha((byte) (value * MAX));
<add> return setAlpha(value * MAX);
<ide> }
<ide>
<ide> |
|
Java | apache-2.0 | 08a8da3979233f771425c9ad18740a3153d0b80e | 0 | ebyhr/presto,smartnews/presto,Praveen2112/presto,smartnews/presto,ebyhr/presto,smartnews/presto,ebyhr/presto,ebyhr/presto,smartnews/presto,ebyhr/presto,Praveen2112/presto,Praveen2112/presto,Praveen2112/presto,smartnews/presto,Praveen2112/presto | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.operator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.airlift.slice.XxHash64;
import io.trino.array.LongBigArray;
import io.trino.spi.Page;
import io.trino.spi.PageBuilder;
import io.trino.spi.block.Block;
import io.trino.spi.block.DictionaryBlock;
import io.trino.spi.block.LongArrayBlock;
import io.trino.spi.block.RunLengthEncodedBlock;
import io.trino.spi.type.AbstractLongType;
import io.trino.spi.type.Type;
import io.trino.spi.type.TypeOperators;
import io.trino.sql.gen.JoinCompiler;
import io.trino.type.BlockTypeOperators;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.profile.GCProfiler;
import org.openjdk.jmh.runner.RunnerException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static io.trino.jmh.Benchmarks.benchmark;
import static io.trino.operator.UpdateMemory.NOOP;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.VarcharType.VARCHAR;
import static it.unimi.dsi.fastutil.HashCommon.arraySize;
@SuppressWarnings("MethodMayBeStatic")
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(2)
@Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
public class BenchmarkGroupByHash
{
private static final int POSITIONS = 10_000_000;
private static final String GROUP_COUNT_STRING = "3000000";
private static final int GROUP_COUNT = Integer.parseInt(GROUP_COUNT_STRING);
private static final int EXPECTED_SIZE = 10_000;
private static final TypeOperators TYPE_OPERATORS = new TypeOperators();
private static final BlockTypeOperators TYPE_OPERATOR_FACTORY = new BlockTypeOperators(TYPE_OPERATORS);
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object groupByHashPreCompute(BenchmarkData data)
{
GroupByHash groupByHash = new MultiChannelGroupByHash(data.getTypes(), data.getChannels(), data.getHashChannel(), EXPECTED_SIZE, false, getJoinCompiler(), TYPE_OPERATOR_FACTORY, NOOP);
addInputPagesToHash(groupByHash, data.getPages());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public List<Page> benchmarkHashPosition(BenchmarkData data)
{
InterpretedHashGenerator hashGenerator = new InterpretedHashGenerator(data.getTypes(), data.getChannels(), TYPE_OPERATOR_FACTORY);
ImmutableList.Builder<Page> results = ImmutableList.builderWithExpectedSize(data.getPages().size());
for (Page page : data.getPages()) {
long[] hashes = new long[page.getPositionCount()];
for (int position = 0; position < page.getPositionCount(); position++) {
hashes[position] = hashGenerator.hashPosition(position, page);
}
results.add(page.appendColumn(new LongArrayBlock(page.getPositionCount(), Optional.empty(), hashes)));
}
return results.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object addPagePreCompute(BenchmarkData data)
{
GroupByHash groupByHash = new MultiChannelGroupByHash(data.getTypes(), data.getChannels(), data.getHashChannel(), EXPECTED_SIZE, false, getJoinCompiler(), TYPE_OPERATOR_FACTORY, NOOP);
addInputPagesToHash(groupByHash, data.getPages());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object bigintGroupByHash(SingleChannelBenchmarkData data)
{
GroupByHash groupByHash = new BigintGroupByHash(0, data.getHashEnabled(), EXPECTED_SIZE, NOOP);
addInputPagesToHash(groupByHash, data.getPages());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public long baseline(BaselinePagesData data)
{
int hashSize = arraySize(GROUP_COUNT, 0.9f);
int mask = hashSize - 1;
long[] table = new long[hashSize];
Arrays.fill(table, -1);
long groupIds = 0;
for (Page page : data.getPages()) {
Block block = page.getBlock(0);
int positionCount = block.getPositionCount();
for (int position = 0; position < positionCount; position++) {
long value = block.getLong(position, 0);
int tablePosition = (int) (value & mask);
while (table[tablePosition] != -1 && table[tablePosition] != value) {
tablePosition++;
}
if (table[tablePosition] == -1) {
table[tablePosition] = value;
groupIds++;
}
}
}
return groupIds;
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public long baselineBigArray(BaselinePagesData data)
{
int hashSize = arraySize(GROUP_COUNT, 0.9f);
int mask = hashSize - 1;
LongBigArray table = new LongBigArray(-1);
table.ensureCapacity(hashSize);
long groupIds = 0;
for (Page page : data.getPages()) {
Block block = page.getBlock(0);
int positionCount = block.getPositionCount();
for (int position = 0; position < positionCount; position++) {
long value = BIGINT.getLong(block, position);
int tablePosition = (int) XxHash64.hash(value) & mask;
while (table.get(tablePosition) != -1 && table.get(tablePosition) != value) {
tablePosition++;
}
if (table.get(tablePosition) == -1) {
table.set(tablePosition, value);
groupIds++;
}
}
}
return groupIds;
}
private static void addInputPagesToHash(GroupByHash groupByHash, List<Page> pages)
{
for (Page page : pages) {
Work<?> work = groupByHash.addPage(page);
boolean finished;
do {
finished = work.process();
}
while (!finished);
}
}
private static List<Page> createBigintPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled, boolean useMixedBlockTypes)
{
List<Type> types = Collections.nCopies(channelCount, BIGINT);
ImmutableList.Builder<Page> pages = ImmutableList.builder();
if (hashEnabled) {
types = ImmutableList.copyOf(Iterables.concat(types, ImmutableList.of(BIGINT)));
}
PageBuilder pageBuilder = new PageBuilder(types);
int pageCount = 0;
for (int position = 0; position < positionCount; position++) {
int rand = ThreadLocalRandom.current().nextInt(groupCount);
pageBuilder.declarePosition();
for (int numChannel = 0; numChannel < channelCount; numChannel++) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(numChannel), rand);
}
if (hashEnabled) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(channelCount), AbstractLongType.hash(rand));
}
if (pageBuilder.isFull()) {
Page page = pageBuilder.build();
pageBuilder.reset();
if (useMixedBlockTypes) {
if (pageCount % 3 == 0) {
pages.add(page);
}
else if (pageCount % 3 == 1) {
// rle page
Block[] blocks = new Block[page.getChannelCount()];
for (int channel = 0; channel < blocks.length; ++channel) {
blocks[channel] = new RunLengthEncodedBlock(page.getBlock(channel).getSingleValueBlock(0), page.getPositionCount());
}
pages.add(new Page(blocks));
}
else {
// dictionary page
int[] positions = IntStream.range(0, page.getPositionCount()).toArray();
Block[] blocks = new Block[page.getChannelCount()];
for (int channel = 0; channel < page.getChannelCount(); ++channel) {
blocks[channel] = new DictionaryBlock(page.getBlock(channel), positions);
}
pages.add(new Page(blocks));
}
}
else {
pages.add(page);
}
pageCount++;
}
}
pages.add(pageBuilder.build());
return pages.build();
}
private static List<Page> createVarcharPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled)
{
List<Type> types = Collections.nCopies(channelCount, VARCHAR);
ImmutableList.Builder<Page> pages = ImmutableList.builder();
if (hashEnabled) {
types = ImmutableList.copyOf(Iterables.concat(types, ImmutableList.of(BIGINT)));
}
PageBuilder pageBuilder = new PageBuilder(types);
for (int position = 0; position < positionCount; position++) {
int rand = ThreadLocalRandom.current().nextInt(groupCount);
Slice value = Slices.wrappedBuffer(ByteBuffer.allocate(4).putInt(rand));
pageBuilder.declarePosition();
for (int channel = 0; channel < channelCount; channel++) {
VARCHAR.writeSlice(pageBuilder.getBlockBuilder(channel), value);
}
if (hashEnabled) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(channelCount), XxHash64.hash(value));
}
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pages.build();
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class BaselinePagesData
{
@Param("1")
private int channelCount = 1;
@Param("false")
private boolean hashEnabled;
@Param(GROUP_COUNT_STRING)
private int groupCount;
private List<Page> pages;
@Setup
public void setup()
{
pages = createBigintPages(POSITIONS, groupCount, channelCount, hashEnabled, false);
}
public List<Page> getPages()
{
return pages;
}
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class SingleChannelBenchmarkData
{
@Param("1")
private int channelCount = 1;
@Param({"true", "false"})
private boolean hashEnabled = true;
private List<Page> pages;
private List<Type> types;
private int[] channels;
@Setup
public void setup()
{
setup(false);
}
public void setup(boolean useMixedBlockTypes)
{
pages = createBigintPages(POSITIONS, GROUP_COUNT, channelCount, hashEnabled, useMixedBlockTypes);
types = Collections.nCopies(1, BIGINT);
channels = new int[1];
for (int i = 0; i < 1; i++) {
channels[i] = i;
}
}
public List<Page> getPages()
{
return pages;
}
public List<Type> getTypes()
{
return types;
}
public boolean getHashEnabled()
{
return hashEnabled;
}
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class BenchmarkData
{
@Param({"1", "5", "10", "15", "20"})
private int channelCount = 1;
// todo add more group counts when JMH support programmatic ability to set OperationsPerInvocation
@Param(GROUP_COUNT_STRING)
private int groupCount = GROUP_COUNT;
@Param({"true", "false"})
private boolean hashEnabled;
@Param({"VARCHAR", "BIGINT"})
private String dataType = "VARCHAR";
private List<Page> pages;
private Optional<Integer> hashChannel;
private List<Type> types;
private int[] channels;
@Setup
public void setup()
{
switch (dataType) {
case "VARCHAR":
types = Collections.nCopies(channelCount, VARCHAR);
pages = createVarcharPages(POSITIONS, groupCount, channelCount, hashEnabled);
break;
case "BIGINT":
types = Collections.nCopies(channelCount, BIGINT);
pages = createBigintPages(POSITIONS, groupCount, channelCount, hashEnabled, false);
break;
default:
throw new UnsupportedOperationException("Unsupported dataType");
}
hashChannel = hashEnabled ? Optional.of(channelCount) : Optional.empty();
channels = new int[channelCount];
for (int i = 0; i < channelCount; i++) {
channels[i] = i;
}
}
public List<Page> getPages()
{
return pages;
}
public Optional<Integer> getHashChannel()
{
return hashChannel;
}
public List<Type> getTypes()
{
return types;
}
public int[] getChannels()
{
return channels;
}
}
private static JoinCompiler getJoinCompiler()
{
return new JoinCompiler(TYPE_OPERATORS);
}
static {
// pollute BigintGroupByHash profile by different block types
SingleChannelBenchmarkData singleChannelBenchmarkData = new SingleChannelBenchmarkData();
singleChannelBenchmarkData.setup(true);
BenchmarkGroupByHash hash = new BenchmarkGroupByHash();
for (int i = 0; i < 5; ++i) {
hash.bigintGroupByHash(singleChannelBenchmarkData);
}
}
public static void main(String[] args)
throws RunnerException
{
// assure the benchmarks are valid before running
BenchmarkData data = new BenchmarkData();
data.setup();
new BenchmarkGroupByHash().groupByHashPreCompute(data);
new BenchmarkGroupByHash().addPagePreCompute(data);
SingleChannelBenchmarkData singleChannelBenchmarkData = new SingleChannelBenchmarkData();
singleChannelBenchmarkData.setup();
new BenchmarkGroupByHash().bigintGroupByHash(singleChannelBenchmarkData);
benchmark(BenchmarkGroupByHash.class)
.withOptions(optionsBuilder -> optionsBuilder
.addProfiler(GCProfiler.class)
.jvmArgs("-Xmx10g"))
.run();
}
}
| core/trino-main/src/test/java/io/trino/operator/BenchmarkGroupByHash.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.operator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.airlift.slice.XxHash64;
import io.trino.array.LongBigArray;
import io.trino.spi.Page;
import io.trino.spi.PageBuilder;
import io.trino.spi.block.Block;
import io.trino.spi.block.DictionaryBlock;
import io.trino.spi.block.LongArrayBlock;
import io.trino.spi.block.RunLengthEncodedBlock;
import io.trino.spi.type.AbstractLongType;
import io.trino.spi.type.Type;
import io.trino.spi.type.TypeOperators;
import io.trino.sql.gen.JoinCompiler;
import io.trino.type.BlockTypeOperators;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OperationsPerInvocation;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.profile.GCProfiler;
import org.openjdk.jmh.runner.RunnerException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static io.trino.jmh.Benchmarks.benchmark;
import static io.trino.operator.UpdateMemory.NOOP;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.VarcharType.VARCHAR;
import static it.unimi.dsi.fastutil.HashCommon.arraySize;
@SuppressWarnings("MethodMayBeStatic")
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(2)
@Warmup(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.AverageTime)
public class BenchmarkGroupByHash
{
private static final int POSITIONS = 10_000_000;
private static final String GROUP_COUNT_STRING = "3000000";
private static final int GROUP_COUNT = Integer.parseInt(GROUP_COUNT_STRING);
private static final int EXPECTED_SIZE = 10_000;
private static final TypeOperators TYPE_OPERATORS = new TypeOperators();
private static final BlockTypeOperators TYPE_OPERATOR_FACTORY = new BlockTypeOperators(TYPE_OPERATORS);
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object groupByHashPreCompute(BenchmarkData data)
{
GroupByHash groupByHash = new MultiChannelGroupByHash(data.getTypes(), data.getChannels(), data.getHashChannel(), EXPECTED_SIZE, false, getJoinCompiler(), TYPE_OPERATOR_FACTORY, NOOP);
addInputPagesToHash(groupByHash, data.getPages());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public List<Page> benchmarkHashPosition(BenchmarkData data)
{
InterpretedHashGenerator hashGenerator = new InterpretedHashGenerator(data.getTypes(), data.getChannels(), TYPE_OPERATOR_FACTORY);
ImmutableList.Builder<Page> results = ImmutableList.builderWithExpectedSize(data.getPages().size());
for (Page page : data.getPages()) {
long[] hashes = new long[page.getPositionCount()];
for (int position = 0; position < page.getPositionCount(); position++) {
hashes[position] = hashGenerator.hashPosition(position, page);
}
results.add(page.appendColumn(new LongArrayBlock(page.getPositionCount(), Optional.empty(), hashes)));
}
return results.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object addPagePreCompute(BenchmarkData data)
{
GroupByHash groupByHash = new MultiChannelGroupByHash(data.getTypes(), data.getChannels(), data.getHashChannel(), EXPECTED_SIZE, false, getJoinCompiler(), TYPE_OPERATOR_FACTORY, NOOP);
addInputPagesToHash(groupByHash, data.getPages());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public Object bigintGroupByHash(SingleChannelBenchmarkData data)
{
GroupByHash groupByHash = new BigintGroupByHash(0, data.getHashEnabled(), EXPECTED_SIZE, NOOP);
addInputPagesToHash(groupByHash, data.getPages());
ImmutableList.Builder<Page> pages = ImmutableList.builder();
PageBuilder pageBuilder = new PageBuilder(groupByHash.getTypes());
for (int groupId = 0; groupId < groupByHash.getGroupCount(); groupId++) {
pageBuilder.declarePosition();
groupByHash.appendValuesTo(groupId, pageBuilder, 0);
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pageBuilder.build();
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public long baseline(BaselinePagesData data)
{
int hashSize = arraySize(GROUP_COUNT, 0.9f);
int mask = hashSize - 1;
long[] table = new long[hashSize];
Arrays.fill(table, -1);
long groupIds = 0;
for (Page page : data.getPages()) {
Block block = page.getBlock(0);
int positionCount = block.getPositionCount();
for (int position = 0; position < positionCount; position++) {
long value = block.getLong(position, 0);
int tablePosition = (int) (value & mask);
while (table[tablePosition] != -1 && table[tablePosition] != value) {
tablePosition++;
}
if (table[tablePosition] == -1) {
table[tablePosition] = value;
groupIds++;
}
}
}
return groupIds;
}
@Benchmark
@OperationsPerInvocation(POSITIONS)
public long baselineBigArray(BaselinePagesData data)
{
int hashSize = arraySize(GROUP_COUNT, 0.9f);
int mask = hashSize - 1;
LongBigArray table = new LongBigArray(-1);
table.ensureCapacity(hashSize);
long groupIds = 0;
for (Page page : data.getPages()) {
Block block = page.getBlock(0);
int positionCount = block.getPositionCount();
for (int position = 0; position < positionCount; position++) {
long value = BIGINT.getLong(block, position);
int tablePosition = (int) XxHash64.hash(value) & mask;
while (table.get(tablePosition) != -1 && table.get(tablePosition) != value) {
tablePosition++;
}
if (table.get(tablePosition) == -1) {
table.set(tablePosition, value);
groupIds++;
}
}
}
return groupIds;
}
private static void addInputPagesToHash(GroupByHash groupByHash, List<Page> pages)
{
for (Page page : pages) {
Work<?> work = groupByHash.addPage(page);
boolean finished;
do {
finished = work.process();
}
while (!finished);
}
}
private static List<Page> createBigintPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled, boolean pollute)
{
List<Type> types = Collections.nCopies(channelCount, BIGINT);
ImmutableList.Builder<Page> pages = ImmutableList.builder();
if (hashEnabled) {
types = ImmutableList.copyOf(Iterables.concat(types, ImmutableList.of(BIGINT)));
}
PageBuilder pageBuilder = new PageBuilder(types);
int pageCount = 0;
for (int position = 0; position < positionCount; position++) {
int rand = ThreadLocalRandom.current().nextInt(groupCount);
pageBuilder.declarePosition();
for (int numChannel = 0; numChannel < channelCount; numChannel++) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(numChannel), rand);
}
if (hashEnabled) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(channelCount), AbstractLongType.hash(rand));
}
if (pageBuilder.isFull()) {
Page page = pageBuilder.build();
pageBuilder.reset();
if (pollute) {
if (pageCount % 3 == 0) {
pages.add(page);
}
else if (pageCount % 3 == 1) {
// rle page
Block[] blocks = new Block[page.getChannelCount()];
for (int channel = 0; channel < blocks.length; ++channel) {
blocks[channel] = new RunLengthEncodedBlock(page.getBlock(channel).getSingleValueBlock(0), page.getPositionCount());
}
pages.add(new Page(blocks));
}
else {
// dictionary page
int[] positions = IntStream.range(0, page.getPositionCount()).toArray();
Block[] blocks = new Block[page.getChannelCount()];
for (int channel = 0; channel < page.getChannelCount(); ++channel) {
blocks[channel] = new DictionaryBlock(page.getBlock(channel), positions);
}
pages.add(new Page(blocks));
}
}
else {
pages.add(page);
}
pageCount++;
}
}
pages.add(pageBuilder.build());
return pages.build();
}
private static List<Page> createVarcharPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled)
{
List<Type> types = Collections.nCopies(channelCount, VARCHAR);
ImmutableList.Builder<Page> pages = ImmutableList.builder();
if (hashEnabled) {
types = ImmutableList.copyOf(Iterables.concat(types, ImmutableList.of(BIGINT)));
}
PageBuilder pageBuilder = new PageBuilder(types);
for (int position = 0; position < positionCount; position++) {
int rand = ThreadLocalRandom.current().nextInt(groupCount);
Slice value = Slices.wrappedBuffer(ByteBuffer.allocate(4).putInt(rand));
pageBuilder.declarePosition();
for (int channel = 0; channel < channelCount; channel++) {
VARCHAR.writeSlice(pageBuilder.getBlockBuilder(channel), value);
}
if (hashEnabled) {
BIGINT.writeLong(pageBuilder.getBlockBuilder(channelCount), XxHash64.hash(value));
}
if (pageBuilder.isFull()) {
pages.add(pageBuilder.build());
pageBuilder.reset();
}
}
pages.add(pageBuilder.build());
return pages.build();
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class BaselinePagesData
{
@Param("1")
private int channelCount = 1;
@Param("false")
private boolean hashEnabled;
@Param(GROUP_COUNT_STRING)
private int groupCount;
private List<Page> pages;
@Setup
public void setup()
{
pages = createBigintPages(POSITIONS, groupCount, channelCount, hashEnabled, false);
}
public List<Page> getPages()
{
return pages;
}
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class SingleChannelBenchmarkData
{
@Param("1")
private int channelCount = 1;
@Param({"true", "false"})
private boolean hashEnabled = true;
private List<Page> pages;
private List<Type> types;
private int[] channels;
@Setup
public void setup()
{
setup(false);
}
public void setup(boolean pollute)
{
pages = createBigintPages(POSITIONS, GROUP_COUNT, channelCount, hashEnabled, pollute);
types = Collections.nCopies(1, BIGINT);
channels = new int[1];
for (int i = 0; i < 1; i++) {
channels[i] = i;
}
}
public List<Page> getPages()
{
return pages;
}
public List<Type> getTypes()
{
return types;
}
public boolean getHashEnabled()
{
return hashEnabled;
}
}
@SuppressWarnings("FieldMayBeFinal")
@State(Scope.Thread)
public static class BenchmarkData
{
@Param({"1", "5", "10", "15", "20"})
private int channelCount = 1;
// todo add more group counts when JMH support programmatic ability to set OperationsPerInvocation
@Param(GROUP_COUNT_STRING)
private int groupCount = GROUP_COUNT;
@Param({"true", "false"})
private boolean hashEnabled;
@Param({"VARCHAR", "BIGINT"})
private String dataType = "VARCHAR";
private List<Page> pages;
private Optional<Integer> hashChannel;
private List<Type> types;
private int[] channels;
@Setup
public void setup()
{
switch (dataType) {
case "VARCHAR":
types = Collections.nCopies(channelCount, VARCHAR);
pages = createVarcharPages(POSITIONS, groupCount, channelCount, hashEnabled);
break;
case "BIGINT":
types = Collections.nCopies(channelCount, BIGINT);
pages = createBigintPages(POSITIONS, groupCount, channelCount, hashEnabled, false);
break;
default:
throw new UnsupportedOperationException("Unsupported dataType");
}
hashChannel = hashEnabled ? Optional.of(channelCount) : Optional.empty();
channels = new int[channelCount];
for (int i = 0; i < channelCount; i++) {
channels[i] = i;
}
}
public List<Page> getPages()
{
return pages;
}
public Optional<Integer> getHashChannel()
{
return hashChannel;
}
public List<Type> getTypes()
{
return types;
}
public int[] getChannels()
{
return channels;
}
}
private static JoinCompiler getJoinCompiler()
{
return new JoinCompiler(TYPE_OPERATORS);
}
static {
// pollute BigintGroupByHash profile by different block types
SingleChannelBenchmarkData singleChannelBenchmarkData = new SingleChannelBenchmarkData();
singleChannelBenchmarkData.setup(true);
BenchmarkGroupByHash hash = new BenchmarkGroupByHash();
for (int i = 0; i < 5; ++i) {
hash.bigintGroupByHash(singleChannelBenchmarkData);
}
}
public static void main(String[] args)
throws RunnerException
{
// assure the benchmarks are valid before running
BenchmarkData data = new BenchmarkData();
data.setup();
new BenchmarkGroupByHash().groupByHashPreCompute(data);
new BenchmarkGroupByHash().addPagePreCompute(data);
SingleChannelBenchmarkData singleChannelBenchmarkData = new SingleChannelBenchmarkData();
singleChannelBenchmarkData.setup();
new BenchmarkGroupByHash().bigintGroupByHash(singleChannelBenchmarkData);
benchmark(BenchmarkGroupByHash.class)
.withOptions(optionsBuilder -> optionsBuilder
.addProfiler(GCProfiler.class)
.jvmArgs("-Xmx10g"))
.run();
}
}
| Rename pollute to useMixedBlockTypes
Addressing comment from https://github.com/trinodb/trino/pull/9510
which was ommited by mistake
| core/trino-main/src/test/java/io/trino/operator/BenchmarkGroupByHash.java | Rename pollute to useMixedBlockTypes | <ide><path>ore/trino-main/src/test/java/io/trino/operator/BenchmarkGroupByHash.java
<ide> }
<ide> }
<ide>
<del> private static List<Page> createBigintPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled, boolean pollute)
<add> private static List<Page> createBigintPages(int positionCount, int groupCount, int channelCount, boolean hashEnabled, boolean useMixedBlockTypes)
<ide> {
<ide> List<Type> types = Collections.nCopies(channelCount, BIGINT);
<ide> ImmutableList.Builder<Page> pages = ImmutableList.builder();
<ide> if (pageBuilder.isFull()) {
<ide> Page page = pageBuilder.build();
<ide> pageBuilder.reset();
<del> if (pollute) {
<add> if (useMixedBlockTypes) {
<ide> if (pageCount % 3 == 0) {
<ide> pages.add(page);
<ide> }
<ide> setup(false);
<ide> }
<ide>
<del> public void setup(boolean pollute)
<del> {
<del> pages = createBigintPages(POSITIONS, GROUP_COUNT, channelCount, hashEnabled, pollute);
<add> public void setup(boolean useMixedBlockTypes)
<add> {
<add> pages = createBigintPages(POSITIONS, GROUP_COUNT, channelCount, hashEnabled, useMixedBlockTypes);
<ide> types = Collections.nCopies(1, BIGINT);
<ide> channels = new int[1];
<ide> for (int i = 0; i < 1; i++) { |
|
Java | bsd-3-clause | 189bbe60dff78b0153b5347221af5ae52c463f1d | 0 | Moliholy/cvmfs-java | package com.molina.cvmfs.history;
import com.molina.cvmfs.common.DatabaseObject;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Wrapper around CernVM-FS 2.1.x repository history databases
*
* @author Jose Molina Colmenero
*/
public class History extends DatabaseObject {
private String schema;
private String fqrn;
public History(File databaseFile) throws IllegalStateException, SQLException {
super(databaseFile);
readProperties();
}
public static History open(String historyPath) throws SQLException {
return new History(new File(historyPath));
}
public String getSchema() {
return schema;
}
public String getFqrn() {
return fqrn;
}
private void readProperties() throws SQLException {
Map<String, Object> properties = readPropertiesTable();
assert (properties.containsKey("schema") &&
properties.get("schema").equals("1.0"));
if (properties.containsKey("fqrn"))
fqrn = (String) properties.get("fqrn");
schema = (String) properties.get("schema");
}
private RevisionTag getTagByQuery(String query) throws SQLException {
Statement statement = createStatement();
ResultSet result = statement.executeQuery(query);
if (result != null && result.next()) {
RevisionTag rt = new RevisionTag(result);
statement.close();
result.close();
return rt;
}
return null;
}
public List<RevisionTag> listTags() throws SQLException {
Statement statement = createStatement();
ResultSet results = statement.executeQuery(RevisionTag.sqlQueryAll());
List<RevisionTag> tags = new ArrayList<RevisionTag>();
while (results.next()) {
tags.add(new RevisionTag(results));
}
results.getStatement().close();
results.close();
return tags;
}
public RevisionTag getTagByName(String name) throws SQLException {
return getTagByQuery(RevisionTag.sqlQueryName(name));
}
public RevisionTag getTagByRevision(int revision) throws SQLException {
return getTagByQuery(RevisionTag.sqlQueryRevision(revision));
}
public RevisionTag getTagByDate(long timestamp) throws SQLException {
return getTagByQuery(RevisionTag.sqlQueryDate(timestamp));
}
}
| src/main/java/com/molina/cvmfs/history/History.java | package com.molina.cvmfs.history;
import com.molina.cvmfs.common.DatabaseObject;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Wrapper around CernVM-FS 2.1.x repository history databases
*
* @author Jose Molina Colmenero
*/
public class History extends DatabaseObject {
private String schema;
private String fqrn;
public History(File databaseFile) throws IllegalStateException, SQLException {
super(databaseFile);
readProperties();
}
public static History open(String historyPath) throws SQLException {
return new History(new File(historyPath));
}
public String getSchema() {
return schema;
}
public String getFqrn() {
return fqrn;
}
private void readProperties() throws SQLException {
Map<String, Object> properties = readPropertiesTable();
assert (properties.containsKey("schema") &&
properties.get("schema").equals("1.0"));
if (properties.containsKey("fqrn"))
fqrn = (String) properties.get("fqrn");
schema = (String) properties.get("schema");
}
private RevisionTag getTagByQuery(String query) throws SQLException {
ResultSet result = runSQL(query);
if (result != null && result.next()) {
RevisionTag rt = new RevisionTag(result);
result.getStatement().close();
result.close();
return rt;
}
return null;
}
public List<RevisionTag> listTags() throws SQLException {
ResultSet results = runSQL(RevisionTag.sqlQueryAll());
List<RevisionTag> tags = new ArrayList<RevisionTag>();
while (results.next()) {
tags.add(new RevisionTag(results));
}
results.getStatement().close();
results.close();
return tags;
}
public RevisionTag getTagByName(String name) throws SQLException {
return getTagByQuery(RevisionTag.sqlQueryName(name));
}
public RevisionTag getTagByRevision(int revision) throws SQLException {
return getTagByQuery(RevisionTag.sqlQueryRevision(revision));
}
public RevisionTag getTagByDate(long timestamp) throws SQLException {
return getTagByQuery(RevisionTag.sqlQueryDate(timestamp));
}
}
| Fix new statements
| src/main/java/com/molina/cvmfs/history/History.java | Fix new statements | <ide><path>rc/main/java/com/molina/cvmfs/history/History.java
<ide> import java.io.File;
<ide> import java.sql.ResultSet;
<ide> import java.sql.SQLException;
<add>import java.sql.Statement;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> }
<ide>
<ide> private RevisionTag getTagByQuery(String query) throws SQLException {
<del> ResultSet result = runSQL(query);
<add> Statement statement = createStatement();
<add> ResultSet result = statement.executeQuery(query);
<ide> if (result != null && result.next()) {
<ide> RevisionTag rt = new RevisionTag(result);
<del> result.getStatement().close();
<add> statement.close();
<ide> result.close();
<ide> return rt;
<ide> }
<ide> }
<ide>
<ide> public List<RevisionTag> listTags() throws SQLException {
<del> ResultSet results = runSQL(RevisionTag.sqlQueryAll());
<add> Statement statement = createStatement();
<add> ResultSet results = statement.executeQuery(RevisionTag.sqlQueryAll());
<ide> List<RevisionTag> tags = new ArrayList<RevisionTag>();
<ide> while (results.next()) {
<ide> tags.add(new RevisionTag(results)); |
|
Java | apache-2.0 | 16c0ca1be7f71eadf6e563623e51564c9c3a3034 | 0 | rajapulau/qiscus-sdk-android,qiscus/qiscus-sdk-android | /*
* Copyright (c) 2016 Qiscus.
*
* 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.qiscus.sdk.data.remote;
import android.net.Uri;
import android.support.v4.util.Pair;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.qiscus.sdk.Qiscus;
import com.qiscus.sdk.R;
import com.qiscus.sdk.data.model.QiscusAccount;
import com.qiscus.sdk.data.model.QiscusChatRoom;
import com.qiscus.sdk.data.model.QiscusComment;
import com.qiscus.sdk.util.QiscusAndroidUtil;
import com.qiscus.sdk.util.QiscusDateUtil;
import com.qiscus.sdk.util.QiscusErrorLogger;
import com.qiscus.sdk.util.QiscusFileUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.Util;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import rx.Emitter;
import rx.Observable;
import rx.exceptions.OnErrorThrowable;
/**
* Created on : August 18, 2016
* Author : zetbaitsu
* Name : Zetra
* GitHub : https://github.com/zetbaitsu
*/
public enum QiscusApi {
INSTANCE;
private final OkHttpClient httpClient;
private String baseUrl;
private final Api api;
QiscusApi() {
baseUrl = Qiscus.getAppServer();
httpClient = new OkHttpClient.Builder()
.build();
api = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
.create(Api.class);
}
public static QiscusApi getInstance() {
return INSTANCE;
}
public Observable<QiscusAccount> loginOrRegister(String email, String password, String username, String avatarUrl) {
return api.loginOrRegister(email, password, username, avatarUrl)
.map(QiscusApiParser::parseQiscusAccount);
}
public Observable<QiscusChatRoom> getChatRoom(String withEmail, String distinctId, String options) {
return api.createOrGetChatRoom(Qiscus.getToken(), Collections.singletonList(withEmail), distinctId, options)
.map(QiscusApiParser::parseQiscusChatRoom);
}
public Observable<QiscusChatRoom> createGroupChatRoom(String name, List<String> emails, String avatarUrl, String options) {
return api.createGroupChatRoom(Qiscus.getToken(), name, emails, avatarUrl, options)
.map(QiscusApiParser::parseQiscusChatRoom);
}
public Observable<QiscusChatRoom> getGroupChatRoom(String uniqueId, String name, String avatarUrl, String options) {
return api.createOrGetGroupChatRoom(Qiscus.getToken(), uniqueId, name, avatarUrl, options)
.map(QiscusApiParser::parseQiscusChatRoom);
}
public Observable<QiscusChatRoom> getChatRoom(int roomId) {
return api.getChatRoom(Qiscus.getToken(), roomId)
.map(QiscusApiParser::parseQiscusChatRoom);
}
public Observable<Pair<QiscusChatRoom, List<QiscusComment>>> getChatRoomComments(int roomId) {
return api.getChatRoom(Qiscus.getToken(), roomId)
.map(QiscusApiParser::parseQiscusChatRoomWithComments);
}
public Observable<QiscusComment> getComments(int roomId, int topicId, int lastCommentId) {
return api.getComments(Qiscus.getToken(), topicId, lastCommentId, false)
.flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray()))
.map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId, topicId));
}
public Observable<QiscusComment> getCommentsAfter(int roomId, int topicId, int lastCommentId) {
return api.getComments(Qiscus.getToken(), topicId, lastCommentId, true)
.flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray()))
.map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId, topicId));
}
public Observable<QiscusComment> postComment(QiscusComment qiscusComment) {
return api.postComment(Qiscus.getToken(), qiscusComment.getMessage(),
qiscusComment.getTopicId(), qiscusComment.getUniqueId(), qiscusComment.getRawType(),
qiscusComment.getExtraPayload())
.map(jsonElement -> {
JsonObject jsonComment = jsonElement.getAsJsonObject()
.get("results").getAsJsonObject().get("comment").getAsJsonObject();
qiscusComment.setId(jsonComment.get("id").getAsInt());
qiscusComment.setCommentBeforeId(jsonComment.get("comment_before_id").getAsInt());
return qiscusComment;
});
}
public Observable<QiscusComment> sync(int lastCommentId) {
return api.sync(Qiscus.getToken(), lastCommentId)
.onErrorReturn(throwable -> {
QiscusErrorLogger.print("Sync", throwable);
return null;
})
.filter(jsonElement -> jsonElement != null)
.flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray()))
.map(jsonElement -> {
JsonObject jsonComment = jsonElement.getAsJsonObject();
return QiscusApiParser.parseQiscusComment(jsonElement,
jsonComment.get("room_id").getAsInt(), jsonComment.get("topic_id").getAsInt());
});
}
public Observable<QiscusComment> sync() {
QiscusComment latestComment = Qiscus.getDataStore().getLatestComment();
if (latestComment == null || !QiscusAndroidUtil.getString(R.string.qiscus_today)
.equals(QiscusDateUtil.toTodayOrDate(latestComment.getTime()))) {
return Observable.empty();
}
return sync(latestComment.getId());
}
public Observable<Uri> uploadFile(File file, ProgressListener progressListener) {
return Observable.create(subscriber -> {
long fileLength = file.length();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("token", Qiscus.getToken())
.addFormDataPart("file", file.getName(),
new CountingFileRequestBody(file, totalBytes -> {
int progress = (int) (totalBytes * 100 / fileLength);
progressListener.onProgress(progress);
}))
.build();
Request request = new Request.Builder()
.url(baseUrl + "/api/v2/mobile/upload")
.post(requestBody).build();
try {
Response response = httpClient.newCall(request).execute();
JSONObject responseJ = new JSONObject(response.body().string());
String result = responseJ.getJSONObject("results").getJSONObject("file").getString("url");
subscriber.onNext(Uri.parse(result));
subscriber.onCompleted();
} catch (IOException | JSONException e) {
QiscusErrorLogger.print("UploadFile", e);
subscriber.onError(e);
}
}, Emitter.BackpressureMode.BUFFER);
}
public Observable<File> downloadFile(int topicId, String url, String fileName, ProgressListener progressListener) {
return Observable.create(subscriber -> {
InputStream inputStream = null;
FileOutputStream fos = null;
try {
Request request = new Request.Builder().url(url).build();
Response response = httpClient.newCall(request).execute();
File output = new File(QiscusFileUtil.generateFilePath(fileName, topicId));
fos = new FileOutputStream(output.getPath());
if (!response.isSuccessful()) {
throw new IOException();
} else {
ResponseBody responseBody = response.body();
long fileLength = responseBody.contentLength();
inputStream = responseBody.byteStream();
byte[] buffer = new byte[4096];
long total = 0;
int count;
while ((count = inputStream.read(buffer)) != -1) {
total += count;
long totalCurrent = total;
if (fileLength > 0) {
progressListener.onProgress((totalCurrent * 100 / fileLength));
}
fos.write(buffer, 0, count);
}
fos.flush();
subscriber.onNext(output);
subscriber.onCompleted();
}
} catch (Exception e) {
throw OnErrorThrowable.from(OnErrorThrowable.addValueAsLastCause(e, url));
} finally {
try {
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ignored) {
//Do nothing
}
}
}, Emitter.BackpressureMode.BUFFER);
}
public Observable<QiscusChatRoom> updateChatRoom(int roomId, String name, String avatarUrl, String options) {
return api.updateChatRoom(Qiscus.getToken(), roomId, name, avatarUrl, options)
.map(QiscusApiParser::parseQiscusChatRoom)
.doOnNext(qiscusChatRoom -> Qiscus.getDataStore().addOrUpdate(qiscusChatRoom));
}
public Observable<Void> updateCommentStatus(int roomId, int lastReadId, int lastReceivedId) {
return api.updateCommentStatus(Qiscus.getToken(), roomId, lastReadId, lastReceivedId)
.map(jsonElement -> null);
}
public Observable<Void> registerFcmToken(String fcmToken) {
return api.registerFcmToken(Qiscus.getToken(), "android", fcmToken)
.map(jsonElement -> null);
}
public Observable<List<QiscusComment>> searchComments(String query, int lastCommentId) {
return searchComments(query, 0, lastCommentId);
}
public Observable<List<QiscusComment>> searchComments(String query, int roomId, int lastCommentId) {
return api.searchComments(Qiscus.getToken(), query, roomId, lastCommentId)
.flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray()))
.map(jsonElement -> {
JsonObject jsonComment = jsonElement.getAsJsonObject();
return QiscusApiParser.parseQiscusComment(jsonElement,
jsonComment.get("room_id").getAsInt(), jsonComment.get("topic_id").getAsInt());
})
.toList();
}
private interface Api {
@FormUrlEncoded
@POST("/api/v2/mobile/login_or_register")
Observable<JsonElement> loginOrRegister(@Field("email") String email,
@Field("password") String password,
@Field("username") String username,
@Field("avatar_url") String avatarUrl);
@FormUrlEncoded
@POST("/api/v2/mobile/get_or_create_room_with_target")
Observable<JsonElement> createOrGetChatRoom(@Field("token") String token,
@Field("emails[]") List<String> emails,
@Field("distinct_id") String distinctId,
@Field("options") String options);
@FormUrlEncoded
@POST("/api/v2/mobile/create_room")
Observable<JsonElement> createGroupChatRoom(@Field("token") String token,
@Field("name") String name,
@Field("participants[]") List<String> emails,
@Field("avatar_url") String avatarUrl,
@Field("options") String options);
@FormUrlEncoded
@POST("/api/v2/mobile/get_or_create_room_with_unique_id")
Observable<JsonElement> createOrGetGroupChatRoom(@Field("token") String token,
@Field("unique_id") String uniqueId,
@Field("name") String name,
@Field("avatar_url") String avatarUrl,
@Field("options") String options);
@GET("/api/v2/mobile/get_room_by_id")
Observable<JsonElement> getChatRoom(@Query("token") String token,
@Query("id") int roomId);
@GET("/api/v2/mobile/load_comments")
Observable<JsonElement> getComments(@Query("token") String token,
@Query("topic_id") int topicId,
@Query("last_comment_id") int lastCommentId,
@Query("after") boolean after);
@FormUrlEncoded
@POST("/api/v2/mobile/post_comment")
Observable<JsonElement> postComment(@Field("token") String token,
@Field("comment") String message,
@Field("topic_id") int topicId,
@Field("unique_temp_id") String uniqueId,
@Field("type") String type,
@Field("payload") String payload);
@GET("/api/v2/mobile/sync")
Observable<JsonElement> sync(@Query("token") String token,
@Query("last_received_comment_id") int lastCommentId);
@FormUrlEncoded
@POST("/api/v2/mobile/update_room")
Observable<JsonElement> updateChatRoom(@Field("token") String token,
@Field("id") int id,
@Field("room_name") String name,
@Field("avatar_url") String avatarUrl,
@Field("options") String options);
@FormUrlEncoded
@POST("/api/v2/mobile/update_comment_status")
Observable<JsonElement> updateCommentStatus(@Field("token") String token,
@Field("room_id") int roomId,
@Field("last_comment_read_id") int lastReadId,
@Field("last_comment_received_id") int lastReceivedId);
@FormUrlEncoded
@POST("/api/v2/mobile/set_user_device_token")
Observable<JsonElement> registerFcmToken(@Field("token") String token,
@Field("device_platform") String devicePlatform,
@Field("device_token") String fcmToken);
@POST("/api/v2/mobile/search_messages")
Observable<JsonElement> searchComments(@Query("token") String token,
@Query("query") String query,
@Query("room_id") int roomId,
@Query("last_comment_id") int lastCommentId);
}
private static class CountingFileRequestBody extends RequestBody {
private final File file;
private final ProgressListener progressListener;
private static final int SEGMENT_SIZE = 2048;
private CountingFileRequestBody(File file, ProgressListener progressListener) {
this.file = file;
this.progressListener = progressListener;
}
@Override
public MediaType contentType() {
return MediaType.parse("application/octet-stream");
}
@Override
public long contentLength() throws IOException {
return file.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(file);
long total = 0;
long read;
while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
total += read;
sink.flush();
progressListener.onProgress(total);
}
} finally {
Util.closeQuietly(source);
}
}
}
public interface ProgressListener {
void onProgress(long total);
}
}
| chat/src/main/java/com/qiscus/sdk/data/remote/QiscusApi.java | /*
* Copyright (c) 2016 Qiscus.
*
* 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.qiscus.sdk.data.remote;
import android.net.Uri;
import android.support.v4.util.Pair;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.qiscus.sdk.Qiscus;
import com.qiscus.sdk.R;
import com.qiscus.sdk.data.model.QiscusAccount;
import com.qiscus.sdk.data.model.QiscusChatRoom;
import com.qiscus.sdk.data.model.QiscusComment;
import com.qiscus.sdk.util.QiscusAndroidUtil;
import com.qiscus.sdk.util.QiscusDateUtil;
import com.qiscus.sdk.util.QiscusErrorLogger;
import com.qiscus.sdk.util.QiscusFileUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.Util;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import rx.Emitter;
import rx.Observable;
import rx.exceptions.OnErrorThrowable;
/**
* Created on : August 18, 2016
* Author : zetbaitsu
* Name : Zetra
* GitHub : https://github.com/zetbaitsu
*/
public enum QiscusApi {
INSTANCE;
private final OkHttpClient httpClient;
private String baseUrl;
private final Api api;
QiscusApi() {
baseUrl = Qiscus.getAppServer();
httpClient = new OkHttpClient.Builder()
.build();
api = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
.create(Api.class);
}
public static QiscusApi getInstance() {
return INSTANCE;
}
public Observable<QiscusAccount> loginOrRegister(String email, String password, String username, String avatarUrl) {
return api.loginOrRegister(email, password, username, avatarUrl)
.map(QiscusApiParser::parseQiscusAccount);
}
public Observable<QiscusChatRoom> getChatRoom(String withEmail, String distinctId, String options) {
return api.createOrGetChatRoom(Qiscus.getToken(), Collections.singletonList(withEmail), distinctId, options)
.map(QiscusApiParser::parseQiscusChatRoom);
}
public Observable<QiscusChatRoom> createGroupChatRoom(String name, List<String> emails, String avatarUrl, String options) {
return api.createGroupChatRoom(Qiscus.getToken(), name, emails, avatarUrl, options)
.map(QiscusApiParser::parseQiscusChatRoom);
}
public Observable<QiscusChatRoom> getGroupChatRoom(String uniqueId, String name, String avatarUrl, String options) {
return api.createOrGetGroupChatRoom(Qiscus.getToken(), uniqueId, name, avatarUrl, options)
.map(QiscusApiParser::parseQiscusChatRoom);
}
public Observable<QiscusChatRoom> getChatRoom(int roomId) {
return api.getChatRoom(Qiscus.getToken(), roomId)
.map(QiscusApiParser::parseQiscusChatRoom);
}
public Observable<Pair<QiscusChatRoom, List<QiscusComment>>> getChatRoomComments(int roomId) {
return api.getChatRoom(Qiscus.getToken(), roomId)
.map(QiscusApiParser::parseQiscusChatRoomWithComments);
}
public Observable<QiscusComment> getComments(int roomId, int topicId, int lastCommentId) {
return api.getComments(Qiscus.getToken(), topicId, lastCommentId, false)
.flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray()))
.map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId, topicId));
}
public Observable<QiscusComment> getCommentsAfter(int roomId, int topicId, int lastCommentId) {
return api.getComments(Qiscus.getToken(), topicId, lastCommentId, true)
.flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray()))
.map(jsonElement -> QiscusApiParser.parseQiscusComment(jsonElement, roomId, topicId));
}
public Observable<QiscusComment> postComment(QiscusComment qiscusComment) {
return api.postComment(Qiscus.getToken(), qiscusComment.getMessage(),
qiscusComment.getTopicId(), qiscusComment.getUniqueId(), qiscusComment.getRawType(),
qiscusComment.getExtraPayload())
.map(jsonElement -> {
JsonObject jsonComment = jsonElement.getAsJsonObject()
.get("results").getAsJsonObject().get("comment").getAsJsonObject();
qiscusComment.setId(jsonComment.get("id").getAsInt());
qiscusComment.setCommentBeforeId(jsonComment.get("comment_before_id").getAsInt());
return qiscusComment;
});
}
public Observable<QiscusComment> sync(int lastCommentId) {
return api.sync(Qiscus.getToken(), lastCommentId)
.onErrorReturn(throwable -> {
QiscusErrorLogger.print("Sync", throwable);
return null;
})
.filter(jsonElement -> jsonElement != null)
.flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results")
.getAsJsonObject().get("comments").getAsJsonArray()))
.map(jsonElement -> {
JsonObject jsonComment = jsonElement.getAsJsonObject();
return QiscusApiParser.parseQiscusComment(jsonElement,
jsonComment.get("room_id").getAsInt(), jsonComment.get("topic_id").getAsInt());
});
}
public Observable<QiscusComment> sync() {
QiscusComment latestComment = Qiscus.getDataStore().getLatestComment();
if (latestComment == null || !QiscusAndroidUtil.getString(R.string.qiscus_today)
.equals(QiscusDateUtil.toTodayOrDate(latestComment.getTime()))) {
return Observable.empty();
}
return sync(latestComment.getId());
}
public Observable<Uri> uploadFile(File file, ProgressListener progressListener) {
return Observable.create(subscriber -> {
long fileLength = file.length();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("token", Qiscus.getToken())
.addFormDataPart("file", file.getName(),
new CountingFileRequestBody(file, totalBytes -> {
int progress = (int) (totalBytes * 100 / fileLength);
progressListener.onProgress(progress);
}))
.build();
Request request = new Request.Builder()
.url(baseUrl + "/api/v2/mobile/upload")
.post(requestBody).build();
try {
Response response = httpClient.newCall(request).execute();
JSONObject responseJ = new JSONObject(response.body().string());
String result = responseJ.getJSONObject("results").getJSONObject("file").getString("url");
subscriber.onNext(Uri.parse(result));
subscriber.onCompleted();
} catch (IOException | JSONException e) {
QiscusErrorLogger.print("UploadFile", e);
subscriber.onError(e);
}
}, Emitter.BackpressureMode.BUFFER);
}
public Observable<File> downloadFile(int topicId, String url, String fileName, ProgressListener progressListener) {
return Observable.create(subscriber -> {
InputStream inputStream = null;
FileOutputStream fos = null;
try {
Request request = new Request.Builder().url(url).build();
Response response = httpClient.newCall(request).execute();
File output = new File(QiscusFileUtil.generateFilePath(fileName, topicId));
fos = new FileOutputStream(output.getPath());
if (!response.isSuccessful()) {
throw new IOException();
} else {
ResponseBody responseBody = response.body();
long fileLength = responseBody.contentLength();
inputStream = responseBody.byteStream();
byte[] buffer = new byte[4096];
long total = 0;
int count;
while ((count = inputStream.read(buffer)) != -1) {
total += count;
long totalCurrent = total;
if (fileLength > 0) {
progressListener.onProgress((totalCurrent * 100 / fileLength));
}
fos.write(buffer, 0, count);
}
fos.flush();
subscriber.onNext(output);
subscriber.onCompleted();
}
} catch (Exception e) {
throw OnErrorThrowable.from(OnErrorThrowable.addValueAsLastCause(e, url));
} finally {
try {
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ignored) {
//Do nothing
}
}
}, Emitter.BackpressureMode.BUFFER);
}
public Observable<QiscusChatRoom> updateChatRoom(int roomId, String name, String avatarUrl, String options) {
return api.updateChatRoom(Qiscus.getToken(), roomId, name, avatarUrl, options)
.map(QiscusApiParser::parseQiscusChatRoom)
.doOnNext(qiscusChatRoom -> Qiscus.getDataStore().addOrUpdate(qiscusChatRoom));
}
public Observable<Void> updateCommentStatus(int roomId, int lastReadId, int lastReceivedId) {
return api.updateCommentStatus(Qiscus.getToken(), roomId, lastReadId, lastReceivedId)
.map(jsonElement -> null);
}
public Observable<Void> registerFcmToken(String fcmToken) {
return api.registerFcmToken(Qiscus.getToken(), "android", fcmToken)
.map(jsonElement -> null);
}
private interface Api {
@FormUrlEncoded
@POST("/api/v2/mobile/login_or_register")
Observable<JsonElement> loginOrRegister(@Field("email") String email,
@Field("password") String password,
@Field("username") String username,
@Field("avatar_url") String avatarUrl);
@FormUrlEncoded
@POST("/api/v2/mobile/get_or_create_room_with_target")
Observable<JsonElement> createOrGetChatRoom(@Field("token") String token,
@Field("emails[]") List<String> emails,
@Field("distinct_id") String distinctId,
@Field("options") String options);
@FormUrlEncoded
@POST("/api/v2/mobile/create_room")
Observable<JsonElement> createGroupChatRoom(@Field("token") String token,
@Field("name") String name,
@Field("participants[]") List<String> emails,
@Field("avatar_url") String avatarUrl,
@Field("options") String options);
@FormUrlEncoded
@POST("/api/v2/mobile/get_or_create_room_with_unique_id")
Observable<JsonElement> createOrGetGroupChatRoom(@Field("token") String token,
@Field("unique_id") String uniqueId,
@Field("name") String name,
@Field("avatar_url") String avatarUrl,
@Field("options") String options);
@GET("/api/v2/mobile/get_room_by_id")
Observable<JsonElement> getChatRoom(@Query("token") String token,
@Query("id") int roomId);
@GET("/api/v2/mobile/load_comments")
Observable<JsonElement> getComments(@Query("token") String token,
@Query("topic_id") int topicId,
@Query("last_comment_id") int lastCommentId,
@Query("after") boolean after);
@FormUrlEncoded
@POST("/api/v2/mobile/post_comment")
Observable<JsonElement> postComment(@Field("token") String token,
@Field("comment") String message,
@Field("topic_id") int topicId,
@Field("unique_temp_id") String uniqueId,
@Field("type") String type,
@Field("payload") String payload);
@GET("/api/v2/mobile/sync")
Observable<JsonElement> sync(@Query("token") String token,
@Query("last_received_comment_id") int lastCommentId);
@FormUrlEncoded
@POST("/api/v2/mobile/update_room")
Observable<JsonElement> updateChatRoom(@Field("token") String token,
@Field("id") int id,
@Field("room_name") String name,
@Field("avatar_url") String avatarUrl,
@Field("options") String options);
@FormUrlEncoded
@POST("/api/v2/mobile/update_comment_status")
Observable<JsonElement> updateCommentStatus(@Field("token") String token,
@Field("room_id") int roomId,
@Field("last_comment_read_id") int lastReadId,
@Field("last_comment_received_id") int lastReceivedId);
@FormUrlEncoded
@POST("/api/v2/mobile/set_user_device_token")
Observable<JsonElement> registerFcmToken(@Field("token") String token,
@Field("device_platform") String devicePlatform,
@Field("device_token") String fcmToken);
}
private static class CountingFileRequestBody extends RequestBody {
private final File file;
private final ProgressListener progressListener;
private static final int SEGMENT_SIZE = 2048;
private CountingFileRequestBody(File file, ProgressListener progressListener) {
this.file = file;
this.progressListener = progressListener;
}
@Override
public MediaType contentType() {
return MediaType.parse("application/octet-stream");
}
@Override
public long contentLength() throws IOException {
return file.length();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(file);
long total = 0;
long read;
while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
total += read;
sink.flush();
progressListener.onProgress(total);
}
} finally {
Util.closeQuietly(source);
}
}
}
public interface ProgressListener {
void onProgress(long total);
}
}
| Add searching method
| chat/src/main/java/com/qiscus/sdk/data/remote/QiscusApi.java | Add searching method | <ide><path>hat/src/main/java/com/qiscus/sdk/data/remote/QiscusApi.java
<ide> .map(jsonElement -> null);
<ide> }
<ide>
<add> public Observable<List<QiscusComment>> searchComments(String query, int lastCommentId) {
<add> return searchComments(query, 0, lastCommentId);
<add> }
<add>
<add> public Observable<List<QiscusComment>> searchComments(String query, int roomId, int lastCommentId) {
<add> return api.searchComments(Qiscus.getToken(), query, roomId, lastCommentId)
<add> .flatMap(jsonElement -> Observable.from(jsonElement.getAsJsonObject().get("results")
<add> .getAsJsonObject().get("comments").getAsJsonArray()))
<add> .map(jsonElement -> {
<add> JsonObject jsonComment = jsonElement.getAsJsonObject();
<add> return QiscusApiParser.parseQiscusComment(jsonElement,
<add> jsonComment.get("room_id").getAsInt(), jsonComment.get("topic_id").getAsInt());
<add> })
<add> .toList();
<add> }
<add>
<ide> private interface Api {
<ide>
<ide> @FormUrlEncoded
<ide> Observable<JsonElement> registerFcmToken(@Field("token") String token,
<ide> @Field("device_platform") String devicePlatform,
<ide> @Field("device_token") String fcmToken);
<add>
<add> @POST("/api/v2/mobile/search_messages")
<add> Observable<JsonElement> searchComments(@Query("token") String token,
<add> @Query("query") String query,
<add> @Query("room_id") int roomId,
<add> @Query("last_comment_id") int lastCommentId);
<ide> }
<ide>
<ide> private static class CountingFileRequestBody extends RequestBody { |
|
Java | apache-2.0 | 3d685a6c3d64a9fb48925d9974ad0fc383bdfe50 | 0 | adammurdoch/native-platform,adammurdoch/native-platform,adammurdoch/native-platform,adammurdoch/native-platform | /*
* Copyright 2012 Adam Murdoch
*
* 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 net.rubygrapefruit.platform.test;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import net.rubygrapefruit.platform.*;
import net.rubygrapefruit.platform.Process;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
OptionParser optionParser = new OptionParser();
optionParser.accepts("cache-dir", "The directory to cache native libraries in").withRequiredArg();
optionParser.accepts("stat", "Display details about the specified file or directory").withRequiredArg();
optionParser.accepts("watch", "Watches for changes to the specified file or directory").withRequiredArg();
optionParser.accepts("machine", "Display details about the current machine");
OptionSet result = null;
try {
result = optionParser.parse(args);
} catch (OptionException e) {
System.err.println(e.getMessage());
System.err.println();
optionParser.printHelpOn(System.err);
System.exit(1);
}
if (result.has("cache-dir")) {
Native.init(new File(result.valueOf("cache-dir").toString()));
}
if (result.has("stat")) {
stat((String) result.valueOf("stat"));
return;
}
if (result.has("watch")) {
watch((String) result.valueOf("watch"));
return;
}
if (result.has("machine")) {
machine();
return;
}
terminal();
}
private static void terminal() {
System.out.println();
Terminals terminals = Native.get(Terminals.class);
boolean stdoutIsTerminal = terminals.isTerminal(Terminals.Output.Stdout);
boolean stderrIsTerminal = terminals.isTerminal(Terminals.Output.Stderr);
System.out.println("* Stdout: " + (stdoutIsTerminal ? "terminal" : "not a terminal"));
System.out.println("* Stderr: " + (stderrIsTerminal ? "terminal" : "not a terminal"));
if (stdoutIsTerminal) {
Terminal terminal = terminals.getTerminal(Terminals.Output.Stdout);
TerminalSize terminalSize = terminal.getTerminalSize();
System.out.println("* Terminal implementation: " + terminal);
System.out.println("* Terminal size: " + terminalSize.getCols() + " cols x " + terminalSize.getRows() + " rows");
System.out.println("* Text attributes: " + (terminal.supportsTextAttributes() ? "yes" : "no"));
System.out.println("* Color: " + (terminal.supportsColor() ? "yes" : "no"));
System.out.println("* Cursor motion: " + (terminal.supportsCursorMotion() ? "yes" : "no"));
System.out.println();
System.out.println("TEXT ATTRIBUTES");
System.out.print("[normal] ");
terminal.bold();
System.out.print("[bold]");
terminal.normal();
System.out.println(" [normal]");
System.out.println();
System.out.println("COLORS");
for (Terminal.Color color : Terminal.Color.values()) {
terminal.foreground(color);
terminal.bold();
System.out.print(String.format("[%s] ", color.toString().toLowerCase()));
terminal.normal();
System.out.print(String.format("[%s]", color.toString().toLowerCase()));
System.out.println();
}
System.out.println();
terminal.reset();
if (terminal.supportsCursorMotion()) {
System.out.println("CURSOR MOVEMENT");
System.out.println(" ");
System.out.println(" ");
System.out.print("[delete me]");
terminal.cursorLeft(11);
terminal.cursorUp(1);
terminal.cursorRight(10);
System.out.print("[4]");
terminal.cursorUp(1);
terminal.cursorLeft(3);
System.out.print("[2]");
terminal.cursorLeft(13);
System.out.print("[1]");
terminal.cursorLeft(3);
terminal.cursorDown(1);
System.out.print("[3]");
terminal.cursorDown(1);
terminal.cursorStartOfLine();
terminal.foreground(Terminal.Color.Blue).bold();
System.out.print("done");
terminal.clearToEndOfLine();
System.out.println("!");
System.out.println();
}
} else if (stderrIsTerminal) {
Terminal terminal = terminals.getTerminal(Terminals.Output.Stderr);
System.err.print("* this is ");
terminal.bold().foreground(Terminal.Color.Red);
System.err.print("red");
terminal.reset();
System.err.print(" text on ");
terminal.bold();
System.err.print("stderr");
terminal.reset();
System.err.println(".");
}
}
private static void machine() {
System.out.println();
System.out.println("* JVM: " + System.getProperty("java.vm.vendor") + ' ' + System.getProperty("java.version"));
System.out.println("* OS (JVM): " + System.getProperty("os.name") + ' ' + System.getProperty("os.version") + ' ' + System.getProperty("os.arch"));
SystemInfo systemInfo = Native.get(SystemInfo.class);
System.out.println("* OS (Kernel): " + systemInfo.getKernelName() + ' ' + systemInfo.getKernelVersion() + ' ' + systemInfo.getArchitectureName() + " (" + systemInfo.getArchitecture() + ")");
Process process = Native.get(Process.class);
System.out.println("* PID: " + process.getProcessId());
FileSystems fileSystems = Native.get(FileSystems.class);
System.out.println("* File systems: ");
for (FileSystem fileSystem : fileSystems.getFileSystems()) {
System.out.println(String.format(" * %s -> %s (type: %s %s, case sensitive: %s, case preserving: %s)",
fileSystem.getMountPoint(), fileSystem.getDeviceName(), fileSystem.getFileSystemType(),
fileSystem.isRemote() ? "remote" : "local", fileSystem.isCaseSensitive(), fileSystem.isCasePreserving()));
}
System.out.println();
}
private static void watch(String path) {
File file = new File(path);
FileWatch watch = Native.get(FileEvents.class).startWatch(file);
try {
System.out.println("Waiting ...");
for (int i = 0; i < 10; i++) {
watch.nextChange();
System.out.println("Change detected.");
}
} finally {
watch.close();
}
System.out.println("Done");
}
private static void stat(String path) {
File file = new File(path);
PosixFile stat = Native.get(PosixFiles.class).stat(file);
System.out.println();
System.out.println("* File: " + file);
System.out.println("* Type: " + stat.getType());
System.out.println(String.format("* Mode: %03o", stat.getMode()));
System.out.println();
}
}
| test-app/src/main/java/net/rubygrapefruit/platform/test/Main.java | /*
* Copyright 2012 Adam Murdoch
*
* 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 net.rubygrapefruit.platform.test;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import net.rubygrapefruit.platform.*;
import net.rubygrapefruit.platform.Process;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
OptionParser optionParser = new OptionParser();
optionParser.accepts("cache-dir", "The directory to cache native libraries in").withRequiredArg();
optionParser.accepts("stat", "Display details about the specified file").withRequiredArg();
optionParser.accepts("watch", "Watches for changes to the specified file or directory").withRequiredArg();
OptionSet result = null;
try {
result = optionParser.parse(args);
} catch (OptionException e) {
System.err.println(e.getMessage());
System.err.println();
optionParser.printHelpOn(System.err);
System.exit(1);
}
if (result.has("cache-dir")) {
Native.init(new File(result.valueOf("cache-dir").toString()));
}
if (result.has("stat")) {
stat((String) result.valueOf("stat"));
return;
}
if (result.has("watch")) {
watch((String) result.valueOf("watch"));
return;
}
System.out.println();
System.out.println("* JVM: " + System.getProperty("java.vm.vendor") + ' ' + System.getProperty("java.version"));
System.out.println("* OS (JVM): " + System.getProperty("os.name") + ' ' + System.getProperty("os.version") + ' ' + System.getProperty("os.arch"));
SystemInfo systemInfo = Native.get(SystemInfo.class);
System.out.println("* OS (Kernel): " + systemInfo.getKernelName() + ' ' + systemInfo.getKernelVersion() + ' ' + systemInfo.getArchitectureName() + " (" + systemInfo.getArchitecture() + ")");
Process process = Native.get(Process.class);
System.out.println("* PID: " + process.getProcessId());
FileSystems fileSystems = Native.get(FileSystems.class);
System.out.println("* File systems: ");
for (FileSystem fileSystem : fileSystems.getFileSystems()) {
System.out.println(String.format(" * %s -> %s (type: %s %s, case sensitive: %s, case preserving: %s)",
fileSystem.getMountPoint(), fileSystem.getDeviceName(), fileSystem.getFileSystemType(),
fileSystem.isRemote() ? "remote" : "local", fileSystem.isCaseSensitive(), fileSystem.isCasePreserving()));
}
Terminals terminals = Native.get(Terminals.class);
boolean stdoutIsTerminal = terminals.isTerminal(Terminals.Output.Stdout);
boolean stderrIsTerminal = terminals.isTerminal(Terminals.Output.Stderr);
System.out.println("* Stdout: " + (stdoutIsTerminal ? "terminal" : "not a terminal"));
System.out.println("* Stderr: " + (stderrIsTerminal ? "terminal" : "not a terminal"));
if (stdoutIsTerminal) {
Terminal terminal = terminals.getTerminal(Terminals.Output.Stdout);
TerminalSize terminalSize = terminal.getTerminalSize();
System.out.println("* Terminal implementation: " + terminal);
System.out.println("* Terminal size: " + terminalSize.getCols() + " cols x " + terminalSize.getRows() + " rows");
System.out.println("* Text attributes: " + (terminal.supportsTextAttributes() ? "yes" : "no"));
System.out.println("* Color: " + (terminal.supportsColor() ? "yes" : "no"));
System.out.println("* Cursor motion: " + (terminal.supportsCursorMotion() ? "yes" : "no"));
System.out.println();
System.out.println("TEXT ATTRIBUTES");
System.out.print("[normal] ");
terminal.bold();
System.out.print("[bold]");
terminal.normal();
System.out.println(" [normal]");
System.out.println();
System.out.println("COLORS");
for (Terminal.Color color : Terminal.Color.values()) {
terminal.foreground(color);
terminal.bold();
System.out.print(String.format("[%s] ", color.toString().toLowerCase()));
terminal.normal();
System.out.print(String.format("[%s]", color.toString().toLowerCase()));
System.out.println();
}
System.out.println();
terminal.reset();
if (terminal.supportsCursorMotion()) {
System.out.println("CURSOR MOVEMENT");
System.out.println(" ");
System.out.println(" ");
System.out.print("[delete me]");
terminal.cursorLeft(11);
terminal.cursorUp(1);
terminal.cursorRight(10);
System.out.print("[4]");
terminal.cursorUp(1);
terminal.cursorLeft(3);
System.out.print("[2]");
terminal.cursorLeft(13);
System.out.print("[1]");
terminal.cursorLeft(3);
terminal.cursorDown(1);
System.out.print("[3]");
terminal.cursorDown(1);
terminal.cursorStartOfLine();
terminal.foreground(Terminal.Color.Blue).bold();
System.out.print("done");
terminal.clearToEndOfLine();
System.out.println("!");
System.out.println();
}
} else if (stderrIsTerminal) {
Terminal terminal = terminals.getTerminal(Terminals.Output.Stderr);
System.err.print("* this is ");
terminal.bold().foreground(Terminal.Color.Red);
System.err.print("red");
terminal.reset();
System.err.print(" text on ");
terminal.bold();
System.err.print("stderr");
terminal.reset();
System.err.println(".");
}
}
private static void watch(String path) {
File file = new File(path);
FileWatch watch = Native.get(FileEvents.class).startWatch(file);
try {
System.out.println("Waiting ...");
for (int i = 0; i < 10; i++) {
watch.nextChange();
System.out.println("Change detected.");
}
} finally {
watch.close();
}
System.out.println("Done");
}
private static void stat(String path) {
File file = new File(path);
PosixFile stat = Native.get(PosixFiles.class).stat(file);
System.out.println();
System.out.println("* File: " + file);
System.out.println("* Type: " + stat.getType());
System.out.println(String.format("* Mode: %03o", stat.getMode()));
System.out.println();
}
}
| Split up the test app output into terminal and machine details.
| test-app/src/main/java/net/rubygrapefruit/platform/test/Main.java | Split up the test app output into terminal and machine details. | <ide><path>est-app/src/main/java/net/rubygrapefruit/platform/test/Main.java
<ide> public static void main(String[] args) throws IOException {
<ide> OptionParser optionParser = new OptionParser();
<ide> optionParser.accepts("cache-dir", "The directory to cache native libraries in").withRequiredArg();
<del> optionParser.accepts("stat", "Display details about the specified file").withRequiredArg();
<add> optionParser.accepts("stat", "Display details about the specified file or directory").withRequiredArg();
<ide> optionParser.accepts("watch", "Watches for changes to the specified file or directory").withRequiredArg();
<add> optionParser.accepts("machine", "Display details about the current machine");
<ide>
<ide> OptionSet result = null;
<ide> try {
<ide> return;
<ide> }
<ide>
<del> System.out.println();
<del> System.out.println("* JVM: " + System.getProperty("java.vm.vendor") + ' ' + System.getProperty("java.version"));
<del> System.out.println("* OS (JVM): " + System.getProperty("os.name") + ' ' + System.getProperty("os.version") + ' ' + System.getProperty("os.arch"));
<del>
<del> SystemInfo systemInfo = Native.get(SystemInfo.class);
<del> System.out.println("* OS (Kernel): " + systemInfo.getKernelName() + ' ' + systemInfo.getKernelVersion() + ' ' + systemInfo.getArchitectureName() + " (" + systemInfo.getArchitecture() + ")");
<del>
<del> Process process = Native.get(Process.class);
<del> System.out.println("* PID: " + process.getProcessId());
<del>
<del> FileSystems fileSystems = Native.get(FileSystems.class);
<del> System.out.println("* File systems: ");
<del> for (FileSystem fileSystem : fileSystems.getFileSystems()) {
<del> System.out.println(String.format(" * %s -> %s (type: %s %s, case sensitive: %s, case preserving: %s)",
<del> fileSystem.getMountPoint(), fileSystem.getDeviceName(), fileSystem.getFileSystemType(),
<del> fileSystem.isRemote() ? "remote" : "local", fileSystem.isCaseSensitive(), fileSystem.isCasePreserving()));
<add> if (result.has("machine")) {
<add> machine();
<add> return;
<ide> }
<ide>
<add> terminal();
<add> }
<add>
<add> private static void terminal() {
<add> System.out.println();
<ide> Terminals terminals = Native.get(Terminals.class);
<ide> boolean stdoutIsTerminal = terminals.isTerminal(Terminals.Output.Stdout);
<ide> boolean stderrIsTerminal = terminals.isTerminal(Terminals.Output.Stderr);
<ide> }
<ide> }
<ide>
<add> private static void machine() {
<add> System.out.println();
<add> System.out.println("* JVM: " + System.getProperty("java.vm.vendor") + ' ' + System.getProperty("java.version"));
<add> System.out.println("* OS (JVM): " + System.getProperty("os.name") + ' ' + System.getProperty("os.version") + ' ' + System.getProperty("os.arch"));
<add>
<add> SystemInfo systemInfo = Native.get(SystemInfo.class);
<add> System.out.println("* OS (Kernel): " + systemInfo.getKernelName() + ' ' + systemInfo.getKernelVersion() + ' ' + systemInfo.getArchitectureName() + " (" + systemInfo.getArchitecture() + ")");
<add>
<add> Process process = Native.get(Process.class);
<add> System.out.println("* PID: " + process.getProcessId());
<add>
<add> FileSystems fileSystems = Native.get(FileSystems.class);
<add> System.out.println("* File systems: ");
<add> for (FileSystem fileSystem : fileSystems.getFileSystems()) {
<add> System.out.println(String.format(" * %s -> %s (type: %s %s, case sensitive: %s, case preserving: %s)",
<add> fileSystem.getMountPoint(), fileSystem.getDeviceName(), fileSystem.getFileSystemType(),
<add> fileSystem.isRemote() ? "remote" : "local", fileSystem.isCaseSensitive(), fileSystem.isCasePreserving()));
<add> }
<add> System.out.println();
<add> }
<add>
<ide> private static void watch(String path) {
<ide> File file = new File(path);
<ide> FileWatch watch = Native.get(FileEvents.class).startWatch(file); |
|
Java | apache-2.0 | 265f09429d84ecc8ff0f5fdd6eb5eae9f3b5134b | 0 | ulfjack/bazel,safarmer/bazel,meteorcloudy/bazel,perezd/bazel,dslomov/bazel,safarmer/bazel,cushon/bazel,katre/bazel,perezd/bazel,dslomov/bazel,meteorcloudy/bazel,ulfjack/bazel,werkt/bazel,aehlig/bazel,akira-baruah/bazel,akira-baruah/bazel,ButterflyNetwork/bazel,perezd/bazel,bazelbuild/bazel,davidzchen/bazel,twitter-forks/bazel,werkt/bazel,ButterflyNetwork/bazel,perezd/bazel,ulfjack/bazel,cushon/bazel,aehlig/bazel,bazelbuild/bazel,dslomov/bazel,twitter-forks/bazel,cushon/bazel,dslomov/bazel,bazelbuild/bazel,werkt/bazel,cushon/bazel,davidzchen/bazel,davidzchen/bazel,meteorcloudy/bazel,meteorcloudy/bazel,katre/bazel,perezd/bazel,katre/bazel,davidzchen/bazel,akira-baruah/bazel,meteorcloudy/bazel,werkt/bazel,dslomov/bazel,safarmer/bazel,bazelbuild/bazel,aehlig/bazel,ulfjack/bazel,dslomov/bazel-windows,twitter-forks/bazel,werkt/bazel,ulfjack/bazel,aehlig/bazel,katre/bazel,twitter-forks/bazel,safarmer/bazel,twitter-forks/bazel,ulfjack/bazel,werkt/bazel,davidzchen/bazel,twitter-forks/bazel,akira-baruah/bazel,bazelbuild/bazel,dslomov/bazel-windows,meteorcloudy/bazel,katre/bazel,akira-baruah/bazel,davidzchen/bazel,safarmer/bazel,aehlig/bazel,dslomov/bazel-windows,ButterflyNetwork/bazel,ButterflyNetwork/bazel,davidzchen/bazel,safarmer/bazel,aehlig/bazel,perezd/bazel,ButterflyNetwork/bazel,dslomov/bazel,cushon/bazel,bazelbuild/bazel,aehlig/bazel,meteorcloudy/bazel,ButterflyNetwork/bazel,dslomov/bazel-windows,dslomov/bazel,perezd/bazel,cushon/bazel,dslomov/bazel-windows,katre/bazel,dslomov/bazel-windows,akira-baruah/bazel,twitter-forks/bazel,ulfjack/bazel | // Copyright 2018 The Bazel Authors. 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.devtools.build.android.aapt2;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import com.android.build.gradle.tasks.ResourceUsageAnalyzer;
import com.android.resources.ResourceType;
import com.android.tools.lint.checks.ResourceUsageModel;
import com.android.tools.lint.checks.ResourceUsageModel.Resource;
import com.android.tools.lint.detector.api.LintUtils;
import com.android.utils.XmlUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.devtools.build.android.aapt2.ProtoApk.ManifestVisitor;
import com.google.devtools.build.android.aapt2.ProtoApk.ReferenceVisitor;
import com.google.devtools.build.android.aapt2.ProtoApk.ResourcePackageVisitor;
import com.google.devtools.build.android.aapt2.ProtoApk.ResourceValueVisitor;
import com.google.devtools.build.android.aapt2.ProtoApk.ResourceVisitor;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.xml.sax.SAXException;
/** A resource usage analyzer tha functions on apks in protocol buffer format. */
public class ProtoResourceUsageAnalyzer extends ResourceUsageAnalyzer {
private static final Logger logger = Logger.getLogger(ProtoResourceUsageAnalyzer.class.getName());
public ProtoResourceUsageAnalyzer(Set<String> resourcePackages, Path mapping, Path logFile)
throws DOMException, ParserConfigurationException {
super(resourcePackages, null, null, null, mapping, null, logFile);
}
private static Resource parse(ResourceUsageModel model, String resourceTypeAndName) {
final Iterator<String> iterator = Splitter.on('/').split(resourceTypeAndName).iterator();
Preconditions.checkArgument(
iterator.hasNext(), "%s invalid resource name", resourceTypeAndName);
ResourceType resourceType = ResourceType.getEnum(iterator.next());
Preconditions.checkArgument(
iterator.hasNext(), "%s invalid resource name", resourceTypeAndName);
return model.getResource(resourceType, iterator.next());
}
/**
* Calculate and removes unused resource from the {@link ProtoApk}.
*
* @param apk An apk in the aapt2 proto format.
* @param classes The associated classes for the apk.
* @param destination Where to write the reduced resources.
* @param keep A list of resource urls to keep, unused or not.
* @param discard A list of resource urls to always discard.
*/
@CheckReturnValue
public ProtoApk shrink(
ProtoApk apk,
Path classes,
Path destination,
Collection<String> keep,
Collection<String> discard)
throws IOException, ParserConfigurationException, SAXException {
// record resources and manifest
apk.visitResources(
// First, collect all declarations using the declaration visitor.
// This allows the model to start with a defined set of resources to build the reference
// graph on.
apk.visitResources(new ResourceDeclarationVisitor(model())).toUsageVisitor());
recordClassUsages(classes);
// Have to give the model xml attributes with keep and discard urls.
final NamedNodeMap toolAttributes =
XmlUtils.parseDocument(
String.format(
"<resources xmlns:tools='http://schemas.android.com/tools' tools:keep='%s'"
+ " tools:discard='%s'></resources>",
keep.stream().collect(joining(",")), discard.stream().collect(joining(","))),
true)
.getDocumentElement()
.getAttributes();
for (int i = 0; i < toolAttributes.getLength(); i++) {
model().recordToolsAttributes((Attr) toolAttributes.item(i));
}
model().processToolsAttributes();
keepPossiblyReferencedResources();
final List<Resource> resources = model().getResources();
List<Resource> roots =
resources.stream().filter(r -> r.isKeep() || r.isReachable()).collect(toList());
final Set<Resource> reachable = findReachableResources(roots);
return apk.copy(
destination,
(resourceType, name) -> reachable.contains(model().getResource(resourceType, name)));
}
private Set<Resource> findReachableResources(List<Resource> roots) {
final Multimap<Resource, Resource> referenceLog = HashMultimap.create();
Deque<Resource> queue = new ArrayDeque<>(roots);
final Set<Resource> reachable = new HashSet<>();
while (!queue.isEmpty()) {
Resource resource = queue.pop();
if (resource.references != null) {
resource.references.forEach(
r -> {
referenceLog.put(r, resource);
// add if it has not been marked reachable, therefore processed.
if (!reachable.contains(r)) {
queue.add(r);
}
});
}
// if we see it, it is reachable.
reachable.add(resource);
}
// dump resource reference map:
final StringBuilder keptResourceLog = new StringBuilder();
referenceLog
.asMap()
.forEach(
(resource, referencesTo) ->
keptResourceLog
.append(printResource(resource))
.append(" => [")
.append(
referencesTo
.stream()
.map(ProtoResourceUsageAnalyzer::printResource)
.collect(joining(", ")))
.append("]\n"));
logger.fine("Kept resource references:\n" + keptResourceLog);
return reachable;
}
private static String printResource(Resource res) {
return String.format(
"{%s[isRoot: %s] = %s}",
res.getUrl(), res.isReachable() || res.isKeep(), "0x" + Integer.toHexString(res.value));
}
private static final class ResourceDeclarationVisitor implements ResourceVisitor {
private final ResourceShrinkerUsageModel model;
private final Set<Integer> packageIds = new HashSet<>();
private ResourceDeclarationVisitor(ResourceShrinkerUsageModel model) {
this.model = model;
}
@Nullable
@Override
public ManifestVisitor enteringManifest() {
return null;
}
@Override
public ResourcePackageVisitor enteringPackage(int pkgId, String packageName) {
packageIds.add(pkgId);
return (typeId, resourceType) ->
(name, resourceId) -> {
String hexId =
String.format(
"0x%s", Integer.toHexString(((pkgId << 24) | (typeId << 16) | resourceId)));
model.addDeclaredResource(resourceType, LintUtils.getFieldName(name), hexId, true);
// Skip visiting the definition when collecting declarations.
return null;
};
}
ResourceUsageVisitor toUsageVisitor() {
return new ResourceUsageVisitor(model, ImmutableSet.copyOf(packageIds));
}
}
private static final class ResourceUsageVisitor implements ResourceVisitor {
private final ResourceShrinkerUsageModel model;
private final ImmutableSet<Integer> packageIds;
private ResourceUsageVisitor(
ResourceShrinkerUsageModel model, ImmutableSet<Integer> packageIds) {
this.model = model;
this.packageIds = packageIds;
}
@Override
public ManifestVisitor enteringManifest() {
return new ManifestVisitor() {
@Override
public void accept(String name) {
ResourceUsageModel.markReachable(model.getResourceFromUrl(name));
}
@Override
public void accept(int value) {
ResourceUsageModel.markReachable(model.getResource(value));
}
};
}
@Override
public ResourcePackageVisitor enteringPackage(int pkgId, String packageName) {
return (typeId, resourceType) ->
(name, resourceId) ->
new ResourceUsageValueVisitor(
model, model.getResource(resourceType, name), packageIds);
}
}
private static final class ResourceUsageValueVisitor implements ResourceValueVisitor {
private final ResourceUsageModel model;
private final Resource declaredResource;
private final ImmutableSet<Integer> packageIds;
private ResourceUsageValueVisitor(
ResourceUsageModel model, Resource declaredResource, ImmutableSet<Integer> packageIds) {
this.model = model;
this.declaredResource = declaredResource;
this.packageIds = packageIds;
}
@Override
public ReferenceVisitor entering(Path path) {
return this;
}
@Override
public void acceptOpaqueFileType(Path path) {
try {
String pathString = path.toString();
if (pathString.endsWith(".js")) {
model.tokenizeJs(
declaredResource,
new String(java.nio.file.Files.readAllBytes(path), StandardCharsets.UTF_8));
} else if (pathString.endsWith(".css")) {
model.tokenizeCss(
declaredResource,
new String(java.nio.file.Files.readAllBytes(path), StandardCharsets.UTF_8));
} else if (pathString.endsWith(".html")) {
model.tokenizeHtml(
declaredResource,
new String(java.nio.file.Files.readAllBytes(path), StandardCharsets.UTF_8));
} else {
// Path is a reference to the apk zip -- unpack it before getting a file reference.
model.tokenizeUnknownBinary(
declaredResource,
java.nio.file.Files.copy(
path,
java.nio.file.Files.createTempFile("binary-resource", null),
StandardCopyOption.REPLACE_EXISTING)
.toFile());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void accept(String name) {
parse(model, name).addReference(declaredResource);
}
@Override
public void accept(int value) {
if (isInDeclaredPackages(value)) { // ignore references outside of scanned packages.
declaredResource.addReference(model.getResource(value));
}
}
/** Tests if the id is in any of the scanned packages. */
private boolean isInDeclaredPackages(int value) {
return packageIds.contains(value >> 24);
}
}
}
| src/tools/android/java/com/google/devtools/build/android/aapt2/ProtoResourceUsageAnalyzer.java | // Copyright 2018 The Bazel Authors. 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.devtools.build.android.aapt2;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import com.android.build.gradle.tasks.ResourceUsageAnalyzer;
import com.android.resources.ResourceType;
import com.android.tools.lint.checks.ResourceUsageModel;
import com.android.tools.lint.checks.ResourceUsageModel.Resource;
import com.android.tools.lint.detector.api.LintUtils;
import com.android.utils.XmlUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import com.google.devtools.build.android.aapt2.ProtoApk.ManifestVisitor;
import com.google.devtools.build.android.aapt2.ProtoApk.ReferenceVisitor;
import com.google.devtools.build.android.aapt2.ProtoApk.ResourcePackageVisitor;
import com.google.devtools.build.android.aapt2.ProtoApk.ResourceValueVisitor;
import com.google.devtools.build.android.aapt2.ProtoApk.ResourceVisitor;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;
import org.xml.sax.SAXException;
/** A resource usage analyzer tha functions on apks in protocol buffer format. */
public class ProtoResourceUsageAnalyzer extends ResourceUsageAnalyzer {
private static final Logger logger = Logger.getLogger(ProtoResourceUsageAnalyzer.class.getName());
public ProtoResourceUsageAnalyzer(Set<String> resourcePackages, Path mapping, Path logFile)
throws DOMException, ParserConfigurationException {
super(resourcePackages, null, null, null, mapping, null, logFile);
}
private static Resource parse(ResourceUsageModel model, String resourceTypeAndName) {
final Iterator<String> iterator = Splitter.on('/').split(resourceTypeAndName).iterator();
Preconditions.checkArgument(
iterator.hasNext(), "%s invalid resource name", resourceTypeAndName);
ResourceType resourceType = ResourceType.getEnum(iterator.next());
Preconditions.checkArgument(
iterator.hasNext(), "%s invalid resource name", resourceTypeAndName);
return model.getResource(resourceType, iterator.next());
}
/**
* Calculate and removes unused resource from the {@link ProtoApk}.
*
* @param apk An apk in the aapt2 proto format.
* @param classes The associated classes for the apk.
* @param destination Where to write the reduced resources.
* @param keep A list of resource urls to keep, unused or not.
* @param discard A list of resource urls to always discard.
*/
@CheckReturnValue
public ProtoApk shrink(
ProtoApk apk,
Path classes,
Path destination,
Collection<String> keep,
Collection<String> discard)
throws IOException, ParserConfigurationException, SAXException {
// record resources and manifest
apk.visitResources(
// First, collect all declarations using the declaration visitor.
// This allows the model to start with a defined set of resources to build the reference
// graph on.
apk.visitResources(new ResourceDeclarationVisitor(model())).toUsageVisitor());
recordClassUsages(classes);
// Have to give the model xml attributes with keep and discard urls.
final NamedNodeMap toolAttributes =
XmlUtils.parseDocument(
String.format(
"<resources xmlns:tools='http://schemas.android.com/tools' tools:keep='%s'"
+ " tools:discard='%s'></resources>",
keep.stream().collect(joining(",")), discard.stream().collect(joining(","))),
true)
.getDocumentElement()
.getAttributes();
for (int i = 0; i < toolAttributes.getLength(); i++) {
model().recordToolsAttributes((Attr) toolAttributes.item(i));
}
model().processToolsAttributes();
keepPossiblyReferencedResources();
final List<Resource> resources = model().getResources();
List<Resource> roots =
resources.stream().filter(r -> r.isKeep() || r.isReachable()).collect(toList());
final Set<Resource> reachable = findReachableResources(roots);
return apk.copy(
destination,
(resourceType, name) -> reachable.contains(model().getResource(resourceType, name)));
}
private Set<Resource> findReachableResources(List<Resource> roots) {
final Multimap<Resource, Resource> referenceLog = HashMultimap.create();
Deque<Resource> queue = new ArrayDeque<>(roots);
final Set<Resource> reachable = new HashSet<>();
while (!queue.isEmpty()) {
Resource resource = queue.pop();
if (resource.references != null) {
resource.references.forEach(
r -> {
referenceLog.put(r, resource);
queue.add(r);
});
}
// if we see it, it is reachable.
reachable.add(resource);
}
// dump resource reference map:
final StringBuilder keptResourceLog = new StringBuilder();
referenceLog
.asMap()
.forEach(
(resource, referencesTo) ->
keptResourceLog
.append(printResource(resource))
.append(" => [")
.append(
referencesTo
.stream()
.map(ProtoResourceUsageAnalyzer::printResource)
.collect(joining(", ")))
.append("]\n"));
logger.fine("Kept resource references:\n" + keptResourceLog);
return reachable;
}
private static String printResource(Resource res) {
return String.format(
"{%s[isRoot: %s] = %s}",
res.getUrl(), res.isReachable() || res.isKeep(), "0x" + Integer.toHexString(res.value));
}
private static final class ResourceDeclarationVisitor implements ResourceVisitor {
private final ResourceShrinkerUsageModel model;
private final Set<Integer> packageIds = new HashSet<>();
private ResourceDeclarationVisitor(ResourceShrinkerUsageModel model) {
this.model = model;
}
@Nullable
@Override
public ManifestVisitor enteringManifest() {
return null;
}
@Override
public ResourcePackageVisitor enteringPackage(int pkgId, String packageName) {
packageIds.add(pkgId);
return (typeId, resourceType) ->
(name, resourceId) -> {
String hexId =
String.format(
"0x%s", Integer.toHexString(((pkgId << 24) | (typeId << 16) | resourceId)));
model.addDeclaredResource(resourceType, LintUtils.getFieldName(name), hexId, true);
// Skip visiting the definition when collecting declarations.
return null;
};
}
ResourceUsageVisitor toUsageVisitor() {
return new ResourceUsageVisitor(model, ImmutableSet.copyOf(packageIds));
}
}
private static final class ResourceUsageVisitor implements ResourceVisitor {
private final ResourceShrinkerUsageModel model;
private final ImmutableSet<Integer> packageIds;
private ResourceUsageVisitor(
ResourceShrinkerUsageModel model, ImmutableSet<Integer> packageIds) {
this.model = model;
this.packageIds = packageIds;
}
@Override
public ManifestVisitor enteringManifest() {
return new ManifestVisitor() {
@Override
public void accept(String name) {
ResourceUsageModel.markReachable(model.getResourceFromUrl(name));
}
@Override
public void accept(int value) {
ResourceUsageModel.markReachable(model.getResource(value));
}
};
}
@Override
public ResourcePackageVisitor enteringPackage(int pkgId, String packageName) {
return (typeId, resourceType) ->
(name, resourceId) ->
new ResourceUsageValueVisitor(
model, model.getResource(resourceType, name), packageIds);
}
}
private static final class ResourceUsageValueVisitor implements ResourceValueVisitor {
private final ResourceUsageModel model;
private final Resource declaredResource;
private final ImmutableSet<Integer> packageIds;
private ResourceUsageValueVisitor(
ResourceUsageModel model, Resource declaredResource, ImmutableSet<Integer> packageIds) {
this.model = model;
this.declaredResource = declaredResource;
this.packageIds = packageIds;
}
@Override
public ReferenceVisitor entering(Path path) {
return this;
}
@Override
public void acceptOpaqueFileType(Path path) {
try {
String pathString = path.toString();
if (pathString.endsWith(".js")) {
model.tokenizeJs(
declaredResource,
new String(java.nio.file.Files.readAllBytes(path), StandardCharsets.UTF_8));
} else if (pathString.endsWith(".css")) {
model.tokenizeCss(
declaredResource,
new String(java.nio.file.Files.readAllBytes(path), StandardCharsets.UTF_8));
} else if (pathString.endsWith(".html")) {
model.tokenizeHtml(
declaredResource,
new String(java.nio.file.Files.readAllBytes(path), StandardCharsets.UTF_8));
} else {
// Path is a reference to the apk zip -- unpack it before getting a file reference.
model.tokenizeUnknownBinary(
declaredResource,
java.nio.file.Files.copy(
path,
java.nio.file.Files.createTempFile("binary-resource", null),
StandardCopyOption.REPLACE_EXISTING)
.toFile());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void accept(String name) {
parse(model, name).addReference(declaredResource);
}
@Override
public void accept(int value) {
if (isInDeclaredPackages(value)) { // ignore references outside of scanned packages.
declaredResource.addReference(model.getResource(value));
}
}
/** Tests if the id is in any of the scanned packages. */
private boolean isInDeclaredPackages(int value) {
return packageIds.contains(value >> 24);
}
}
}
| Optimize the shrinking pass to prevent timeouts.
RELNOTES: None
PiperOrigin-RevId: 208666806
| src/tools/android/java/com/google/devtools/build/android/aapt2/ProtoResourceUsageAnalyzer.java | Optimize the shrinking pass to prevent timeouts. | <ide><path>rc/tools/android/java/com/google/devtools/build/android/aapt2/ProtoResourceUsageAnalyzer.java
<ide> resource.references.forEach(
<ide> r -> {
<ide> referenceLog.put(r, resource);
<del> queue.add(r);
<add> // add if it has not been marked reachable, therefore processed.
<add> if (!reachable.contains(r)) {
<add> queue.add(r);
<add> }
<ide> });
<ide> }
<ide> // if we see it, it is reachable. |
|
Java | apache-2.0 | 0f2f8304d88bbec1f4c124995e9e1893ebbb8b8f | 0 | brianwernick/ExoMedia | package com.devbrackets.android.exomediademo.service;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.devbrackets.android.exomedia.AudioPlayer;
import com.devbrackets.android.exomedia.ui.widget.VideoControls;
import com.devbrackets.android.exomedia.ui.widget.VideoView;
import com.devbrackets.android.exomediademo.App;
import com.devbrackets.android.exomediademo.R;
import com.devbrackets.android.exomediademo.data.MediaItem;
import com.devbrackets.android.exomediademo.manager.PlaylistManager;
import com.devbrackets.android.exomediademo.playlist.AudioApi;
import com.devbrackets.android.exomediademo.playlist.VideoApi;
import com.devbrackets.android.exomediademo.ui.activity.StartupActivity;
import com.devbrackets.android.playlistcore.api.AudioPlayerApi;
import com.devbrackets.android.playlistcore.service.BasePlaylistService;
/**
* A simple service that extends {@link BasePlaylistService} in order to provide
* the application specific information required.
*/
public class MediaService extends BasePlaylistService<MediaItem, PlaylistManager> {
private static final int NOTIFICATION_ID = 1564; //Arbitrary
private static final int FOREGROUND_REQUEST_CODE = 332; //Arbitrary
private static final float AUDIO_DUCK_VOLUME = 0.1f;
private Bitmap defaultLargeNotificationImage;
private Bitmap largeNotificationImage;
private Bitmap lockScreenArtwork;
private NotificationTarget notificationImageTarget = new NotificationTarget();
private LockScreenTarget lockScreenImageTarget = new LockScreenTarget();
private RequestManager glide;
@Override
public void onCreate() {
super.onCreate();
glide = Glide.with(getApplicationContext());
}
@Override
protected void performOnMediaCompletion() {
performNext();
immediatelyPause = false;
}
@NonNull
@Override
protected AudioPlayerApi getNewAudioPlayer() {
return new AudioApi(new AudioPlayer(getApplicationContext()));
}
@Override
protected int getNotificationId() {
return NOTIFICATION_ID;
}
@Override
protected float getAudioDuckVolume() {
return AUDIO_DUCK_VOLUME;
}
@NonNull
@Override
protected PlaylistManager getPlaylistManager() {
return App.getPlaylistManager();
}
@NonNull
@Override
protected PendingIntent getNotificationClickPendingIntent() {
Intent intent = new Intent(getApplicationContext(), StartupActivity.class);
return PendingIntent.getActivity(getApplicationContext(), FOREGROUND_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
protected Bitmap getDefaultLargeNotificationImage() {
if (defaultLargeNotificationImage == null) {
defaultLargeNotificationImage = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
}
return defaultLargeNotificationImage;
}
@Nullable
@Override
protected Bitmap getDefaultLargeNotificationSecondaryImage() {
return null;
}
@Override
protected int getNotificationIconRes() {
return R.mipmap.ic_launcher;
}
@Override
protected int getRemoteViewIconRes() {
return R.mipmap.ic_launcher;
}
@Override
protected void updateLargeNotificationImage(int size, MediaItem playlistItem) {
glide.load(playlistItem.getThumbnailUrl()).asBitmap().into(notificationImageTarget);
}
@Override
protected void updateRemoteViewArtwork(MediaItem playlistItem) {
glide.load(playlistItem.getArtworkUrl()).asBitmap().into(lockScreenImageTarget);
}
@Nullable
@Override
protected Bitmap getRemoteViewArtwork() {
return lockScreenArtwork;
}
@Nullable
@Override
protected Bitmap getLargeNotificationImage() {
return largeNotificationImage;
}
/**
* Overridden to allow updating the Title, SubTitle, and description in
* the VideoView (VideoControls)
*/
@Override
protected boolean playVideoItem() {
if (super.playVideoItem()) {
updateVideoControls();
return true;
}
return false;
}
/**
* Helper method used to verify we can access the {@link VideoView#getVideoControls()}
* to update both the text and available next/previous buttons
*/
private void updateVideoControls() {
VideoApi videoApi = (VideoApi) getPlaylistManager().getVideoPlayer();
if (videoApi == null) {
return;
}
VideoView videoView = videoApi.getVideoView();
if (videoView == null) {
return;
}
VideoControls videoControls = videoView.getVideoControls();
if (videoControls != null) {
updateVideoControlsText(videoControls);
updateVideoControlsButtons(videoControls);
}
}
private void updateVideoControlsText(@NonNull VideoControls videoControls) {
if (currentPlaylistItem != null) {
videoControls.setTitle(currentPlaylistItem.getTitle());
videoControls.setSubTitle(currentPlaylistItem.getAlbum());
videoControls.setDescription(currentPlaylistItem.getArtist());
}
}
private void updateVideoControlsButtons(@NonNull VideoControls videoControls) {
videoControls.setPreviousButtonEnabled(getPlaylistManager().isPreviousAvailable());
videoControls.setNextButtonEnabled(getPlaylistManager().isNextAvailable());
}
/**
* A class used to listen to the loading of the large notification images and perform
* the correct functionality to update the notification once it is loaded.
* <p>
* <b>NOTE:</b> This is a Glide Image loader class
*/
private class NotificationTarget extends SimpleTarget<Bitmap> {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
largeNotificationImage = resource;
onLargeNotificationImageUpdated();
}
}
/**
* A class used to listen to the loading of the large lock screen images and perform
* the correct functionality to update the artwork once it is loaded.
* <p>
* <b>NOTE:</b> This is a Glide Image loader class
*/
private class LockScreenTarget extends SimpleTarget<Bitmap> {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
lockScreenArtwork = resource;
onRemoteViewArtworkUpdated();
}
}
}
| demo/src/main/java/com/devbrackets/android/exomediademo/service/MediaService.java | package com.devbrackets.android.exomediademo.service;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.devbrackets.android.exomedia.AudioPlayer;
import com.devbrackets.android.exomedia.ui.widget.VideoControls;
import com.devbrackets.android.exomedia.ui.widget.VideoView;
import com.devbrackets.android.exomediademo.App;
import com.devbrackets.android.exomediademo.R;
import com.devbrackets.android.exomediademo.data.MediaItem;
import com.devbrackets.android.exomediademo.manager.PlaylistManager;
import com.devbrackets.android.exomediademo.playlist.AudioApi;
import com.devbrackets.android.exomediademo.playlist.VideoApi;
import com.devbrackets.android.exomediademo.ui.activity.StartupActivity;
import com.devbrackets.android.playlistcore.api.AudioPlayerApi;
import com.devbrackets.android.playlistcore.service.BasePlaylistService;
/**
* A simple service that extends {@link BasePlaylistService} in order to provide
* the application specific information required.
*/
public class MediaService extends BasePlaylistService<MediaItem, PlaylistManager> {
private static final int NOTIFICATION_ID = 1564; //Arbitrary
private static final int FOREGROUND_REQUEST_CODE = 332; //Arbitrary
private static final float AUDIO_DUCK_VOLUME = 0.1f;
private Bitmap defaultLargeNotificationImage;
private Bitmap largeNotificationImage;
private Bitmap lockScreenArtwork;
private NotificationTarget notificationImageTarget = new NotificationTarget();
private LockScreenTarget lockScreenImageTarget = new LockScreenTarget();
private RequestManager glide;
@Override
public void onCreate() {
super.onCreate();
glide = Glide.with(getApplicationContext());
}
@Override
protected void performOnMediaCompletion() {
performNext();
immediatelyPause = false;
}
@NonNull
@Override
protected AudioPlayerApi getNewAudioPlayer() {
return new AudioApi(new AudioPlayer(getApplicationContext()));
}
@Override
protected int getNotificationId() {
return NOTIFICATION_ID;
}
@Override
protected float getAudioDuckVolume() {
return AUDIO_DUCK_VOLUME;
}
@NonNull
@Override
protected PlaylistManager getPlaylistManager() {
return App.getPlaylistManager();
}
@NonNull
@Override
protected PendingIntent getNotificationClickPendingIntent() {
Intent intent = new Intent(getApplicationContext(), StartupActivity.class);
return PendingIntent.getActivity(getApplicationContext(), FOREGROUND_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
protected Bitmap getDefaultLargeNotificationImage() {
if (defaultLargeNotificationImage == null) {
defaultLargeNotificationImage = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
}
return defaultLargeNotificationImage;
}
@Nullable
@Override
protected Bitmap getDefaultLargeNotificationSecondaryImage() {
return null;
}
@Override
protected int getNotificationIconRes() {
return R.mipmap.ic_launcher;
}
@Override
protected int getRemoteViewIconRes() {
return R.mipmap.ic_launcher;
}
@Override
protected void updateLargeNotificationImage(int size, MediaItem playlistItem) {
glide.load(playlistItem.getThumbnailUrl()).asBitmap().into(notificationImageTarget);
}
@Override
protected void updateRemoteViewArtwork(MediaItem playlistItem) {
glide.load(playlistItem.getArtworkUrl()).asBitmap().into(lockScreenImageTarget);
}
@Nullable
@Override
protected Bitmap getRemoteViewArtwork() {
return lockScreenArtwork;
}
@Nullable
@Override
protected Bitmap getLargeNotificationImage() {
return largeNotificationImage;
}
/**
* Overridden to allow updating the Title, SubTitle, and description in
* the VideoView (VideoControls)
*/
@Override
protected boolean playVideoItem() {
if (super.playVideoItem()) {
updateVideoControls();
return true;
}
return false;
}
/**
* Helper method used to verify we can access the {@link VideoView#getVideoControls()}
* to update both the text and available next/previous buttons
*/
private void updateVideoControls() {
VideoApi videoApi = (VideoApi) getPlaylistManager().getVideoPlayer();
if (videoApi == null) {
return;
}
VideoView videoView = videoApi.getVideoView();
if (videoView == null) {
return;
}
VideoControls videoControls = videoView.getVideoControls();
if (videoControls != null) {
updateVideoControlsText(videoControls);
updateVideoControlsButtons(videoControls);
}
}
private void updateVideoControlsText(@NonNull VideoControls videoControls) {
if (currentPlaylistItem != null) {
videoControls.setTitle(currentPlaylistItem.getTitle());
videoControls.setSubTitle(currentPlaylistItem.getAlbum());
videoControls.setDescription(currentPlaylistItem.getArtist());
}
}
private void updateVideoControlsButtons(@NonNull VideoControls videoControls) {
videoControls.setPreviousButtonEnabled(getPlaylistManager().isPreviousAvailable());
videoControls.setNextButtonEnabled(getPlaylistManager().isNextAvailable());
}
/**
* A class used to listen to the loading of the large notification images and perform
* the correct functionality to update the notification once it is loaded.
* <p>
* <b>NOTE:</b> This is a Picasso Image loader class
*/
private class NotificationTarget extends SimpleTarget<Bitmap> {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
largeNotificationImage = resource;
onLargeNotificationImageUpdated();
}
}
/**
* A class used to listen to the loading of the large lock screen images and perform
* the correct functionality to update the artwork once it is loaded.
* <p>
* <b>NOTE:</b> This is a Picasso Image loader class
*/
private class LockScreenTarget extends SimpleTarget<Bitmap> {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
lockScreenArtwork = resource;
onRemoteViewArtworkUpdated();
}
}
} | [Comment Cleanup] Comments mention "Picasso Image Loader Class" (#448)
Just replaced "Picasso" with "Glide" | demo/src/main/java/com/devbrackets/android/exomediademo/service/MediaService.java | [Comment Cleanup] Comments mention "Picasso Image Loader Class" (#448) | <ide><path>emo/src/main/java/com/devbrackets/android/exomediademo/service/MediaService.java
<ide> * A class used to listen to the loading of the large notification images and perform
<ide> * the correct functionality to update the notification once it is loaded.
<ide> * <p>
<del> * <b>NOTE:</b> This is a Picasso Image loader class
<add> * <b>NOTE:</b> This is a Glide Image loader class
<ide> */
<ide> private class NotificationTarget extends SimpleTarget<Bitmap> {
<ide> @Override
<ide> * A class used to listen to the loading of the large lock screen images and perform
<ide> * the correct functionality to update the artwork once it is loaded.
<ide> * <p>
<del> * <b>NOTE:</b> This is a Picasso Image loader class
<add> * <b>NOTE:</b> This is a Glide Image loader class
<ide> */
<ide> private class LockScreenTarget extends SimpleTarget<Bitmap> {
<ide> @Override |
|
Java | mit | ca454ad1fdadc80ed7a31c0fa8971d3188895f3d | 0 | meew0/AdvancedPotions | package meew0.ap.render;
import meew0.ap.backend.Color;
import meew0.ap.block.BlockAdvancedCauldron;
import meew0.ap.te.TileEntityAdvancedCauldron;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
// thanks to whoever made the tile entity rendering tutorial, much appreciated!
// :P
public class RenderTEAdvancedCauldron extends TileEntitySpecialRenderer {
public static int renderId;
public static RenderBlocks rb;
public RenderTEAdvancedCauldron() {
}
// This method is called when minecraft renders a tile entity
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float f) {
GL11.glPushMatrix();
GL11.glTranslatef((float) x, (float) y, (float) z);
TileEntityAdvancedCauldron te2 = (TileEntityAdvancedCauldron) te;
renderCauldron(te2, te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, te.blockType);
GL11.glPopMatrix();
}
// And this method actually renders your tile entity
public void renderCauldron(TileEntityAdvancedCauldron te, World world, int x, int y, int z, Block block) {
// Tessellator tess = Tessellator.instance;
// float f = block.getLightValue(world, x, y, z);
// int l = world.getLightBrightnessForSkyBlocks(x, y, z, 0);
// int l1 = l % 65536;
// int l2 = l / 65536;
// tess.setColorOpaque_F(f, f, f);
// OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) l1, (float) l2);
//
// int dir = world.getBlockMetadata(x, y, z);
//
GL11.glPushMatrix();
// GL11.glTranslatef(0.5F, 0, 0.5F);
// GL11.glRotatef(dir * (-90F), 0F, 1F, 0F);
// GL11.glTranslatef(-0.5F, 0, -0.5F);
//bindTexture(new ResourceLocation("advancedpotions:textures/blocks/potion_base.png"));
double dy = BlockAdvancedCauldron.getRenderLiquidLevel(te.getWaterLevel());
Color c = te.color;
// tess.startDrawingQuads();
// tess.setNormal(0, 1, 0);
// tess.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
// tess.addVertex(0, dy, 0);
// tess.addVertex(0, dy, 1);
// tess.addVertex(1, dy, 1);
// tess.addVertex(1, dy, 0);
// tess.draw();
int par1 = 0;
int par2 = 0;
int par4 = 1;
double par5 = dy;
int zLevel = 1;
IIcon par3Icon = BlockAdvancedCauldron.potionIcon;
// RenderBlocks rb = new RenderBlocks(Minecraft.getMinecraft().theWorld);
//
// rb.renderFaceYPos(block, (double) x, (double) ((float) y - 1.0F + dy), (double) z, par3Icon);
rb.renderFaceYPos(block, (double) x, (double) ((float) y - 1.0f + dy), (double) z, par3Icon);
/* Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
tessellator.addVertexWithUV(0.0, par5, (double) zLevel, (double) par3Icon.getMinU(), (double) par3Icon.getMaxV());
tessellator.addVertexWithUV(1.0, par5, (double) zLevel, (double) par3Icon.getMaxU(), (double) par3Icon.getMaxV());
tessellator.addVertexWithUV(1.0, par5, (double) zLevel - 1.0, (double) par3Icon.getMaxU(), (double) par3Icon.getMinV());
tessellator.addVertexWithUV(0.0, par5, (double) zLevel - 1.0, (double) par3Icon.getMinU(), (double) par3Icon.getMinV());
tessellator.draw();*/
GL11.glPopMatrix();
}
@Override
public void func_147496_a(World world) {
rb = new RenderBlocks(world);
}
}
| main/java/meew0/ap/render/RenderTEAdvancedCauldron.java | package meew0.ap.render;
import meew0.ap.backend.Color;
import meew0.ap.block.BlockAdvancedCauldron;
import meew0.ap.te.TileEntityAdvancedCauldron;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
// thanks to whoever made the tile entity rendering tutorial, much appreciated!
// :P
public class RenderTEAdvancedCauldron extends TileEntitySpecialRenderer {
public static int renderId;
public RenderTEAdvancedCauldron() {
}
// This method is called when minecraft renders a tile entity
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float f) {
GL11.glPushMatrix();
GL11.glTranslatef((float) x, (float) y, (float) z);
TileEntityAdvancedCauldron te2 = (TileEntityAdvancedCauldron) te;
renderCauldron(te2, te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, te.blockType);
GL11.glPopMatrix();
}
// And this method actually renders your tile entity
public void renderCauldron(TileEntityAdvancedCauldron te, World world, int x, int y, int z, Block block) {
// Tessellator tess = Tessellator.instance;
// float f = block.getLightValue(world, x, y, z);
// int l = world.getLightBrightnessForSkyBlocks(x, y, z, 0);
// int l1 = l % 65536;
// int l2 = l / 65536;
// tess.setColorOpaque_F(f, f, f);
// OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) l1, (float) l2);
//
// int dir = world.getBlockMetadata(x, y, z);
//
GL11.glPushMatrix();
// GL11.glTranslatef(0.5F, 0, 0.5F);
// GL11.glRotatef(dir * (-90F), 0F, 1F, 0F);
// GL11.glTranslatef(-0.5F, 0, -0.5F);
//bindTexture(new ResourceLocation("advancedpotions:textures/blocks/potion_base.png"));
double dy = BlockAdvancedCauldron.getRenderLiquidLevel(te.getWaterLevel());
Color c = te.color;
// tess.startDrawingQuads();
// tess.setNormal(0, 1, 0);
// tess.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
// tess.addVertex(0, dy, 0);
// tess.addVertex(0, dy, 1);
// tess.addVertex(1, dy, 1);
// tess.addVertex(1, dy, 0);
// tess.draw();
int par1 = 0;
int par2 = 0;
int par4 = 1;
double par5 = dy;
int zLevel = 1;
IIcon par3Icon = BlockAdvancedCauldron.potionIcon;
// RenderBlocks rb = new RenderBlocks(Minecraft.getMinecraft().theWorld);
//
// rb.renderFaceYPos(block, (double) x, (double) ((float) y - 1.0F + dy), (double) z, par3Icon);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
tessellator.addVertexWithUV(0.0, par5, (double) zLevel, (double) par3Icon.getMinU(), (double) par3Icon.getMaxV());
tessellator.addVertexWithUV(1.0, par5, (double) zLevel, (double) par3Icon.getMaxU(), (double) par3Icon.getMaxV());
tessellator.addVertexWithUV(1.0, par5, (double) zLevel - 1.0, (double) par3Icon.getMaxU(), (double) par3Icon.getMinV());
tessellator.addVertexWithUV(0.0, par5, (double) zLevel - 1.0, (double) par3Icon.getMinU(), (double) par3Icon.getMinV());
tessellator.draw();
GL11.glPopMatrix();
}
}
| Changed TESR from tessellator to RenderBlocks, still doesn't work.
| main/java/meew0/ap/render/RenderTEAdvancedCauldron.java | Changed TESR from tessellator to RenderBlocks, still doesn't work. | <ide><path>ain/java/meew0/ap/render/RenderTEAdvancedCauldron.java
<ide> import meew0.ap.block.BlockAdvancedCauldron;
<ide> import meew0.ap.te.TileEntityAdvancedCauldron;
<ide> import net.minecraft.block.Block;
<del>import net.minecraft.client.renderer.Tessellator;
<add>import net.minecraft.client.renderer.RenderBlocks;
<ide> import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
<ide> import net.minecraft.tileentity.TileEntity;
<ide> import net.minecraft.util.IIcon;
<ide>
<ide> public class RenderTEAdvancedCauldron extends TileEntitySpecialRenderer {
<ide> public static int renderId;
<add>
<add> public static RenderBlocks rb;
<ide>
<ide> public RenderTEAdvancedCauldron() {
<ide> }
<ide> // RenderBlocks rb = new RenderBlocks(Minecraft.getMinecraft().theWorld);
<ide> //
<ide> // rb.renderFaceYPos(block, (double) x, (double) ((float) y - 1.0F + dy), (double) z, par3Icon);
<del> Tessellator tessellator = Tessellator.instance;
<add>
<add> rb.renderFaceYPos(block, (double) x, (double) ((float) y - 1.0f + dy), (double) z, par3Icon);
<add>
<add>
<add>/* Tessellator tessellator = Tessellator.instance;
<ide> tessellator.startDrawingQuads();
<ide> tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
<ide> tessellator.addVertexWithUV(0.0, par5, (double) zLevel, (double) par3Icon.getMinU(), (double) par3Icon.getMaxV());
<ide> tessellator.addVertexWithUV(1.0, par5, (double) zLevel, (double) par3Icon.getMaxU(), (double) par3Icon.getMaxV());
<ide> tessellator.addVertexWithUV(1.0, par5, (double) zLevel - 1.0, (double) par3Icon.getMaxU(), (double) par3Icon.getMinV());
<ide> tessellator.addVertexWithUV(0.0, par5, (double) zLevel - 1.0, (double) par3Icon.getMinU(), (double) par3Icon.getMinV());
<del> tessellator.draw();
<add> tessellator.draw();*/
<add>
<ide>
<ide>
<ide> GL11.glPopMatrix();
<ide> }
<ide>
<add> @Override
<add> public void func_147496_a(World world) {
<add> rb = new RenderBlocks(world);
<add> }
<ide> } |
|
Java | apache-2.0 | 800127c434bad7372bd8102bd9f94b1b1d3b8bbe | 0 | google/graphicsfuzz,google/graphicsfuzz,google/graphicsfuzz,google/graphicsfuzz,google/graphicsfuzz,google/graphicsfuzz,google/graphicsfuzz | /*
* Copyright 2018 The GraphicsFuzz Project 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
*
* 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 com.graphicsfuzz.shadersets;
import com.google.gson.JsonObject;
import com.graphicsfuzz.common.util.IShaderSet;
import com.graphicsfuzz.common.util.IShaderSetExperiment;
import com.graphicsfuzz.common.util.JsonHelper;
import com.graphicsfuzz.common.util.LocalShaderSet;
import com.graphicsfuzz.common.util.LocalShaderSetExperiement;
import com.graphicsfuzz.gifsequencewriter.GifSequenceWriter;
import com.graphicsfuzz.server.thrift.FuzzerServiceManager;
import com.graphicsfuzz.server.thrift.ImageJobResult;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RunShaderFamily {
private static final Logger LOGGER = LoggerFactory.getLogger(RunShaderFamily.class);
public static void main(String[] args) {
try {
mainHelper(args, null);
} catch (ArgumentParserException exception) {
exception.getParser().handleError(exception);
System.exit(1);
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
public static void mainHelper(
String[] args,
FuzzerServiceManager.Iface managerOverride)
throws ShaderDispatchException, InterruptedException, IOException, ArgumentParserException {
ArgumentParser parser = ArgumentParsers.newArgumentParser("RunShaderFamily")
.defaultHelp(true)
.description("Get images for all shaders in a shader set.");
parser.addArgument("--verbose")
.action(Arguments.storeTrue())
.help("Verbose output.");
parser.addArgument("--server")
.help(
"URL of server to use for sending get image requests.")
.type(String.class);
parser.addArgument("--token")
.help("The token of the client used for get image requests. Used with --server.")
.type(String.class);
parser.addArgument("--output")
.help("Output directory.")
.setDefault(new File("."))
.type(File.class);
parser.addArgument("shader_family")
.help("Shader family directory, or prefix of single shader job")
.type(String.class);
Namespace ns = parser.parseArgs(args);
final boolean verbose = ns.get("verbose");
final String shaderFamily = ns.get("shader_family");
final String server = ns.get("server");
final String token = ns.get("token");
final File outputDir = ns.get("output");
if (managerOverride != null && (server == null || token == null)) {
throw new ArgumentParserException(
"Must supply server (dummy string) and token when executing in server process.",
parser);
}
if (server != null) {
if (token == null) {
throw new ArgumentParserException("Must supply token with server.", parser);
}
}
IShaderDispatcher imageGenerator =
server == null
? new LocalShaderDispatcher(false)
: new RemoteShaderDispatcher(
server + "/manageAPI",
token,
managerOverride,
new AtomicLong());
FileUtils.forceMkdir(outputDir);
if (!new File(shaderFamily).isDirectory()) {
if (!new File(shaderFamily + ".json").exists()) {
throw new ArgumentParserException(
"Shader family must be a directory or the prefix of a single shader job.", parser);
}
// Special case: run get image on a single shader.
runShader(outputDir, shaderFamily, imageGenerator,
Optional.empty());
return;
}
IShaderSet shaderSet = new LocalShaderSet(new File(shaderFamily));
runShaderFamily(shaderSet, outputDir, imageGenerator);
}
public static int runShaderFamily(IShaderSet shaderSet, File experimentOutDir,
IShaderDispatcher imageGenerator)
throws ShaderDispatchException, InterruptedException, IOException {
int numShadersRun = 0;
IShaderSetExperiment experiment =
new LocalShaderSetExperiement(
experimentOutDir.toString(),
shaderSet);
if (experiment.getReferenceImage() == null && experiment.getReferenceTextFile() == null) {
runShader(
experimentOutDir,
FilenameUtils.removeExtension(shaderSet.getReference().toString()),
imageGenerator,
Optional.empty());
++numShadersRun;
}
if (experiment.getReferenceImage() == null) {
LOGGER.info("Recipient failed to render, so skipping variants.");
return numShadersRun;
}
for (File variant : shaderSet.getVariants()) {
boolean foundImageOrTextFile =
experiment
.getVariantImages()
.anyMatch(f ->
FilenameUtils.removeExtension(f.getName())
.equals(FilenameUtils.removeExtension(variant.getName())))
||
experiment
.getVariantTextFiles()
.anyMatch(f ->
FilenameUtils.removeExtension(f.getName())
.equals(FilenameUtils.removeExtension(variant.getName())));
if (foundImageOrTextFile) {
LOGGER.info("Skipping {} because we already have a result.", variant);
} else {
try {
runShader(
experimentOutDir,
FilenameUtils.removeExtension(variant.toString()),
imageGenerator,
Optional.of(new ImageData(experiment.getReferenceImage())));
} catch (Exception err) {
LOGGER.error("runShader() raise exception on {}", variant);
err.printStackTrace();
}
++numShadersRun;
}
}
return numShadersRun;
}
public static ImageJobResult runShader(
File outputDir,
String shaderJobPrefix,
IShaderDispatcher imageGenerator,
Optional<ImageData> referenceImage)
throws ShaderDispatchException, InterruptedException, IOException {
final String shaderName = new File(shaderJobPrefix).getName();
final File outputImage = new File(outputDir, shaderName + ".png");
final File outputText = new File(outputDir, shaderName + ".txt");
LOGGER.info("Shader set experiment: {} ", shaderJobPrefix);
ImageJobResult res = imageGenerator.getImage(shaderJobPrefix, outputImage, false);
if (res.isSetLog()) {
FileUtils.writeStringToFile(outputText, res.getLog(), Charset.defaultCharset());
}
if (res.isSetPNG()) {
FileUtils.writeByteArrayToFile(outputImage, res.getPNG());
}
// Create gif when there is two image files set. This may happen not only for NONDET state,
// but also in case of Sanity error after a nondet.
if (res.isSetPNG() && res.isSetPNG2()) {
// we can dump both images
File outputNondet1 = new File(outputDir, shaderName + "_nondet1.png");
File outputNondet2 = new File(outputDir, shaderName + "_nondet2.png");
FileUtils.writeByteArrayToFile(outputNondet1, res.getPNG());
FileUtils.writeByteArrayToFile(outputNondet2, res.getPNG2());
// Create gif
try {
BufferedImage nondetImg = ImageIO.read(
Thread.currentThread().getContextClassLoader().getResourceAsStream("nondet.png"));
BufferedImage img1 = ImageIO.read(
new ByteArrayInputStream(res.getPNG()));
BufferedImage img2 = ImageIO.read(
new ByteArrayInputStream(res.getPNG2()));
File gifFile = new File(outputDir,shaderName + ".gif");
ImageOutputStream gifOutput = new FileImageOutputStream(gifFile);
GifSequenceWriter gifWriter = new GifSequenceWriter(gifOutput, img1.getType(), 500, true);
gifWriter.writeToSequence(nondetImg);
gifWriter.writeToSequence(img1);
gifWriter.writeToSequence(img2);
gifWriter.close();
gifOutput.close();
} catch (Exception err) {
LOGGER.error("Error while creating GIF for nondet");
err.printStackTrace();
}
}
// Dump job info in JSON
File outputJson = new File(outputDir,shaderName + ".info.json");
JsonObject infoJson = makeInfoJson(res, outputImage, referenceImage);
FileUtils.writeStringToFile(outputJson,
JsonHelper.jsonToString(infoJson), Charset.defaultCharset());
return res;
}
private static JsonObject makeInfoJson(ImageJobResult res, File outputImage,
Optional<ImageData> referenceImage) {
JsonObject infoJson = new JsonObject();
if (res.isSetTimingInfo()) {
JsonObject timingInfoJson = new JsonObject();
timingInfoJson.addProperty("compilationTime", res.timingInfo.compilationTime);
timingInfoJson.addProperty("linkingTime", res.timingInfo.linkingTime);
timingInfoJson.addProperty("firstRenderTime", res.timingInfo.firstRenderTime);
timingInfoJson.addProperty("otherRendersTime", res.timingInfo.otherRendersTime);
timingInfoJson.addProperty("captureTime", res.timingInfo.captureTime);
infoJson.add("timingInfo", timingInfoJson);
}
if (res.isSetPNG() && referenceImage.isPresent()) {
try {
// Add image data, e.g. histogram distance
final Map<String, Double> imageStats = referenceImage.get().getImageDiffStats(
new ImageData(outputImage.getAbsolutePath()));
final JsonObject metrics = new JsonObject();
for (String key : imageStats.keySet()) {
metrics.addProperty(key, imageStats.get(key));
}
boolean isIdentical =
ImageUtil.identicalImages(outputImage, referenceImage.get().imageFile);
metrics.addProperty("identical", isIdentical);
infoJson.add("metrics", metrics);
} catch (FileNotFoundException err) {
err.printStackTrace();
}
}
if (res.isSetStage()) {
infoJson.addProperty("stage", res.stage.toString());
}
if (res.isSetStatus()) {
infoJson.addProperty("Status", res.getStatus().toString());
}
infoJson.addProperty("passSanityCheck", "" + res.passSanityCheck);
return infoJson;
}
}
| shadersets-util/src/main/java/com/graphicsfuzz/shadersets/RunShaderFamily.java | /*
* Copyright 2018 The GraphicsFuzz Project 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
*
* 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 com.graphicsfuzz.shadersets;
import com.google.gson.JsonObject;
import com.graphicsfuzz.common.util.IShaderSet;
import com.graphicsfuzz.common.util.IShaderSetExperiment;
import com.graphicsfuzz.common.util.JsonHelper;
import com.graphicsfuzz.common.util.LocalShaderSet;
import com.graphicsfuzz.common.util.LocalShaderSetExperiement;
import com.graphicsfuzz.gifsequencewriter.GifSequenceWriter;
import com.graphicsfuzz.server.thrift.FuzzerServiceManager;
import com.graphicsfuzz.server.thrift.ImageJobResult;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RunShaderFamily {
private static final Logger LOGGER = LoggerFactory.getLogger(RunShaderFamily.class);
public static void main(String[] args) {
try {
mainHelper(args, null);
} catch (ArgumentParserException exception) {
exception.getParser().handleError(exception);
System.exit(1);
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
public static void mainHelper(
String[] args,
FuzzerServiceManager.Iface managerOverride)
throws ShaderDispatchException, InterruptedException, IOException, ArgumentParserException {
ArgumentParser parser = ArgumentParsers.newArgumentParser("RunShaderFamily")
.defaultHelp(true)
.description("Get images for all shaders in a shader set.");
parser.addArgument("--verbose")
.action(Arguments.storeTrue())
.help("Verbose output.");
parser.addArgument("--server")
.help(
"URL of server to use for sending get image requests.")
.type(String.class);
parser.addArgument("--token")
.help("The token of the client used for get image requests. Used with --server.")
.type(String.class);
parser.addArgument("--output")
.help("Output directory.")
.setDefault(new File("."))
.type(File.class);
parser.addArgument("shader_family")
.help("Shader family directory, or prefix of single shader job")
.type(String.class);
Namespace ns = parser.parseArgs(args);
final boolean verbose = ns.get("verbose");
final String shaderFamily = ns.get("shader_family");
final String server = ns.get("server");
final String token = ns.get("token");
final File outputDir = ns.get("output");
if (managerOverride != null && (server == null || token == null)) {
throw new ArgumentParserException(
"Must supply server (dummy string) and token when executing in server process.",
parser);
}
if (server != null) {
if (token == null) {
throw new ArgumentParserException("Must supply token with server.", parser);
}
}
IShaderDispatcher imageGenerator =
server == null
? new LocalShaderDispatcher(false)
: new RemoteShaderDispatcher(
server + "/manageAPI",
token,
managerOverride,
new AtomicLong());
FileUtils.forceMkdir(outputDir);
if (!new File(shaderFamily).isDirectory()) {
if (!new File(shaderFamily + ".json").exists()) {
throw new ArgumentParserException(
"Shader family must be a directory or the prefix of a single shader job.", parser);
}
// Special case: run get image on a single shader.
runShader(outputDir, shaderFamily, imageGenerator,
Optional.empty());
return;
}
IShaderSet shaderSet = new LocalShaderSet(new File(shaderFamily));
runShaderFamily(shaderSet, outputDir, imageGenerator);
}
public static int runShaderFamily(IShaderSet shaderSet, File workDir,
IShaderDispatcher imageGenerator)
throws ShaderDispatchException, InterruptedException, IOException {
int numShadersRun = 0;
IShaderSetExperiment experiment = new LocalShaderSetExperiement(workDir.toString(), shaderSet);
if (experiment.getReferenceImage() == null && experiment.getReferenceTextFile() == null) {
runShader(workDir, FilenameUtils.removeExtension(shaderSet.getReference().getName()),
imageGenerator,
Optional.empty());
++numShadersRun;
}
if (experiment.getReferenceImage() == null) {
LOGGER.info("Recipient failed to render, so skipping variants.");
return numShadersRun;
}
for (File variant : shaderSet.getVariants()) {
boolean foundImageOrTextFile =
experiment
.getVariantImages()
.anyMatch(f ->
FilenameUtils.removeExtension(f.getName())
.equals(FilenameUtils.removeExtension(variant.getName())))
||
experiment
.getVariantTextFiles()
.anyMatch(f ->
FilenameUtils.removeExtension(f.getName())
.equals(FilenameUtils.removeExtension(variant.getName())));
if (foundImageOrTextFile) {
LOGGER.info("Skipping {} because we already have a result.", variant);
} else {
try {
runShader(workDir, FilenameUtils.removeExtension(variant.getName()), imageGenerator,
Optional.of(new ImageData(experiment.getReferenceImage())));
} catch (Exception err) {
LOGGER.error("runShader() raise exception on {}", variant);
err.printStackTrace();
}
++numShadersRun;
}
}
return numShadersRun;
}
public static ImageJobResult runShader(File workDir, String shaderJobPrefix,
IShaderDispatcher imageGenerator, Optional<ImageData> referenceImage)
throws ShaderDispatchException, InterruptedException, IOException {
final File outputImage = new File(workDir, shaderJobPrefix + ".png");
final File outputText = new File(workDir, shaderJobPrefix + ".txt");
LOGGER.info("Shader set experiment: {} ", shaderJobPrefix);
ImageJobResult res = imageGenerator.getImage(
Paths.get(workDir.getAbsolutePath(), shaderJobPrefix).toString(), outputImage, false);
if (res.isSetLog()) {
FileUtils.writeStringToFile(outputText, res.getLog(), Charset.defaultCharset());
}
if (res.isSetPNG()) {
FileUtils.writeByteArrayToFile(outputImage, res.getPNG());
}
// Create gif when there is two image files set. This may happen not only for NONDET state,
// but also in case of Sanity error after a nondet.
if (res.isSetPNG() && res.isSetPNG2()) {
// we can dump both images
File outputNondet1 = new File(workDir,
Paths.get(workDir.getAbsolutePath(), shaderJobPrefix + "_nondet1.png").toString());
File outputNondet2 = new File(workDir,
Paths.get(workDir.getAbsolutePath(), shaderJobPrefix + "_nondet2.png").toString());
FileUtils.writeByteArrayToFile(outputNondet1, res.getPNG());
FileUtils.writeByteArrayToFile(outputNondet2, res.getPNG2());
// Create gif
try {
BufferedImage nondetImg = ImageIO.read(
Thread.currentThread().getContextClassLoader().getResourceAsStream("nondet.png"));
BufferedImage img1 = ImageIO.read(
new ByteArrayInputStream(res.getPNG()));
BufferedImage img2 = ImageIO.read(
new ByteArrayInputStream(res.getPNG2()));
File gifFile = new File(workDir,
shaderJobPrefix + ".gif");
ImageOutputStream gifOutput = new FileImageOutputStream(gifFile);
GifSequenceWriter gifWriter = new GifSequenceWriter(gifOutput, img1.getType(), 500, true);
gifWriter.writeToSequence(nondetImg);
gifWriter.writeToSequence(img1);
gifWriter.writeToSequence(img2);
gifWriter.close();
gifOutput.close();
} catch (Exception err) {
LOGGER.error("Error while creating GIF for nondet");
err.printStackTrace();
}
}
// Dump job info in JSON
File outputJson = new File(workDir,shaderJobPrefix + ".info.json");
JsonObject infoJson = makeInfoJson(res, outputImage, referenceImage);
FileUtils.writeStringToFile(outputJson,
JsonHelper.jsonToString(infoJson), Charset.defaultCharset());
return res;
}
private static JsonObject makeInfoJson(ImageJobResult res, File outputImage,
Optional<ImageData> referenceImage) {
JsonObject infoJson = new JsonObject();
if (res.isSetTimingInfo()) {
JsonObject timingInfoJson = new JsonObject();
timingInfoJson.addProperty("compilationTime", res.timingInfo.compilationTime);
timingInfoJson.addProperty("linkingTime", res.timingInfo.linkingTime);
timingInfoJson.addProperty("firstRenderTime", res.timingInfo.firstRenderTime);
timingInfoJson.addProperty("otherRendersTime", res.timingInfo.otherRendersTime);
timingInfoJson.addProperty("captureTime", res.timingInfo.captureTime);
infoJson.add("timingInfo", timingInfoJson);
}
if (res.isSetPNG() && referenceImage.isPresent()) {
try {
// Add image data, e.g. histogram distance
final Map<String, Double> imageStats = referenceImage.get().getImageDiffStats(
new ImageData(outputImage.getAbsolutePath()));
final JsonObject metrics = new JsonObject();
for (String key : imageStats.keySet()) {
metrics.addProperty(key, imageStats.get(key));
}
boolean isIdentical =
ImageUtil.identicalImages(outputImage, referenceImage.get().imageFile);
metrics.addProperty("identical", isIdentical);
infoJson.add("metrics", metrics);
} catch (FileNotFoundException err) {
err.printStackTrace();
}
}
if (res.isSetStage()) {
infoJson.addProperty("stage", res.stage.toString());
}
if (res.isSetStatus()) {
infoJson.addProperty("Status", res.getStatus().toString());
}
infoJson.addProperty("passSanityCheck", "" + res.passSanityCheck);
return infoJson;
}
}
| Quick fix for running shader sets. (#48)
* Quick fix for running shader sets.
* Fix typo.
| shadersets-util/src/main/java/com/graphicsfuzz/shadersets/RunShaderFamily.java | Quick fix for running shader sets. (#48) | <ide><path>hadersets-util/src/main/java/com/graphicsfuzz/shadersets/RunShaderFamily.java
<ide> runShaderFamily(shaderSet, outputDir, imageGenerator);
<ide> }
<ide>
<del> public static int runShaderFamily(IShaderSet shaderSet, File workDir,
<add> public static int runShaderFamily(IShaderSet shaderSet, File experimentOutDir,
<ide> IShaderDispatcher imageGenerator)
<ide> throws ShaderDispatchException, InterruptedException, IOException {
<ide>
<ide> int numShadersRun = 0;
<ide>
<del> IShaderSetExperiment experiment = new LocalShaderSetExperiement(workDir.toString(), shaderSet);
<add> IShaderSetExperiment experiment =
<add> new LocalShaderSetExperiement(
<add> experimentOutDir.toString(),
<add> shaderSet);
<ide>
<ide> if (experiment.getReferenceImage() == null && experiment.getReferenceTextFile() == null) {
<del> runShader(workDir, FilenameUtils.removeExtension(shaderSet.getReference().getName()),
<add> runShader(
<add> experimentOutDir,
<add> FilenameUtils.removeExtension(shaderSet.getReference().toString()),
<ide> imageGenerator,
<ide> Optional.empty());
<ide> ++numShadersRun;
<ide> LOGGER.info("Skipping {} because we already have a result.", variant);
<ide> } else {
<ide> try {
<del> runShader(workDir, FilenameUtils.removeExtension(variant.getName()), imageGenerator,
<add> runShader(
<add> experimentOutDir,
<add> FilenameUtils.removeExtension(variant.toString()),
<add> imageGenerator,
<ide> Optional.of(new ImageData(experiment.getReferenceImage())));
<add>
<ide> } catch (Exception err) {
<ide> LOGGER.error("runShader() raise exception on {}", variant);
<ide> err.printStackTrace();
<ide> return numShadersRun;
<ide> }
<ide>
<del> public static ImageJobResult runShader(File workDir, String shaderJobPrefix,
<del> IShaderDispatcher imageGenerator, Optional<ImageData> referenceImage)
<add> public static ImageJobResult runShader(
<add> File outputDir,
<add> String shaderJobPrefix,
<add> IShaderDispatcher imageGenerator,
<add> Optional<ImageData> referenceImage)
<ide> throws ShaderDispatchException, InterruptedException, IOException {
<ide>
<del> final File outputImage = new File(workDir, shaderJobPrefix + ".png");
<del> final File outputText = new File(workDir, shaderJobPrefix + ".txt");
<add> final String shaderName = new File(shaderJobPrefix).getName();
<add> final File outputImage = new File(outputDir, shaderName + ".png");
<add> final File outputText = new File(outputDir, shaderName + ".txt");
<ide>
<ide> LOGGER.info("Shader set experiment: {} ", shaderJobPrefix);
<del> ImageJobResult res = imageGenerator.getImage(
<del> Paths.get(workDir.getAbsolutePath(), shaderJobPrefix).toString(), outputImage, false);
<add> ImageJobResult res = imageGenerator.getImage(shaderJobPrefix, outputImage, false);
<ide>
<ide> if (res.isSetLog()) {
<ide> FileUtils.writeStringToFile(outputText, res.getLog(), Charset.defaultCharset());
<ide> // but also in case of Sanity error after a nondet.
<ide> if (res.isSetPNG() && res.isSetPNG2()) {
<ide> // we can dump both images
<del> File outputNondet1 = new File(workDir,
<del> Paths.get(workDir.getAbsolutePath(), shaderJobPrefix + "_nondet1.png").toString());
<del> File outputNondet2 = new File(workDir,
<del> Paths.get(workDir.getAbsolutePath(), shaderJobPrefix + "_nondet2.png").toString());
<add> File outputNondet1 = new File(outputDir, shaderName + "_nondet1.png");
<add> File outputNondet2 = new File(outputDir, shaderName + "_nondet2.png");
<ide> FileUtils.writeByteArrayToFile(outputNondet1, res.getPNG());
<ide> FileUtils.writeByteArrayToFile(outputNondet2, res.getPNG2());
<ide>
<ide> new ByteArrayInputStream(res.getPNG()));
<ide> BufferedImage img2 = ImageIO.read(
<ide> new ByteArrayInputStream(res.getPNG2()));
<del> File gifFile = new File(workDir,
<del> shaderJobPrefix + ".gif");
<add> File gifFile = new File(outputDir,shaderName + ".gif");
<ide> ImageOutputStream gifOutput = new FileImageOutputStream(gifFile);
<ide> GifSequenceWriter gifWriter = new GifSequenceWriter(gifOutput, img1.getType(), 500, true);
<ide> gifWriter.writeToSequence(nondetImg);
<ide> }
<ide>
<ide> // Dump job info in JSON
<del> File outputJson = new File(workDir,shaderJobPrefix + ".info.json");
<add> File outputJson = new File(outputDir,shaderName + ".info.json");
<ide> JsonObject infoJson = makeInfoJson(res, outputImage, referenceImage);
<ide> FileUtils.writeStringToFile(outputJson,
<ide> JsonHelper.jsonToString(infoJson), Charset.defaultCharset()); |
|
Java | mpl-2.0 | 5f4e916d3f3a6f61a6e2180bdbad0fb6253212fe | 0 | 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 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 org.openoffice.xmerge.converter.xml;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Element;
import org.openoffice.xmerge.util.Debug;
abstract class conversionAlgorithm {
int I(String val) {
return 0;
}
}
/*
* This algorithm expects only values in millimeters, e.g. "20.3mm".
*/
class horizSize extends conversionAlgorithm {
int I(String value) {
if (value.endsWith("mm")) {
float size = (float)0.0;
String num = value.substring(0, value.length() - 2);
try {
size = Float.parseFloat(num);
} catch (Exception e) {
Debug.log(Debug.ERROR, "Error parsing " + value, e);
}
size *= 100;
return (int)size;
} else {
Debug.log(Debug.ERROR, "Unexpected value (" + value
+ ") in horizSize.I()");
return 0;
}
}
}
/*
* This algorithm does line height - can be either millimeters or
* a percentage.
*/
class lineHeight extends conversionAlgorithm {
int I(String value) {
if (value.endsWith("mm")) {
float size = (float)0.0;
String num = value.substring(0, value.length() - 2);
try {
size = Float.parseFloat(num);
} catch (Exception e) {
Debug.log(Debug.ERROR, "Error parsing " + value, e);
}
size *= 100;
return (int)size;
} else if (value.endsWith("%")) {
float size = (float)0.0;
String num = value.substring(0, value.length() - 1);
try {
size = Float.parseFloat(num);
} catch (Exception e) {
Debug.log(Debug.ERROR, "Error parsing " + value, e);
}
int retval = (int) size;
retval |= ParaStyle.LH_PCT;
return retval;
}
return 0;
}
}
/**
* This class converts alignment values.
*/
class alignment extends conversionAlgorithm {
int I(String value) {
if (value.equals("end"))
return ParaStyle.ALIGN_RIGHT;
if (value.equals("right"))
return ParaStyle.ALIGN_RIGHT;
if (value.equals("center"))
return ParaStyle.ALIGN_CENTER;
if (value.equals("justify"))
return ParaStyle.ALIGN_JUST;
if (value.equals("justified"))
return ParaStyle.ALIGN_JUST;
if (value.equals("start"))
return ParaStyle.ALIGN_LEFT;
if (value.equals("left"))
return ParaStyle.ALIGN_LEFT;
Debug.log(Debug.ERROR, "Unknown string ("
+ value + ") in alignment.I()");
return ParaStyle.ALIGN_LEFT;
}
}
/**
* <p>This class represents a paragraph <code>Style</code>.</p>
*
* <p><table border="1" cellpadding="1"><tr><td>
* Attribute </td><td>Value
* </td></tr><tr><td>
* MARGIN_LEFT </td><td>mm * 100
* </td></tr><tr><td>
* MARGIN_RIGHT </td><td>mm * 100
* </td></tr><tr><td>
* MARGIN_TOP </td><td>mm * 100 (space on top of paragraph)
* </td></tr><tr><td>
* MARGIN_BOTTOM </td><td>mm * 100
* </td></tr><tr><td>
* TEXT_INDENT </td><td>mm * 100 (first line indent)
* </td></tr><tr><td>
* LINE_HEIGHT </td><td>mm * 100, unless or'ed with LH_PCT, in which
* case it is a percentage (e.g. 200% for double spacing)
* Can also be or'ed with LH_ATLEAST. Value is stored
* in bits indicated by LH_VALUEMASK.
* </td></tr><tr><td>
* TEXT_ALIGN </td><td>ALIGN_RIGHT, ALIGN_CENTER, ALIGN_JUST, ALIGN_LEFT
* </td></tr></table></p>
*
* @author David Proulx
*/
public class ParaStyle extends Style implements Cloneable {
/** The left margin property. */
public static final int MARGIN_LEFT = 0;
/** The right margin property. */
public static final int MARGIN_RIGHT = 1;
/** The top margin property. */
public static final int MARGIN_TOP = 2;
/** The bottom margin property. */
public static final int MARGIN_BOTTOM = 3;
/** Indent left property. */
public static final int TEXT_INDENT = 4;
/** Indent right property. */
public static final int LINE_HEIGHT = 5;
/** Align text property. */
public static final int TEXT_ALIGN = 6;
// This must always be one more than highest property
/** Total number of properties. */
protected static final int NR_PROPERTIES = 7;
/**
* Array of flags indicating which attributes are set for this
* paragraph <code>Style</code>.
*/
protected boolean isSet[] = new boolean[NR_PROPERTIES];
/** Array of attribute values for this paragraph <code>tyle</code>. */
protected int value[] = new int[NR_PROPERTIES];
/** Array of attribute names for this paragraph <code>Style</code>. */
protected String attrName[] = {
"fo:margin-left",
"fo:margin-right",
"fo:margin-top",
"fo:margin-bottom",
"fo:text-indent",
"fo:line-height",
"fo:text-align"
};
/** Array of attribute structures for this paragraph <code>Style</code>. */
protected Class algor[] = {
horizSize.class,
horizSize.class,
horizSize.class,
horizSize.class,
horizSize.class,
lineHeight.class,
alignment.class
};
/** Align right. */
public static final int ALIGN_RIGHT = 1;
/** Align center. */
public static final int ALIGN_CENTER = 2;
/** Align justified. */
public static final int ALIGN_JUST = 3;
/** Align left. */
public static final int ALIGN_LEFT = 4;
/** Line height percentage. */
public static final int LH_PCT = 0x40000000;
/** Line height minimum value. */
public static final int LH_ATLEAST = 0x20000000;
/** Line height mask. */
public static final int LH_VALUEMASK = 0x00FFFFFF;
/** Ignored tags. */
private static String[] ignored = {
"style:font-name", "fo:font-size", "fo:font-weight", "fo:color",
"fo:language", "fo:country", "style:font-name-asian",
"style:font-size-asian", "style:language-asian",
"style:country-asian", "style:font-name-complex",
"style:font-size-complex", "style:language-complex",
"style:country-complex", "style:text-autospace", "style:punctuation-wrap",
"style:line-break", "fo:keep-with-next", "fo:font-style",
"text:number-lines", "text:line-number"
};
/**
* Constructor for use when going from DOM to client device format.
*
* @param node A <i>style:style</i> <code>Node</code> which, which
* is assumed to have <i>family</i> attribute of
* <i>paragraph</i>.
* @param sc The <code>StyleCatalog</code>, which is used for
* looking up ancestor <code>Style</code> objects.
*/
public ParaStyle(Node node, StyleCatalog sc) {
super(node, sc);
// Look for children. Only ones we care about are "style:properties"
// nodes. If any are found, recursively traverse them, passing
// along the style element to add properties to.
//
if (node.hasChildNodes()) {
NodeList children = node.getChildNodes();
int len = children.getLength();
for (int i = 0; i < len; i++) {
Node child = children.item(i);
String name = child.getNodeName();
if (name.equals("style:properties")) {
NamedNodeMap childAttrNodes = child.getAttributes();
if (childAttrNodes != null) {
int nChildAttrNodes = childAttrNodes.getLength();
for (int j = 0; j < nChildAttrNodes; j++) {
Node attr = childAttrNodes.item(j);
setAttribute(attr.getNodeName(), attr.getNodeValue());
}
}
}
}
}
}
/**
* Constructor for use when going from client device format to DOM.
*
* @param name Name of the <code>Style</code>. Can be null.
* @param familyName Family of the <code>Style</code> - usually
* <i>paragraph</i>, <i>text</i>, etc. Can be null.
* @param parentName Name of the parent <code>Style</code>, or null
* if none.
* @param attribs Array of attributes to set.
* @param values Array of values to set.
* @param sc The <code>StyleCatalog</code>, which is used for
* looking up ancestor <code>Style</code> objects.
*/
public ParaStyle(String name, String familyName, String parentName,
String attribs[], String values[], StyleCatalog sc) {
super(name, familyName, parentName, sc);
if (attribs != null)
for (int i = 0; i < attribs.length; i++)
setAttribute(attribs[i], values[i]);
}
/**
* Alternate constructor for use when going from client device
* format to DOM.
*
* @param name Name of the <code>Style</code>. Can be null.
* @param familyName Family of the <code>Style</code> - usually
* <i>paragraph</i>, <i>text</i>, etc. Can be null.
* @param parentName Name of the parent <code>Style</code>, or
* null if none.
* @param attribs Array of attributes indices to set.
* @param values Array of values to set.
* @param lookup The <code>StyleCatalog</code>, which is used for
* looking up ancestor <code>Style</code> objects.
*/
public ParaStyle(String name, String familyName, String parentName,
int attribs[], String values[], StyleCatalog lookup) {
super(name, familyName, parentName, lookup);
if (attribs != null)
for (int i = 0; i < attribs.length; i++)
setAttribute(attribs[i], values[i]);
}
/**
* This code checks whether an attribute is one that we
* intentionally ignore.
*
* @param attribute The attribute to check.
*
* @return true if attribute can be ignored, false otherwise.
*/
private boolean isIgnored(String attribute) {
for (int i = 0; i < ignored.length; i++) {
if (ignored[i].equals(attribute))
return true;
}
return false;
}
/**
* Set an attribute for this paragraph <code>Style</code>.
*
* @param attr The attribute to set.
* @param value The attribute value to set.
*/
public void setAttribute(String attr, String value) {
for (int i = 0; i < NR_PROPERTIES; i++) {
if (attr.equals(attrName[i])) {
setAttribute(i, value);
return;
}
}
if (!isIgnored(attr))
Debug.log(Debug.INFO, "ParaStyle Unhandled: " + attr + "=" + value);
}
/**
* Check whether an attribute is set in this <code>Style</code>.
*
* @param attrIndex The attribute index to check.
*
* @return true if the attribute at specified index is set,
* false otherwise.
*/
public boolean isAttributeSet(int attrIndex) {
return isSet[attrIndex];
}
/**
* Get the value of an integer attribute.
*
* @param attrIndex Index of the attribute.
*
* @return Value of the attribute, 0 if not set.
*/
public int getAttribute(int attrIndex) {
if (isSet[attrIndex])
return value[attrIndex];
else return 0;
}
/**
* Set an attribute for this paragraph <code>Style</code>.
*
* @param attr The attribute index to set.
* @param value The attribute value to set.
*/
public void setAttribute(int attr, String value) {
isSet[attr] = true;
try {
this.value[attr] = (((conversionAlgorithm)algor[attr].newInstance())).I(value);
} catch (Exception e) {
Debug.log(Debug.ERROR, "Instantiation error", e);
}
}
/**
* Return the <code>Style</code> in use.
*
* @return The fully-resolved copy of the <code>Style</code> in use.
*/
public Style getResolved() {
ParaStyle resolved = null;
try {
resolved = (ParaStyle)this.clone();
} catch (Exception e) {
Debug.log(Debug.ERROR, "Can't clone", e);
}
// Look up the parent style. (If there is no style catalog
// specified, we can't do any lookups).
ParaStyle parentStyle = null;
if (sc != null) {
if (parent != null) {
parentStyle = (ParaStyle)sc.lookup(parent, family, null,
this.getClass());
if (parentStyle == null)
Debug.log(Debug.ERROR, "parent style lookup of "
+ parent + " failed!");
else
parentStyle = (ParaStyle)parentStyle.getResolved();
} else if (!name.equals("DEFAULT_STYLE")) {
parentStyle = (ParaStyle)sc.lookup("DEFAULT_STYLE", null, null,
this.getClass());
}
}
// If we found a parent, for any attributes which we don't have
// set, try to get the values from the parent.
if (parentStyle != null) {
parentStyle = (ParaStyle)parentStyle.getResolved();
for (int i = 0; i < NR_PROPERTIES; i++) {
if (!isSet[i] && parentStyle.isSet[i]) {
resolved.isSet[i] = true;
resolved.value[i] = parentStyle.value[i];
}
}
}
return resolved;
}
/**
* Private function to return the value as an element in
* a Comma Separated Value (CSV) format.
*
* @param value The value to format.
*
* @return The formatted value.
*/
private static String toCSV(String value) {
if (value != null)
return "\"" + value + "\",";
else
return "\"\",";
}
/**
* Private function to return the value as a last element in
* a Comma Separated Value (CSV) format.
*
* @param value The value to format.
*
* @return The formatted value.
*/
private static String toLastCSV(String value) {
if (value != null)
return "\"" + value + "\"";
else
return "\"\"";
}
/**
* Print a Comma Separated Value (CSV) header line for the
* spreadsheet dump.
*/
public static void dumpHdr() {
System.out.println(toCSV("Name") + toCSV("Family") + toCSV("parent")
+ toCSV("left mgn") + toCSV("right mgn")
+ toCSV("top mgn") + toCSV("bottom mgn") + toCSV("txt indent")
+ toCSV("line height") + toLastCSV("txt align"));
}
/**
* Dump this <code>Style</code> as a Comma Separated Value (CSV)
* line.
*/
public void dumpCSV() {
String attributes = "";
for (int index = 0; index <= 6; index++) {
if (isSet[index]) {
attributes += toCSV("" + value[index]);
}
else
attributes += toCSV(null); // unspecified
}
System.out.println(toCSV(name) + toCSV(family) + toCSV(parent)
+ attributes + toLastCSV(null));
}
/**
* Create the <code>Node</code> with the specified elements.
*
* @param parentDoc Parent <code>Document</code> of the
* <code>Node</code> to create.
* @param name Name of the <code>Node</code>.
*
* @return The created <code>Node</code>.
*/
public Node createNode(org.w3c.dom.Document parentDoc, String name) {
Element node = parentDoc.createElement(name);
writeAttributes(node);
return node;
}
/**
* Return true if <code>style</code> is a subset of the
* <code>Style</code>.
*
* @param style <code>Style</code> to check.
*
* @return true if <code>style</code> is a subset, false
* otherwise.
*/
public boolean isSubset(Style style) {
if (!super.isSubset(style))
return false;
if (!this.getClass().isAssignableFrom(style.getClass()))
return false;
ParaStyle ps = (ParaStyle)style;
for (int i = 0; i < NR_PROPERTIES; i++) {
if (ps.isSet[i]) {
// if (!isSet[i]) return false;
if (i < NR_PROPERTIES - 1) {
// Compare the actual values. We allow a margin of error
// here because the conversion loses precision.
int diff;
if (value[i] > ps.value[i])
diff = value[i] - ps.value[i];
else
diff = ps.value[i] - value[i];
if (diff > 32)
return false;
} else {
if (i == TEXT_ALIGN)
if ((value[i] == 0) && (ps.value[i] == 4))
continue;
if (value[i] != ps.value[i])
return false;
}
}
}
return true;
}
/**
* Add <code>Style</code> attributes to the given
* <code>Node</code>. This may involve writing child
* <code>Node</code> objects as well.
*
* @param node The <code>Node</code> to add <code>Style</code>
* attributes.
*/
public void writeAttributes(Element node) {
for (int i = 0; i <= TEXT_INDENT; i++) {
if (isSet[i]) {
double temp = value[i] / 100.0;
String stringVal = (new Double(temp)).toString() + "mm";
node.setAttribute(attrName[i], stringVal);
}
}
if (isSet[LINE_HEIGHT]) {
String stringVal;
if ((value[LINE_HEIGHT] & LH_PCT) != 0)
stringVal = (new Integer(value[LINE_HEIGHT] & LH_VALUEMASK)).toString() + "%";
else {
double temp = (value[LINE_HEIGHT] & LH_VALUEMASK) / 100.0;
stringVal = (new Double(temp)).toString() + "mm";
}
node.setAttribute(attrName[LINE_HEIGHT], stringVal);
}
if (isSet[TEXT_ALIGN]) {
String val;
switch (value[TEXT_ALIGN]) {
case ALIGN_RIGHT: val = "end"; break;
case ALIGN_CENTER: val = "center"; break;
case ALIGN_JUST: val = "justify"; break;
case ALIGN_LEFT: val = "left"; break;
default: val = "unknown"; break;
}
node.setAttribute(attrName[TEXT_ALIGN], val);
}
}
}
| xmerge/source/xmerge/java/org/openoffice/xmerge/converter/xml/ParaStyle.java | /*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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 org.openoffice.xmerge.converter.xml;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Element;
import org.openoffice.xmerge.util.Debug;
abstract class conversionAlgorithm {
int I(String val) {
return 0;
}
}
/*
* This algorithm expects only values in millimeters, e.g. "20.3mm".
*/
class horizSize extends conversionAlgorithm {
int I(String value) {
if (value.endsWith("mm")) {
float size = (float)0.0;
String num = value.substring(0, value.length() - 2);
try {
size = Float.parseFloat(num);
} catch (Exception e) {
Debug.log(Debug.ERROR, "Error parsing " + value, e);
}
size *= 100;
return (int)size;
} else {
Debug.log(Debug.ERROR, "Unexpected value (" + value
+ ") in horizSize.I()");
return 0;
}
}
}
/*
* This algorithm does line height - can be either millimeters or
* a percentage.
*/
class lineHeight extends conversionAlgorithm {
int I(String value) {
if (value.endsWith("mm")) {
float size = (float)0.0;
String num = value.substring(0, value.length() - 2);
try {
size = Float.parseFloat(num);
} catch (Exception e) {
Debug.log(Debug.ERROR, "Error parsing " + value, e);
}
size *= 100;
return (int)size;
} else if (value.endsWith("%")) {
float size = (float)0.0;
String num = value.substring(0, value.length() - 1);
try {
size = Float.parseFloat(num);
} catch (Exception e) {
Debug.log(Debug.ERROR, "Error parsing " + value, e);
}
int retval = (int) size;
retval |= ParaStyle.LH_PCT;
return retval;
}
return 0;
}
}
/**
* This class converts alignment values.
*/
class alignment extends conversionAlgorithm {
int I(String value) {
if (value.equals("end"))
return ParaStyle.ALIGN_RIGHT;
if (value.equals("right"))
return ParaStyle.ALIGN_RIGHT;
if (value.equals("center"))
return ParaStyle.ALIGN_CENTER;
if (value.equals("justify"))
return ParaStyle.ALIGN_JUST;
if (value.equals("justified"))
return ParaStyle.ALIGN_JUST;
if (value.equals("start"))
return ParaStyle.ALIGN_LEFT;
if (value.equals("left"))
return ParaStyle.ALIGN_LEFT;
Debug.log(Debug.ERROR, "Unknown string ("
+ value + ") in alignment.I()");
return ParaStyle.ALIGN_LEFT;
}
}
/**
* <p>This class represents a paragraph <code>Style</code>.</p>
*
* <p><table border="1" cellpadding="1"><tr><td>
* Attribute </td><td>Value
* </td></tr><tr><td>
* MARGIN_LEFT </td><td>mm * 100
* </td></tr><tr><td>
* MARGIN_RIGHT </td><td>mm * 100
* </td></tr><tr><td>
* MARGIN_TOP </td><td>mm * 100 (space on top of paragraph)
* </td></tr><tr><td>
* MARGIN_BOTTOM </td><td>mm * 100
* </td></tr><tr><td>
* TEXT_INDENT </td><td>mm * 100 (first line indent)
* </td></tr><tr><td>
* LINE_HEIGHT </td><td>mm * 100, unless or'ed with LH_PCT, in which
* case it is a percentage (e.g. 200% for double spacing)
* Can also be or'ed with LH_ATLEAST. Value is stored
* in bits indicated by LH_VALUEMASK.
* </td></tr><tr><td>
* TEXT_ALIGN </td><td>ALIGN_RIGHT, ALIGN_CENTER, ALIGN_JUST, ALIGN_LEFT
* </td></tr></table></p>
*
* @author David Proulx
*/
public class ParaStyle extends Style implements Cloneable {
/** The left margin property. */
public static final int MARGIN_LEFT = 0;
/** The right margin property. */
public static final int MARGIN_RIGHT = 1;
/** The top margin property. */
public static final int MARGIN_TOP = 2;
/** The bottom margin property. */
public static final int MARGIN_BOTTOM = 3;
/** Indent left property. */
public static final int TEXT_INDENT = 4;
/** Indent right property. */
public static final int LINE_HEIGHT = 5;
/** Align text property. */
public static final int TEXT_ALIGN = 6;
// This must always be one more than highest property
/** Total number of properties. */
protected static final int NR_PROPERTIES = 7;
/**
* Array of flags indicating which attributes are set for this
* paragraph <code>Style</code>.
*/
protected boolean isSet[] = new boolean[NR_PROPERTIES];
/** Array of attribute values for this paragraph <code>tyle</code>. */
protected int value[] = new int[NR_PROPERTIES];
/** Array of attribute names for this paragraph <code>Style</code>. */
protected String attrName[] = {
"fo:margin-left",
"fo:margin-right",
"fo:margin-top",
"fo:margin-bottom",
"fo:text-indent",
"fo:line-height",
"fo:text-align"
};
/** Array of attribute structures for this paragraph <code>Style</code>. */
protected Class algor[] = {
horizSize.class,
horizSize.class,
horizSize.class,
horizSize.class,
horizSize.class,
lineHeight.class,
alignment.class
};
/** Align right. */
public static final int ALIGN_RIGHT = 1;
/** Align center. */
public static final int ALIGN_CENTER = 2;
/** Align justified. */
public static final int ALIGN_JUST = 3;
/** Align left. */
public static final int ALIGN_LEFT = 4;
/** Line height percentage. */
public static final int LH_PCT = 0x40000000;
/** Line height minimum value. */
public static final int LH_ATLEAST = 0x20000000;
/** Line height mask. */
public static final int LH_VALUEMASK = 0x00FFFFFF;
/** Ignored tags. */
private static String[] ignored = {
"style:font-name", "fo:font-size", "fo:font-weight", "fo:color",
"fo:language", "fo:country", "style:font-name-asian",
"style:font-size-asian", "style:language-asian",
"style:country-asian", "style:font-name-complex",
"style:font-size-complex", "style:language-complex",
"style:country-complex", "style:text-autospace", "style:punctuation-wrap",
"style:line-break", "fo:keep-with-next", "fo:font-style",
"text:number-lines", "text:line-number"
};
/**
* Constructor for use when going from DOM to client device format.
*
* @param node A <i>style:style</i> <code>Node</code> which, which
* is assumed to have <i>family</i> attribute of
* <i>paragraph</i>.
* @param sc The <code>StyleCatalog</code>, which is used for
* looking up ancestor <code>Style</code> objects.
*/
public ParaStyle(Node node, StyleCatalog sc) {
super(node, sc);
// Look for children. Only ones we care about are "style:properties"
// nodes. If any are found, recursively traverse them, passing
// along the style element to add properties to.
//
if (node.hasChildNodes()) {
NodeList children = node.getChildNodes();
int len = children.getLength();
for (int i = 0; i < len; i++) {
Node child = children.item(i);
String name = child.getNodeName();
if (name.equals("style:properties")) {
NamedNodeMap childAttrNodes = child.getAttributes();
if (childAttrNodes != null) {
int nChildAttrNodes = childAttrNodes.getLength();
for (int j = 0; j < nChildAttrNodes; j++) {
Node attr = childAttrNodes.item(j);
setAttribute(attr.getNodeName(), attr.getNodeValue());
}
}
}
}
}
}
/**
* Constructor for use when going from client device format to DOM.
*
* @param name Name of the <code>Style</code>. Can be null.
* @param family Family of the <code>Style</code> - usually
* <i>paragraph</i>, <i>text</i>, etc. Can be null.
* @param parent Name of the parent <code>Style</code>, or null
* if none.
* @param attribs Array of attributes to set.
* @param values Array of values to set.
* @param sc The <code>StyleCatalog</code>, which is used for
* looking up ancestor <code>Style</code> objects.
*/
public ParaStyle(String name, String familyName, String parentName,
String attribs[], String values[], StyleCatalog sc) {
super(name, familyName, parentName, sc);
if (attribs != null)
for (int i = 0; i < attribs.length; i++)
setAttribute(attribs[i], values[i]);
}
/**
* Alternate constructor for use when going from client device
* format to DOM.
*
* @param name Name of the <code>Style</code>. Can be null.
* @param family Family of the <code>Style</code> - usually
* <i>paragraph</i>, <i>text</i>, etc. Can be null.
* @param parent Name of the parent <code>Style</code>, or
* null if none.
* @param attribs Array of attributes indices to set.
* @param values Array of values to set.
* @param sc The <code>StyleCatalog</code>, which is used for
* looking up ancestor <code>Style</code> objects.
*/
public ParaStyle(String name, String familyName, String parentName,
int attribs[], String values[], StyleCatalog lookup) {
super(name, familyName, parentName, lookup);
if (attribs != null)
for (int i = 0; i < attribs.length; i++)
setAttribute(attribs[i], values[i]);
}
/**
* This code checks whether an attribute is one that we
* intentionally ignore.
*
* @param attribute The attribute to check.
*
* @return true if attribute can be ignored, false otherwise.
*/
private boolean isIgnored(String attribute) {
for (int i = 0; i < ignored.length; i++) {
if (ignored[i].equals(attribute))
return true;
}
return false;
}
/**
* Set an attribute for this paragraph <code>Style</code>.
*
* @param attr The attribute to set.
* @param value The attribute value to set.
*/
public void setAttribute(String attr, String value) {
for (int i = 0; i < NR_PROPERTIES; i++) {
if (attr.equals(attrName[i])) {
setAttribute(i, value);
return;
}
}
if (!isIgnored(attr))
Debug.log(Debug.INFO, "ParaStyle Unhandled: " + attr + "=" + value);
}
/**
* Check whether an attribute is set in this <code>Style</code>.
*
* @param attrIndex The attribute index to check.
*
* @return true if the attribute at specified index is set,
* false otherwise.
*/
public boolean isAttributeSet(int attrIndex) {
return isSet[attrIndex];
}
/**
* Get the value of an integer attribute.
*
* @param attrIndex Index of the attribute.
*
* @return Value of the attribute, 0 if not set.
*/
public int getAttribute(int attrIndex) {
if (isSet[attrIndex])
return value[attrIndex];
else return 0;
}
/**
* Set an attribute for this paragraph <code>Style</code>.
*
* @param attr The attribute index to set.
* @apram value The attribute value to set.
*/
public void setAttribute(int attr, String value) {
isSet[attr] = true;
try {
this.value[attr] = (((conversionAlgorithm)algor[attr].newInstance())).I(value);
} catch (Exception e) {
Debug.log(Debug.ERROR, "Instantiation error", e);
}
}
/**
* Return the <code>Style</code> in use.
*
* @return The fully-resolved copy of the <code>Style</code> in use.
*/
public Style getResolved() {
ParaStyle resolved = null;
try {
resolved = (ParaStyle)this.clone();
} catch (Exception e) {
Debug.log(Debug.ERROR, "Can't clone", e);
}
// Look up the parent style. (If there is no style catalog
// specified, we can't do any lookups).
ParaStyle parentStyle = null;
if (sc != null) {
if (parent != null) {
parentStyle = (ParaStyle)sc.lookup(parent, family, null,
this.getClass());
if (parentStyle == null)
Debug.log(Debug.ERROR, "parent style lookup of "
+ parent + " failed!");
else
parentStyle = (ParaStyle)parentStyle.getResolved();
} else if (!name.equals("DEFAULT_STYLE")) {
parentStyle = (ParaStyle)sc.lookup("DEFAULT_STYLE", null, null,
this.getClass());
}
}
// If we found a parent, for any attributes which we don't have
// set, try to get the values from the parent.
if (parentStyle != null) {
parentStyle = (ParaStyle)parentStyle.getResolved();
for (int i = 0; i < NR_PROPERTIES; i++) {
if (!isSet[i] && parentStyle.isSet[i]) {
resolved.isSet[i] = true;
resolved.value[i] = parentStyle.value[i];
}
}
}
return resolved;
}
/**
* Private function to return the value as an element in
* a Comma Separated Value (CSV) format.
*
* @param value The value to format.
*
* @return The formatted value.
*/
private static String toCSV(String value) {
if (value != null)
return "\"" + value + "\",";
else
return "\"\",";
}
/**
* Private function to return the value as a last element in
* a Comma Separated Value (CSV) format.
*
* @param value The value to format.
*
* @return The formatted value.
*/
private static String toLastCSV(String value) {
if (value != null)
return "\"" + value + "\"";
else
return "\"\"";
}
/**
* Print a Comma Separated Value (CSV) header line for the
* spreadsheet dump.
*/
public static void dumpHdr() {
System.out.println(toCSV("Name") + toCSV("Family") + toCSV("parent")
+ toCSV("left mgn") + toCSV("right mgn")
+ toCSV("top mgn") + toCSV("bottom mgn") + toCSV("txt indent")
+ toCSV("line height") + toLastCSV("txt align"));
}
/**
* Dump this <code>Style</code> as a Comma Separated Value (CSV)
* line.
*/
public void dumpCSV() {
String attributes = "";
for (int index = 0; index <= 6; index++) {
if (isSet[index]) {
attributes += toCSV("" + value[index]);
}
else
attributes += toCSV(null); // unspecified
}
System.out.println(toCSV(name) + toCSV(family) + toCSV(parent)
+ attributes + toLastCSV(null));
}
/**
* Create the <code>Node</code> with the specified elements.
*
* @parentDoc Parent <code>Document</code> of the
* <code>Node</code> to create.
* @param name Name of the <code>Node</code>.
*
* @return The created <code>Node</code>.
*/
public Node createNode(org.w3c.dom.Document parentDoc, String name) {
Element node = parentDoc.createElement(name);
writeAttributes(node);
return node;
}
/**
* Return true if <code>style</code> is a subset of the
* <code>Style</code>.
*
* @param style <code>Style</code> to check.
*
* @return true if <code>style</code> is a subset, false
* otherwise.
*/
public boolean isSubset(Style style) {
if (!super.isSubset(style))
return false;
if (!this.getClass().isAssignableFrom(style.getClass()))
return false;
ParaStyle ps = (ParaStyle)style;
for (int i = 0; i < NR_PROPERTIES; i++) {
if (ps.isSet[i]) {
// if (!isSet[i]) return false;
if (i < NR_PROPERTIES - 1) {
// Compare the actual values. We allow a margin of error
// here because the conversion loses precision.
int diff;
if (value[i] > ps.value[i])
diff = value[i] - ps.value[i];
else
diff = ps.value[i] - value[i];
if (diff > 32)
return false;
} else {
if (i == TEXT_ALIGN)
if ((value[i] == 0) && (ps.value[i] == 4))
continue;
if (value[i] != ps.value[i])
return false;
}
}
}
return true;
}
/**
* Add <code>Style</code> attributes to the given
* <code>Node</code>. This may involve writing child
* <code>Node</code> objects as well.
*
* @param node The <code>Node</code> to add <code>Style</code>
* attributes.
*/
public void writeAttributes(Element node) {
for (int i = 0; i <= TEXT_INDENT; i++) {
if (isSet[i]) {
double temp = value[i] / 100.0;
String stringVal = (new Double(temp)).toString() + "mm";
node.setAttribute(attrName[i], stringVal);
}
}
if (isSet[LINE_HEIGHT]) {
String stringVal;
if ((value[LINE_HEIGHT] & LH_PCT) != 0)
stringVal = (new Integer(value[LINE_HEIGHT] & LH_VALUEMASK)).toString() + "%";
else {
double temp = (value[LINE_HEIGHT] & LH_VALUEMASK) / 100.0;
stringVal = (new Double(temp)).toString() + "mm";
}
node.setAttribute(attrName[LINE_HEIGHT], stringVal);
}
if (isSet[TEXT_ALIGN]) {
String val;
switch (value[TEXT_ALIGN]) {
case ALIGN_RIGHT: val = "end"; break;
case ALIGN_CENTER: val = "center"; break;
case ALIGN_JUST: val = "justify"; break;
case ALIGN_LEFT: val = "left"; break;
default: val = "unknown"; break;
}
node.setAttribute(attrName[TEXT_ALIGN], val);
}
}
}
| Fix javadoc comments in ParaStyle.java
| xmerge/source/xmerge/java/org/openoffice/xmerge/converter/xml/ParaStyle.java | Fix javadoc comments in ParaStyle.java | <ide><path>merge/source/xmerge/java/org/openoffice/xmerge/converter/xml/ParaStyle.java
<ide> /**
<ide> * Constructor for use when going from client device format to DOM.
<ide> *
<del> * @param name Name of the <code>Style</code>. Can be null.
<del> * @param family Family of the <code>Style</code> - usually
<del> * <i>paragraph</i>, <i>text</i>, etc. Can be null.
<del> * @param parent Name of the parent <code>Style</code>, or null
<del> * if none.
<del> * @param attribs Array of attributes to set.
<del> * @param values Array of values to set.
<del> * @param sc The <code>StyleCatalog</code>, which is used for
<del> * looking up ancestor <code>Style</code> objects.
<add> * @param name Name of the <code>Style</code>. Can be null.
<add> * @param familyName Family of the <code>Style</code> - usually
<add> * <i>paragraph</i>, <i>text</i>, etc. Can be null.
<add> * @param parentName Name of the parent <code>Style</code>, or null
<add> * if none.
<add> * @param attribs Array of attributes to set.
<add> * @param values Array of values to set.
<add> * @param sc The <code>StyleCatalog</code>, which is used for
<add> * looking up ancestor <code>Style</code> objects.
<ide> */
<ide> public ParaStyle(String name, String familyName, String parentName,
<ide> String attribs[], String values[], StyleCatalog sc) {
<ide> * Alternate constructor for use when going from client device
<ide> * format to DOM.
<ide> *
<del> * @param name Name of the <code>Style</code>. Can be null.
<del> * @param family Family of the <code>Style</code> - usually
<del> * <i>paragraph</i>, <i>text</i>, etc. Can be null.
<del> * @param parent Name of the parent <code>Style</code>, or
<del> * null if none.
<del> * @param attribs Array of attributes indices to set.
<del> * @param values Array of values to set.
<del> * @param sc The <code>StyleCatalog</code>, which is used for
<del> * looking up ancestor <code>Style</code> objects.
<add> * @param name Name of the <code>Style</code>. Can be null.
<add> * @param familyName Family of the <code>Style</code> - usually
<add> * <i>paragraph</i>, <i>text</i>, etc. Can be null.
<add> * @param parentName Name of the parent <code>Style</code>, or
<add> * null if none.
<add> * @param attribs Array of attributes indices to set.
<add> * @param values Array of values to set.
<add> * @param lookup The <code>StyleCatalog</code>, which is used for
<add> * looking up ancestor <code>Style</code> objects.
<ide> */
<ide> public ParaStyle(String name, String familyName, String parentName,
<ide> int attribs[], String values[], StyleCatalog lookup) {
<ide> * Set an attribute for this paragraph <code>Style</code>.
<ide> *
<ide> * @param attr The attribute index to set.
<del> * @apram value The attribute value to set.
<add> * @param value The attribute value to set.
<ide> */
<ide> public void setAttribute(int attr, String value) {
<ide> isSet[attr] = true;
<ide> /**
<ide> * Create the <code>Node</code> with the specified elements.
<ide> *
<del> * @parentDoc Parent <code>Document</code> of the
<del> * <code>Node</code> to create.
<del> * @param name Name of the <code>Node</code>.
<add> * @param parentDoc Parent <code>Document</code> of the
<add> * <code>Node</code> to create.
<add> * @param name Name of the <code>Node</code>.
<ide> *
<ide> * @return The created <code>Node</code>.
<ide> */ |
|
Java | mit | dbe07c357988c4a69979c1357a7d98b3ae985903 | 0 | jugglinmike/es6draft,jugglinmike/es6draft,anba/es6draft,anba/es6draft,anba/es6draft,jugglinmike/es6draft,jugglinmike/es6draft | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.repl;
import static com.github.anba.es6draft.repl.SourceBuilder.ToSource;
import static com.github.anba.es6draft.runtime.AbstractOperations.CreateArrayFromList;
import static com.github.anba.es6draft.runtime.types.Undefined.UNDEFINED;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import com.github.anba.es6draft.Script;
import com.github.anba.es6draft.ScriptLoader;
import com.github.anba.es6draft.compiler.CompilationException;
import com.github.anba.es6draft.compiler.Compiler;
import com.github.anba.es6draft.parser.Parser;
import com.github.anba.es6draft.parser.ParserEOFException;
import com.github.anba.es6draft.parser.ParserException;
import com.github.anba.es6draft.repl.StopExecutionException.Reason;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.CompatibilityOption;
import com.github.anba.es6draft.runtime.internal.ScriptCache;
import com.github.anba.es6draft.runtime.internal.ScriptException;
import com.github.anba.es6draft.runtime.types.PropertyDescriptor;
import com.github.anba.es6draft.runtime.types.ScriptObject;
/**
* Simple REPL
*/
public class Repl {
private static final int STACKTRACE_DEPTH = 20;
public static void main(String[] args) {
try {
EnumSet<Option> options = Option.fromArgs(args);
StartScript startScript = StartScript.fromArgs(args);
new Repl(options, startScript, System.console()).loop();
} catch (Throwable e) {
printStackTrace(e);
}
}
private static void printStackTrace(Throwable e) {
StackTraceElement[] stackTrace = e.getStackTrace();
if (stackTrace.length > STACKTRACE_DEPTH) {
stackTrace = Arrays.copyOf(stackTrace, STACKTRACE_DEPTH + 1);
stackTrace[STACKTRACE_DEPTH] = new StackTraceElement("..", "", null, 0);
e.setStackTrace(stackTrace);
}
e.printStackTrace();
}
private enum Option {
CompileOnly, Debug, StackTrace, Strict, SimpleShell, MozillaShell, V8Shell;
static EnumSet<Option> fromArgs(String[] args) {
EnumSet<Option> options = EnumSet.noneOf(Option.class);
for (String arg : args) {
switch (arg) {
case "--compile-only":
options.add(CompileOnly);
break;
case "--debug":
options.add(CompileOnly);
options.add(Debug);
break;
case "--stacktrace":
options.add(StackTrace);
break;
case "--strict":
options.add(Strict);
break;
case "--shell=simple":
options.add(SimpleShell);
break;
case "--shell=mozilla":
options.add(MozillaShell);
break;
case "--shell=v8":
options.add(V8Shell);
break;
case "--help":
System.out.print(getHelp());
System.exit(0);
break;
default:
if (arg.startsWith("-") && arg.length() > 1) {
System.err.printf("invalid option '%s'\n\n", arg);
System.out.print(getHelp());
System.exit(0);
}
break;
}
}
return options;
}
}
private static String getHelp() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("es6draft (%s)\n\n", getBuildDate()));
sb.append("Options: \n");
sb.append(" --compile-only Disable interpreter\n");
sb.append(" --debug Print generated Java bytecode\n");
sb.append(" --stacktrace Print stack-trace on error\n");
sb.append(" --strict Strict semantics without web compatibility\n");
sb.append(" --shell=[mode] Set default shell emulation [simple, mozilla, v8] (default = simple)\n");
sb.append(" --help Print this help\n");
return sb.toString();
}
private static String getBuildDate() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
Repl.class.getResourceAsStream("/build-date"), StandardCharsets.UTF_8))) {
return reader.readLine();
} catch (IOException e) {
return "<unknown build>";
}
}
private static class StartScript {
private Path script = Paths.get("-");
private List<String> arguments = new ArrayList<>();
static StartScript fromArgs(String[] args) {
StartScript startScript = new StartScript();
boolean inOptions = true;
for (String arg : args) {
if (inOptions && arg.startsWith("-") && arg.length() > 1) {
// skip options
continue;
}
if (inOptions) {
inOptions = false;
startScript.script = Paths.get(arg);
} else if (!arg.isEmpty()) {
startScript.arguments.add(arg);
}
}
return startScript;
}
}
private final EnumSet<Option> options;
private final StartScript startScript;
private final Console console;
private Repl(EnumSet<Option> options, StartScript startScript, Console console) {
this.options = options;
this.startScript = startScript;
this.console = console;
}
private void handleException(Throwable e) {
String message = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
console.printf("%s%n", message);
if (options.contains(Option.StackTrace)) {
printStackTrace(e);
}
}
private void handleException(ScriptException e) {
console.printf("uncaught exception: %s%n", e.getMessage());
if (options.contains(Option.StackTrace)) {
printStackTrace(e);
}
}
/**
* REPL: Read
*/
private com.github.anba.es6draft.ast.Script read(Realm realm, int line) {
StringBuilder source = new StringBuilder();
for (;;) {
String s = console.readLine();
if (s == null) {
continue;
}
source.append(s).append('\n');
try {
EnumSet<Parser.Option> options = Parser.Option.from(realm.getOptions());
Parser parser = new Parser("typein", line, options);
return parser.parse(source);
} catch (ParserEOFException e) {
continue;
}
}
}
/**
* REPL: Eval
*/
private Object eval(Realm realm, com.github.anba.es6draft.ast.Script parsedScript) {
Script script = script(parsedScript);
return ScriptLoader.ScriptEvaluation(script, realm, false);
}
/**
* REPL: Print
*/
private void print(Realm realm, Object result) {
if (result != UNDEFINED) {
console.printf("%s%n", ToSource(realm.defaultContext(), result));
}
}
/**
* REPL: Loop
*/
private void loop() {
ShellGlobalObject global = newGlobal();
runStartScript(global);
Realm realm = global.getRealm();
for (int line = 1;; line += 1) {
try {
console.printf("js> ");
com.github.anba.es6draft.ast.Script parsedScript = read(realm, line);
if (parsedScript.getStatements().isEmpty()) {
continue;
}
Object result = eval(realm, parsedScript);
print(realm, result);
} catch (StopExecutionException e) {
if (e.getReason() == Reason.Quit) {
System.exit(0);
}
} catch (ScriptException e) {
handleException(e);
} catch (ParserException | CompilationException | StackOverflowError e) {
handleException(e);
}
}
}
private AtomicInteger scriptCounter = new AtomicInteger(0);
private Script script(com.github.anba.es6draft.ast.Script parsedScript)
throws CompilationException {
String className = "typein_" + scriptCounter.incrementAndGet();
if (options.contains(Option.CompileOnly)) {
EnumSet<Compiler.Option> opts = EnumSet.noneOf(Compiler.Option.class);
if (options.contains(Option.Debug)) {
opts.add(Compiler.Option.Debug);
}
return ScriptLoader.compile(className, parsedScript, opts);
} else {
return ScriptLoader.load(className, parsedScript);
}
}
private ShellGlobalObject newGlobal() {
ReplConsole console = new ReplConsole(this.console);
Path baseDir = Paths.get("").toAbsolutePath();
Path script = Paths.get("./.");
Set<CompatibilityOption> compatOpts;
if (options.contains(Option.Strict)) {
compatOpts = CompatibilityOption.StrictCompatibility();
} else {
compatOpts = CompatibilityOption.WebCompatibility();
}
ScriptCache scriptCache = new ScriptCache(Parser.Option.from(compatOpts));
List<String> initScripts;
ShellGlobalObject global;
if (options.contains(Option.MozillaShell)) {
Path libDir = Paths.get("");
initScripts = asList("mozlegacy.js");
global = MozShellGlobalObject.newGlobal(console, baseDir, script, libDir, scriptCache,
compatOpts);
} else if (options.contains(Option.V8Shell)) {
initScripts = asList("v8legacy.js");
global = V8ShellGlobalObject.newGlobal(console, baseDir, script, scriptCache,
compatOpts);
} else {
initScripts = emptyList();
global = SimpleShellGlobalObject.newGlobal(console, baseDir, script, scriptCache,
compatOpts);
}
for (String name : initScripts) {
try {
global.eval(ShellGlobalObject.compileScript(scriptCache, name));
} catch (ParserException | CompilationException | IOException e) {
System.err.println(e);
}
}
return global;
}
private void runStartScript(ShellGlobalObject global) {
ExecutionContext cx = global.getRealm().defaultContext();
ScriptObject arguments = CreateArrayFromList(cx, startScript.arguments);
global.defineOwnProperty(cx, "arguments", new PropertyDescriptor(arguments, true, false,
true));
Path script = startScript.script;
if (!script.toString().equals("-")) {
try {
global.eval(script, script);
} catch (ParserException | CompilationException | IOException e) {
System.err.println(e);
}
}
}
private static class ReplConsole implements ShellConsole {
private Console console;
ReplConsole(Console console) {
this.console = console;
}
@Override
public String readLine() {
return console.readLine();
}
@Override
public void putstr(String s) {
console.writer().print(s);
}
@Override
public void print(String s) {
console.writer().println(s);
}
@Override
public void printErr(String s) {
System.err.println(s);
}
}
}
| src/main/java/com/github/anba/es6draft/repl/Repl.java | /**
* Copyright (c) 2012-2013 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.repl;
import static com.github.anba.es6draft.repl.SourceBuilder.ToSource;
import static com.github.anba.es6draft.runtime.AbstractOperations.CreateArrayFromList;
import static com.github.anba.es6draft.runtime.types.Undefined.UNDEFINED;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import com.github.anba.es6draft.Script;
import com.github.anba.es6draft.ScriptLoader;
import com.github.anba.es6draft.compiler.CompilationException;
import com.github.anba.es6draft.compiler.Compiler;
import com.github.anba.es6draft.parser.Parser;
import com.github.anba.es6draft.parser.ParserEOFException;
import com.github.anba.es6draft.parser.ParserException;
import com.github.anba.es6draft.repl.StopExecutionException.Reason;
import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.CompatibilityOption;
import com.github.anba.es6draft.runtime.internal.ScriptCache;
import com.github.anba.es6draft.runtime.internal.ScriptException;
import com.github.anba.es6draft.runtime.types.PropertyDescriptor;
import com.github.anba.es6draft.runtime.types.ScriptObject;
/**
* Simple REPL
*/
public class Repl {
private static final int STACKTRACE_DEPTH = 20;
public static void main(String[] args) {
try {
EnumSet<Option> options = Option.fromArgs(args);
StartScript startScript = StartScript.fromArgs(args);
new Repl(options, startScript, System.console()).loop();
} catch (Throwable e) {
printStackTrace(e);
}
}
private static void printStackTrace(Throwable e) {
StackTraceElement[] stackTrace = e.getStackTrace();
if (stackTrace.length > STACKTRACE_DEPTH) {
stackTrace = Arrays.copyOf(stackTrace, STACKTRACE_DEPTH + 1);
stackTrace[STACKTRACE_DEPTH] = new StackTraceElement("..", "", null, 0);
e.setStackTrace(stackTrace);
}
e.printStackTrace();
}
private enum Option {
CompileOnly, Debug, StackTrace, Strict, SimpleShell, MozillaShell, V8Shell;
static EnumSet<Option> fromArgs(String[] args) {
EnumSet<Option> options = EnumSet.noneOf(Option.class);
for (String arg : args) {
switch (arg) {
case "--compile-only":
options.add(CompileOnly);
break;
case "--debug":
options.add(CompileOnly);
options.add(Debug);
break;
case "--stacktrace":
options.add(StackTrace);
break;
case "--strict":
options.add(Strict);
break;
case "--shell=simple":
options.add(SimpleShell);
break;
case "--shell=mozilla":
options.add(MozillaShell);
break;
case "--shell=v8":
options.add(V8Shell);
break;
case "--help":
System.out.print(getHelp());
System.exit(0);
break;
default:
if (arg.startsWith("-") && arg.length() > 1) {
System.err.printf("invalid option '%s'\n\n", arg);
System.out.print(getHelp());
System.exit(0);
}
break;
}
}
return options;
}
}
private static String getHelp() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("es6draft (%s)\n\n", getBuildDate()));
sb.append("Options: \n");
sb.append(" --compile-only Disable interpreter\n");
sb.append(" --debug Print generated Java bytecode\n");
sb.append(" --stacktrace Print stack-trace on error\n");
sb.append(" --strict Strict semantics without web compatibility\n");
sb.append(" --shell=[mode] Set default shell emulation [simple, mozilla, v8] (default = simple)\n");
sb.append(" --help Print this help\n");
return sb.toString();
}
private static String getBuildDate() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
Repl.class.getResourceAsStream("/build-date"), StandardCharsets.UTF_8))) {
return reader.readLine();
} catch (IOException e) {
return "<unknown build>";
}
}
private static class StartScript {
private Path script = Paths.get("-");
private List<String> arguments = new ArrayList<>();
static StartScript fromArgs(String[] args) {
StartScript startScript = new StartScript();
boolean inOptions = true;
for (String arg : args) {
if (inOptions && arg.startsWith("-") && arg.length() > 1) {
// skip options
continue;
}
if (inOptions) {
inOptions = false;
startScript.script = Paths.get(arg);
} else if (!arg.isEmpty()) {
startScript.arguments.add(arg);
}
}
return startScript;
}
}
private final EnumSet<Option> options;
private final StartScript startScript;
private final Console console;
private Repl(EnumSet<Option> options, StartScript startScript, Console console) {
this.options = options;
this.startScript = startScript;
this.console = console;
}
private void handleException(Throwable e) {
String message = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
console.printf("%s\n", message);
if (options.contains(Option.StackTrace)) {
printStackTrace(e);
}
}
private void handleException(ScriptException e) {
console.printf("uncaught exception: %s\n", e.getMessage());
if (options.contains(Option.StackTrace)) {
printStackTrace(e);
}
}
/**
* REPL: Read
*/
private com.github.anba.es6draft.ast.Script read(Realm realm, int line) {
StringBuilder source = new StringBuilder();
try {
for (;;) {
String s = console.readLine();
if (s == null) {
continue;
}
source.append(s).append('\n');
try {
EnumSet<Parser.Option> options = Parser.Option.from(realm.getOptions());
Parser parser = new Parser("typein", line, options);
return parser.parse(source);
} catch (ParserEOFException e) {
continue;
}
}
} catch (ParserException | StackOverflowError e) {
handleException(e);
return null;
}
}
/**
* REPL: Eval
*/
private Object eval(Realm realm, com.github.anba.es6draft.ast.Script parsedScript) {
if (parsedScript.getStatements().isEmpty()) {
console.writer().println();
return null;
}
try {
Script script = script(parsedScript);
return ScriptLoader.ScriptEvaluation(script, realm, false);
} catch (ScriptException e) {
handleException(e);
return null;
} catch (ParserException | CompilationException | StackOverflowError e) {
handleException(e);
return null;
}
}
/**
* REPL: Print
*/
private void print(Realm realm, Object result) {
try {
if (result != UNDEFINED) {
console.writer().println(ToSource(realm.defaultContext(), result));
}
} catch (ScriptException e) {
handleException(e);
} catch (StackOverflowError e) {
handleException(e);
}
}
/**
* REPL: Loop
*/
private void loop() {
ShellGlobalObject global = newGlobal();
runStartScript(global);
Realm realm = global.getRealm();
for (int line = 1;; line += 1) {
try {
console.printf("js> ");
com.github.anba.es6draft.ast.Script parsedScript = read(realm, line);
if (parsedScript == null) {
continue;
}
Object result = eval(realm, parsedScript);
if (result == null) {
continue;
}
print(realm, result);
} catch (StopExecutionException e) {
if (e.getReason() == Reason.Quit) {
System.exit(0);
}
}
}
}
private AtomicInteger scriptCounter = new AtomicInteger(0);
private Script script(com.github.anba.es6draft.ast.Script parsedScript)
throws CompilationException {
String className = "typein_" + scriptCounter.incrementAndGet();
if (options.contains(Option.CompileOnly)) {
EnumSet<Compiler.Option> opts = EnumSet.noneOf(Compiler.Option.class);
if (options.contains(Option.Debug)) {
opts.add(Compiler.Option.Debug);
}
return ScriptLoader.compile(className, parsedScript, opts);
} else {
return ScriptLoader.load(className, parsedScript);
}
}
private ShellGlobalObject newGlobal() {
ReplConsole console = new ReplConsole(this.console);
Path baseDir = Paths.get("").toAbsolutePath();
Path script = Paths.get("./.");
Set<CompatibilityOption> compatOpts;
if (options.contains(Option.Strict)) {
compatOpts = CompatibilityOption.StrictCompatibility();
} else {
compatOpts = CompatibilityOption.WebCompatibility();
}
ScriptCache scriptCache = new ScriptCache(Parser.Option.from(compatOpts));
List<String> initScripts;
ShellGlobalObject global;
if (options.contains(Option.MozillaShell)) {
Path libDir = Paths.get("");
initScripts = asList("mozlegacy.js");
global = MozShellGlobalObject.newGlobal(console, baseDir, script, libDir, scriptCache,
compatOpts);
} else if (options.contains(Option.V8Shell)) {
initScripts = asList("v8legacy.js");
global = V8ShellGlobalObject.newGlobal(console, baseDir, script, scriptCache,
compatOpts);
} else {
initScripts = emptyList();
global = SimpleShellGlobalObject.newGlobal(console, baseDir, script, scriptCache,
compatOpts);
}
for (String name : initScripts) {
try {
global.eval(ShellGlobalObject.compileScript(scriptCache, name));
} catch (ParserException | CompilationException | IOException e) {
System.err.println(e);
}
}
return global;
}
private void runStartScript(ShellGlobalObject global) {
ExecutionContext cx = global.getRealm().defaultContext();
ScriptObject arguments = CreateArrayFromList(cx, startScript.arguments);
global.defineOwnProperty(cx, "arguments", new PropertyDescriptor(arguments, true, false,
true));
Path script = startScript.script;
if (!script.toString().equals("-")) {
try {
global.eval(script, script);
} catch (ParserException | CompilationException | IOException e) {
System.err.println(e);
}
}
}
private static class ReplConsole implements ShellConsole {
private Console console;
ReplConsole(Console console) {
this.console = console;
}
@Override
public String readLine() {
return console.readLine();
}
@Override
public void putstr(String s) {
console.writer().print(s);
}
@Override
public void print(String s) {
console.writer().println(s);
}
@Override
public void printErr(String s) {
System.err.println(s);
}
}
}
| Handle all exceptions in loop() method
| src/main/java/com/github/anba/es6draft/repl/Repl.java | Handle all exceptions in loop() method | <ide><path>rc/main/java/com/github/anba/es6draft/repl/Repl.java
<ide>
<ide> private void handleException(Throwable e) {
<ide> String message = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
<del> console.printf("%s\n", message);
<add> console.printf("%s%n", message);
<ide> if (options.contains(Option.StackTrace)) {
<ide> printStackTrace(e);
<ide> }
<ide> }
<ide>
<ide> private void handleException(ScriptException e) {
<del> console.printf("uncaught exception: %s\n", e.getMessage());
<add> console.printf("uncaught exception: %s%n", e.getMessage());
<ide> if (options.contains(Option.StackTrace)) {
<ide> printStackTrace(e);
<ide> }
<ide> */
<ide> private com.github.anba.es6draft.ast.Script read(Realm realm, int line) {
<ide> StringBuilder source = new StringBuilder();
<del> try {
<del> for (;;) {
<del> String s = console.readLine();
<del> if (s == null) {
<del> continue;
<del> }
<del> source.append(s).append('\n');
<del> try {
<del> EnumSet<Parser.Option> options = Parser.Option.from(realm.getOptions());
<del> Parser parser = new Parser("typein", line, options);
<del> return parser.parse(source);
<del> } catch (ParserEOFException e) {
<del> continue;
<del> }
<del> }
<del> } catch (ParserException | StackOverflowError e) {
<del> handleException(e);
<del> return null;
<add> for (;;) {
<add> String s = console.readLine();
<add> if (s == null) {
<add> continue;
<add> }
<add> source.append(s).append('\n');
<add> try {
<add> EnumSet<Parser.Option> options = Parser.Option.from(realm.getOptions());
<add> Parser parser = new Parser("typein", line, options);
<add> return parser.parse(source);
<add> } catch (ParserEOFException e) {
<add> continue;
<add> }
<ide> }
<ide> }
<ide>
<ide> * REPL: Eval
<ide> */
<ide> private Object eval(Realm realm, com.github.anba.es6draft.ast.Script parsedScript) {
<del> if (parsedScript.getStatements().isEmpty()) {
<del> console.writer().println();
<del> return null;
<del> }
<del> try {
<del> Script script = script(parsedScript);
<del> return ScriptLoader.ScriptEvaluation(script, realm, false);
<del> } catch (ScriptException e) {
<del> handleException(e);
<del> return null;
<del> } catch (ParserException | CompilationException | StackOverflowError e) {
<del> handleException(e);
<del> return null;
<del> }
<add> Script script = script(parsedScript);
<add> return ScriptLoader.ScriptEvaluation(script, realm, false);
<ide> }
<ide>
<ide> /**
<ide> * REPL: Print
<ide> */
<ide> private void print(Realm realm, Object result) {
<del> try {
<del> if (result != UNDEFINED) {
<del> console.writer().println(ToSource(realm.defaultContext(), result));
<del> }
<del> } catch (ScriptException e) {
<del> handleException(e);
<del> } catch (StackOverflowError e) {
<del> handleException(e);
<add> if (result != UNDEFINED) {
<add> console.printf("%s%n", ToSource(realm.defaultContext(), result));
<ide> }
<ide> }
<ide>
<ide> try {
<ide> console.printf("js> ");
<ide> com.github.anba.es6draft.ast.Script parsedScript = read(realm, line);
<del> if (parsedScript == null) {
<add> if (parsedScript.getStatements().isEmpty()) {
<ide> continue;
<ide> }
<ide> Object result = eval(realm, parsedScript);
<del> if (result == null) {
<del> continue;
<del> }
<ide> print(realm, result);
<ide> } catch (StopExecutionException e) {
<ide> if (e.getReason() == Reason.Quit) {
<ide> System.exit(0);
<ide> }
<add> } catch (ScriptException e) {
<add> handleException(e);
<add> } catch (ParserException | CompilationException | StackOverflowError e) {
<add> handleException(e);
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 407042057c4d22ae835043c7728777ac82534641 | 0 | ahb0327/intellij-community,caot/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,fnouama/intellij-community,signed/intellij-community,retomerz/intellij-community,allotria/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,supersven/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,ernestp/consulo,retomerz/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,holmes/intellij-community,ryano144/intellij-community,ibinti/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,amith01994/intellij-community,jagguli/intellij-community,hurricup/intellij-community,amith01994/intellij-community,petteyg/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,robovm/robovm-studio,diorcety/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,dslomov/intellij-community,dslomov/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,amith01994/intellij-community,signed/intellij-community,supersven/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,consulo/consulo,kdwink/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,vladmm/intellij-community,petteyg/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,izonder/intellij-community,apixandru/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,semonte/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,wreckJ/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,hurricup/intellij-community,robovm/robovm-studio,FHannes/intellij-community,petteyg/intellij-community,robovm/robovm-studio,adedayo/intellij-community,apixandru/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,holmes/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,da1z/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,caot/intellij-community,caot/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,allotria/intellij-community,holmes/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,kool79/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,da1z/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,samthor/intellij-community,asedunov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,allotria/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,slisson/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,caot/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,adedayo/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,samthor/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,kool79/intellij-community,consulo/consulo,kool79/intellij-community,robovm/robovm-studio,fnouama/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,supersven/intellij-community,signed/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,apixandru/intellij-community,petteyg/intellij-community,apixandru/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,signed/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,orekyuu/intellij-community,signed/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,clumsy/intellij-community,consulo/consulo,ryano144/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,kdwink/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,asedunov/intellij-community,jagguli/intellij-community,caot/intellij-community,blademainer/intellij-community,izonder/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,signed/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,fnouama/intellij-community,vladmm/intellij-community,robovm/robovm-studio,ernestp/consulo,ivan-fedorov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,vladmm/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,caot/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,fnouama/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,supersven/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,holmes/intellij-community,semonte/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,fnouama/intellij-community,consulo/consulo,MER-GROUP/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,samthor/intellij-community,izonder/intellij-community,supersven/intellij-community,vladmm/intellij-community,semonte/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,blademainer/intellij-community,allotria/intellij-community,kool79/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,hurricup/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ernestp/consulo,ahb0327/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,holmes/intellij-community,Distrotech/intellij-community,holmes/intellij-community,robovm/robovm-studio,semonte/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,semonte/intellij-community,jagguli/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,supersven/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,FHannes/intellij-community,signed/intellij-community,robovm/robovm-studio,holmes/intellij-community,allotria/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,allotria/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,FHannes/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,dslomov/intellij-community,caot/intellij-community,diorcety/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,consulo/consulo,diorcety/intellij-community,fnouama/intellij-community,da1z/intellij-community,slisson/intellij-community,Distrotech/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,izonder/intellij-community,supersven/intellij-community,apixandru/intellij-community,apixandru/intellij-community,petteyg/intellij-community,diorcety/intellij-community,adedayo/intellij-community,amith01994/intellij-community,fitermay/intellij-community,allotria/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,holmes/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,hurricup/intellij-community,da1z/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,diorcety/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,caot/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,signed/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,supersven/intellij-community,retomerz/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,izonder/intellij-community,ryano144/intellij-community,vladmm/intellij-community,xfournet/intellij-community,ernestp/consulo,akosyakov/intellij-community,semonte/intellij-community,xfournet/intellij-community,retomerz/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,kool79/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,slisson/intellij-community,consulo/consulo,petteyg/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,robovm/robovm-studio,izonder/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,fitermay/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,dslomov/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,kool79/intellij-community,akosyakov/intellij-community,samthor/intellij-community,blademainer/intellij-community,FHannes/intellij-community,petteyg/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,fitermay/intellij-community,samthor/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,retomerz/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,da1z/intellij-community,samthor/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,kool79/intellij-community,kdwink/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,xfournet/intellij-community,kdwink/intellij-community,holmes/intellij-community,FHannes/intellij-community,adedayo/intellij-community,izonder/intellij-community,slisson/intellij-community,samthor/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,FHannes/intellij-community,adedayo/intellij-community,slisson/intellij-community,FHannes/intellij-community,xfournet/intellij-community,da1z/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,nicolargo/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util;
import com.intellij.CommonBundle;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.DataManager;
import com.intellij.ide.DeleteProvider;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ex.MessagesEx;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.WritingAccessProvider;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.safeDelete.SafeDeleteProcessor;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.io.ReadOnlyAttributeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class DeleteHandler {
private DeleteHandler() {
}
public static class DefaultDeleteProvider implements DeleteProvider {
public boolean canDeleteElement(@NotNull DataContext dataContext) {
if (PlatformDataKeys.PROJECT.getData(dataContext) == null) {
return false;
}
final PsiElement[] elements = getPsiElements(dataContext);
return elements != null && shouldEnableDeleteAction(elements);
}
@Nullable
private static PsiElement[] getPsiElements(DataContext dataContext) {
PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
if (elements == null) {
final Object data = LangDataKeys.PSI_ELEMENT.getData(dataContext);
if (data != null) {
elements = new PsiElement[]{(PsiElement)data};
}
else {
final Object data1 = LangDataKeys.PSI_FILE.getData(dataContext);
if (data1 != null) {
elements = new PsiElement[]{(PsiFile)data1};
}
}
}
return elements;
}
public void deleteElement(@NotNull DataContext dataContext) {
PsiElement[] elements = getPsiElements(dataContext);
if (elements == null) return;
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
if (project == null) return;
LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting"));
try {
deletePsiElement(elements, project);
}
finally {
a.finish();
}
}
}
public static void deletePsiElement(final PsiElement[] elementsToDelete, final Project project) {
deletePsiElement(elementsToDelete, project, true);
}
public static void deletePsiElement(final PsiElement[] elementsToDelete, final Project project, boolean needConfirmation) {
if (elementsToDelete == null || elementsToDelete.length == 0) return;
final PsiElement[] elements = PsiTreeUtil.filterAncestors(elementsToDelete);
boolean safeDeleteApplicable = true;
for (int i = 0; i < elements.length && safeDeleteApplicable; i++) {
PsiElement element = elements[i];
safeDeleteApplicable = SafeDeleteProcessor.validElement(element);
}
final boolean dumb = DumbService.getInstance(project).isDumb();
if (safeDeleteApplicable && !dumb) {
final Ref<Boolean> exit = Ref.create(false);
DeleteDialog dialog = new DeleteDialog(project, elements, new DeleteDialog.Callback() {
public void run(final DeleteDialog dialog) {
if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(elements), true)) return;
SafeDeleteProcessor.createInstance(project, new Runnable() {
public void run() {
exit.set(true);
dialog.close(DialogWrapper.OK_EXIT_CODE);
}
}, elements, dialog.isSearchInComments(), dialog.isSearchInNonJava(), true).run();
}
});
if (needConfirmation) {
dialog.show();
if (!dialog.isOK() || exit.get()) return;
}
}
else {
@SuppressWarnings({"UnresolvedPropertyKey"})
String warningMessage = DeleteUtil.generateWarningMessage(IdeBundle.message("prompt.delete.elements"), elements);
boolean anyDirectories = false;
String directoryName = null;
for (PsiElement psiElement : elementsToDelete) {
if (psiElement instanceof PsiDirectory && !PsiUtilBase.isSymLink((PsiDirectory)psiElement)) {
anyDirectories = true;
directoryName = ((PsiDirectory)psiElement).getName();
break;
}
}
if (anyDirectories) {
if (elements.length == 1) {
warningMessage += IdeBundle.message("warning.delete.all.files.and.subdirectories", directoryName);
}
else {
warningMessage += IdeBundle.message("warning.delete.all.files.and.subdirectories.in.the.selected.directory");
}
}
if (safeDeleteApplicable && dumb) {
warningMessage += "\n\nWarning:\n Safe delete is not available while " +
ApplicationNamesInfo.getInstance().getFullProductName() +
" updates indices,\n no usages will be checked.";
}
if (needConfirmation) {
int result = Messages.showOkCancelDialog(project, warningMessage, IdeBundle.message("title.delete"),
ApplicationBundle.message("button.delete"), CommonBundle.getCancelButtonText(),
Messages.getQuestionIcon());
if (result != 0) return;
}
}
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(elements), false)) {
return;
}
// deleted from project view or something like that.
if (PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext()) == null) {
CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
}
for (final PsiElement elementToDelete : elements) {
if (!elementToDelete.isValid()) continue; //was already deleted
if (elementToDelete instanceof PsiDirectory) {
VirtualFile virtualFile = ((PsiDirectory)elementToDelete).getVirtualFile();
if (virtualFile.isInLocalFileSystem() && !virtualFile.isSymLink()) {
ArrayList<VirtualFile> readOnlyFiles = new ArrayList<VirtualFile>();
CommonRefactoringUtil.collectReadOnlyFiles(virtualFile, readOnlyFiles);
if (!readOnlyFiles.isEmpty()) {
String message = IdeBundle.message("prompt.directory.contains.read.only.files", virtualFile.getPresentableUrl());
int _result = Messages.showYesNoDialog(project, message, IdeBundle.message("title.delete"), Messages.getQuestionIcon());
if (_result != 0) continue;
boolean success = true;
for (VirtualFile file : readOnlyFiles) {
success = clearReadOnlyFlag(file, project);
if (!success) break;
}
if (!success) continue;
}
}
}
else if (!elementToDelete.isWritable() &&
!(elementToDelete instanceof PsiFileSystemItem && PsiUtilBase.isSymLink((PsiFileSystemItem)elementToDelete))) {
final PsiFile file = elementToDelete.getContainingFile();
if (file != null) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile.isInLocalFileSystem()) {
int _result = MessagesEx.fileIsReadOnly(project, virtualFile)
.setTitle(IdeBundle.message("title.delete"))
.appendMessage(IdeBundle.message("prompt.delete.it.anyway"))
.askYesNo();
if (_result != 0) continue;
boolean success = clearReadOnlyFlag(virtualFile, project);
if (!success) continue;
}
}
}
try {
elementToDelete.checkDelete();
}
catch (IncorrectOperationException ex) {
Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon());
continue;
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
elementToDelete.delete();
}
catch (final IncorrectOperationException ex) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon());
}
});
}
}
});
}
}
}, RefactoringBundle.message("safe.delete.command", RefactoringUIUtil.calculatePsiElementDescriptionList(elements)), null);
}
private static boolean clearReadOnlyFlag(final VirtualFile virtualFile, final Project project) {
final boolean[] success = new boolean[1];
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
Runnable action = new Runnable() {
public void run() {
try {
ReadOnlyAttributeUtil.setReadOnlyAttribute(virtualFile, false);
success[0] = true;
}
catch (IOException e1) {
Messages.showMessageDialog(project, e1.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon());
}
}
};
ApplicationManager.getApplication().runWriteAction(action);
}
}, "", null);
return success[0];
}
public static boolean shouldEnableDeleteAction(PsiElement[] elements) {
if (elements == null || elements.length == 0) return false;
for (PsiElement element : elements) {
VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
if (virtualFile == null) {
return false;
}
if (!WritingAccessProvider.isPotentiallyWritable(virtualFile, element.getProject())) {
return false;
}
}
return true;
}
}
| platform/lang-impl/src/com/intellij/ide/util/DeleteHandler.java | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util;
import com.intellij.CommonBundle;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.DataManager;
import com.intellij.ide.DeleteProvider;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ex.MessagesEx;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.WritingAccessProvider;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilBase;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.safeDelete.SafeDeleteProcessor;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.io.ReadOnlyAttributeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public class DeleteHandler {
private DeleteHandler() {
}
public static class DefaultDeleteProvider implements DeleteProvider {
public boolean canDeleteElement(@NotNull DataContext dataContext) {
if (PlatformDataKeys.PROJECT.getData(dataContext) == null) {
return false;
}
final PsiElement[] elements = getPsiElements(dataContext);
return elements != null && shouldEnableDeleteAction(elements);
}
@Nullable
private static PsiElement[] getPsiElements(DataContext dataContext) {
PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
if (elements == null) {
final Object data = LangDataKeys.PSI_ELEMENT.getData(dataContext);
if (data != null) {
elements = new PsiElement[]{(PsiElement)data};
}
else {
final Object data1 = LangDataKeys.PSI_FILE.getData(dataContext);
if (data1 != null) {
elements = new PsiElement[]{(PsiFile)data1};
}
}
}
return elements;
}
public void deleteElement(@NotNull DataContext dataContext) {
PsiElement[] elements = getPsiElements(dataContext);
if (elements == null) return;
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
if (project == null) return;
LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting"));
try {
deletePsiElement(elements, project);
}
finally {
a.finish();
}
}
}
public static void deletePsiElement(final PsiElement[] elementsToDelete, final Project project) {
deletePsiElement(elementsToDelete, project, true);
}
public static void deletePsiElement(final PsiElement[] elementsToDelete, final Project project, boolean needConfirmation) {
if (elementsToDelete == null || elementsToDelete.length == 0) return;
final PsiElement[] elements = PsiTreeUtil.filterAncestors(elementsToDelete);
boolean safeDeleteApplicable = true;
for (int i = 0; i < elements.length && safeDeleteApplicable; i++) {
PsiElement element = elements[i];
safeDeleteApplicable = SafeDeleteProcessor.validElement(element);
}
final boolean dumb = DumbService.getInstance(project).isDumb();
if (safeDeleteApplicable && !dumb) {
DeleteDialog dialog = new DeleteDialog(project, elements, new DeleteDialog.Callback() {
public void run(final DeleteDialog dialog) {
if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(elements), true)) return;
SafeDeleteProcessor.createInstance(project, new Runnable() {
public void run() {
dialog.close(DialogWrapper.CANCEL_EXIT_CODE);
}
}, elements, dialog.isSearchInComments(), dialog.isSearchInNonJava(), true).run();
}
});
if (needConfirmation) {
dialog.show();
if (!dialog.isOK()) return;
}
}
else {
@SuppressWarnings({"UnresolvedPropertyKey"})
String warningMessage = DeleteUtil.generateWarningMessage(IdeBundle.message("prompt.delete.elements"), elements);
boolean anyDirectories = false;
String directoryName = null;
for (PsiElement psiElement : elementsToDelete) {
if (psiElement instanceof PsiDirectory && !PsiUtilBase.isSymLink((PsiDirectory)psiElement)) {
anyDirectories = true;
directoryName = ((PsiDirectory)psiElement).getName();
break;
}
}
if (anyDirectories) {
if (elements.length == 1) {
warningMessage += IdeBundle.message("warning.delete.all.files.and.subdirectories", directoryName);
}
else {
warningMessage += IdeBundle.message("warning.delete.all.files.and.subdirectories.in.the.selected.directory");
}
}
if (safeDeleteApplicable && dumb) {
warningMessage += "\n\nWarning:\n Safe delete is not available while " +
ApplicationNamesInfo.getInstance().getFullProductName() +
" updates indices,\n no usages will be checked.";
}
if (needConfirmation) {
int result = Messages.showOkCancelDialog(project, warningMessage, IdeBundle.message("title.delete"),
ApplicationBundle.message("button.delete"), CommonBundle.getCancelButtonText(),
Messages.getQuestionIcon());
if (result != 0) return;
}
}
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(elements), false)) {
return;
}
// deleted from project view or something like that.
if (PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext()) == null) {
CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
}
for (final PsiElement elementToDelete : elements) {
if (!elementToDelete.isValid()) continue; //was already deleted
if (elementToDelete instanceof PsiDirectory) {
VirtualFile virtualFile = ((PsiDirectory)elementToDelete).getVirtualFile();
if (virtualFile.isInLocalFileSystem() && !virtualFile.isSymLink()) {
ArrayList<VirtualFile> readOnlyFiles = new ArrayList<VirtualFile>();
CommonRefactoringUtil.collectReadOnlyFiles(virtualFile, readOnlyFiles);
if (!readOnlyFiles.isEmpty()) {
String message = IdeBundle.message("prompt.directory.contains.read.only.files", virtualFile.getPresentableUrl());
int _result = Messages.showYesNoDialog(project, message, IdeBundle.message("title.delete"), Messages.getQuestionIcon());
if (_result != 0) continue;
boolean success = true;
for (VirtualFile file : readOnlyFiles) {
success = clearReadOnlyFlag(file, project);
if (!success) break;
}
if (!success) continue;
}
}
}
else if (!elementToDelete.isWritable() &&
!(elementToDelete instanceof PsiFileSystemItem && PsiUtilBase.isSymLink((PsiFileSystemItem)elementToDelete))) {
final PsiFile file = elementToDelete.getContainingFile();
if (file != null) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile.isInLocalFileSystem()) {
int _result = MessagesEx.fileIsReadOnly(project, virtualFile)
.setTitle(IdeBundle.message("title.delete"))
.appendMessage(IdeBundle.message("prompt.delete.it.anyway"))
.askYesNo();
if (_result != 0) continue;
boolean success = clearReadOnlyFlag(virtualFile, project);
if (!success) continue;
}
}
}
try {
elementToDelete.checkDelete();
}
catch (IncorrectOperationException ex) {
Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon());
continue;
}
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
elementToDelete.delete();
}
catch (final IncorrectOperationException ex) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon());
}
});
}
}
});
}
}
}, RefactoringBundle.message("safe.delete.command", RefactoringUIUtil.calculatePsiElementDescriptionList(elements)), null);
}
private static boolean clearReadOnlyFlag(final VirtualFile virtualFile, final Project project) {
final boolean[] success = new boolean[1];
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
Runnable action = new Runnable() {
public void run() {
try {
ReadOnlyAttributeUtil.setReadOnlyAttribute(virtualFile, false);
success[0] = true;
}
catch (IOException e1) {
Messages.showMessageDialog(project, e1.getMessage(), CommonBundle.getErrorTitle(), Messages.getErrorIcon());
}
}
};
ApplicationManager.getApplication().runWriteAction(action);
}
}, "", null);
return success[0];
}
public static boolean shouldEnableDeleteAction(PsiElement[] elements) {
if (elements == null || elements.length == 0) return false;
for (PsiElement element : elements) {
VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
if (virtualFile == null) {
return false;
}
if (!WritingAccessProvider.isPotentiallyWritable(virtualFile, element.getProject())) {
return false;
}
}
return true;
}
}
| no hacks, please (This will be used in NavBarListener to fix IDEA-96105)
| platform/lang-impl/src/com/intellij/ide/util/DeleteHandler.java | no hacks, please (This will be used in NavBarListener to fix IDEA-96105) | <ide><path>latform/lang-impl/src/com/intellij/ide/util/DeleteHandler.java
<ide> /*
<del> * Copyright 2000-2012 JetBrains s.r.o.
<add> * Copyright 2000-2013 JetBrains s.r.o.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import com.intellij.openapi.ui.DialogWrapper;
<ide> import com.intellij.openapi.ui.Messages;
<ide> import com.intellij.openapi.ui.ex.MessagesEx;
<add>import com.intellij.openapi.util.Ref;
<ide> import com.intellij.openapi.vfs.VirtualFile;
<ide> import com.intellij.openapi.vfs.WritingAccessProvider;
<ide> import com.intellij.psi.PsiDirectory;
<ide>
<ide> final boolean dumb = DumbService.getInstance(project).isDumb();
<ide> if (safeDeleteApplicable && !dumb) {
<add> final Ref<Boolean> exit = Ref.create(false);
<ide> DeleteDialog dialog = new DeleteDialog(project, elements, new DeleteDialog.Callback() {
<ide> public void run(final DeleteDialog dialog) {
<ide> if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(elements), true)) return;
<ide> SafeDeleteProcessor.createInstance(project, new Runnable() {
<ide> public void run() {
<del> dialog.close(DialogWrapper.CANCEL_EXIT_CODE);
<add> exit.set(true);
<add> dialog.close(DialogWrapper.OK_EXIT_CODE);
<ide> }
<ide> }, elements, dialog.isSearchInComments(), dialog.isSearchInNonJava(), true).run();
<ide> }
<ide> });
<ide> if (needConfirmation) {
<ide> dialog.show();
<del> if (!dialog.isOK()) return;
<add> if (!dialog.isOK() || exit.get()) return;
<ide> }
<ide> }
<ide> else { |
|
Java | apache-2.0 | f0eb79540497e0d3ec5fbbe56119596effa4302c | 0 | udayinfy/vaadin,jdahlstrom/vaadin.react,magi42/vaadin,cbmeeks/vaadin,Flamenco/vaadin,mstahv/framework,asashour/framework,Flamenco/vaadin,udayinfy/vaadin,oalles/vaadin,peterl1084/framework,asashour/framework,Peppe/vaadin,magi42/vaadin,sitexa/vaadin,shahrzadmn/vaadin,fireflyc/vaadin,Scarlethue/vaadin,Darsstar/framework,synes/vaadin,oalles/vaadin,Legioth/vaadin,fireflyc/vaadin,carrchang/vaadin,kironapublic/vaadin,asashour/framework,cbmeeks/vaadin,Legioth/vaadin,Scarlethue/vaadin,mstahv/framework,synes/vaadin,jdahlstrom/vaadin.react,mstahv/framework,magi42/vaadin,oalles/vaadin,kironapublic/vaadin,peterl1084/framework,kironapublic/vaadin,travisfw/vaadin,synes/vaadin,travisfw/vaadin,asashour/framework,cbmeeks/vaadin,peterl1084/framework,sitexa/vaadin,peterl1084/framework,bmitc/vaadin,synes/vaadin,Darsstar/framework,travisfw/vaadin,sitexa/vaadin,travisfw/vaadin,carrchang/vaadin,mittop/vaadin,oalles/vaadin,jdahlstrom/vaadin.react,Flamenco/vaadin,Peppe/vaadin,Flamenco/vaadin,oalles/vaadin,kironapublic/vaadin,jdahlstrom/vaadin.react,mittop/vaadin,Scarlethue/vaadin,Darsstar/framework,Legioth/vaadin,Peppe/vaadin,Peppe/vaadin,mstahv/framework,synes/vaadin,bmitc/vaadin,bmitc/vaadin,shahrzadmn/vaadin,sitexa/vaadin,carrchang/vaadin,asashour/framework,udayinfy/vaadin,magi42/vaadin,udayinfy/vaadin,udayinfy/vaadin,magi42/vaadin,peterl1084/framework,mstahv/framework,Darsstar/framework,kironapublic/vaadin,mittop/vaadin,travisfw/vaadin,jdahlstrom/vaadin.react,carrchang/vaadin,cbmeeks/vaadin,shahrzadmn/vaadin,Legioth/vaadin,fireflyc/vaadin,Legioth/vaadin,Peppe/vaadin,bmitc/vaadin,Darsstar/framework,fireflyc/vaadin,fireflyc/vaadin,mittop/vaadin,Scarlethue/vaadin,shahrzadmn/vaadin,Scarlethue/vaadin,sitexa/vaadin,shahrzadmn/vaadin | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Iterator;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.dom.client.HasDoubleClickHandlers;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
public class VTwinColSelect extends VOptionGroupBase implements KeyDownHandler,
MouseDownHandler, DoubleClickHandler, SubPartAware {
private static final String CLASSNAME = "v-select-twincol";
public static final String ATTRIBUTE_LEFT_CAPTION = "lc";
public static final String ATTRIBUTE_RIGHT_CAPTION = "rc";
private static final int VISIBLE_COUNT = 10;
private static final int DEFAULT_COLUMN_COUNT = 10;
private final DoubleClickListBox options;
private final DoubleClickListBox selections;
private FlowPanel captionWrapper;
private HTML optionsCaption = null;
private HTML selectionsCaption = null;
private final VButton add;
private final VButton remove;
private final FlowPanel buttons;
private final Panel panel;
private boolean widthSet = false;
/**
* A ListBox which catches double clicks
*
*/
public class DoubleClickListBox extends ListBox implements
HasDoubleClickHandlers {
public DoubleClickListBox(boolean isMultipleSelect) {
super(isMultipleSelect);
}
public DoubleClickListBox() {
super();
}
@Override
public HandlerRegistration addDoubleClickHandler(
DoubleClickHandler handler) {
return addDomHandler(handler, DoubleClickEvent.getType());
}
}
public VTwinColSelect() {
super(CLASSNAME);
captionWrapper = new FlowPanel();
options = new DoubleClickListBox();
options.addClickHandler(this);
options.addDoubleClickHandler(this);
options.setVisibleItemCount(VISIBLE_COUNT);
options.setStyleName(CLASSNAME + "-options");
selections = new DoubleClickListBox();
selections.addClickHandler(this);
selections.addDoubleClickHandler(this);
selections.setVisibleItemCount(VISIBLE_COUNT);
selections.setStyleName(CLASSNAME + "-selections");
buttons = new FlowPanel();
buttons.setStyleName(CLASSNAME + "-buttons");
add = new VButton();
add.setText(">>");
add.addClickHandler(this);
remove = new VButton();
remove.setText("<<");
remove.addClickHandler(this);
panel = ((Panel) optionsContainer);
panel.add(captionWrapper);
captionWrapper.getElement().getStyle().setOverflow(Overflow.HIDDEN);
// Hide until there actually is a caption to prevent IE from rendering
// extra empty space
captionWrapper.setVisible(false);
panel.add(options);
buttons.add(add);
final HTML br = new HTML("<span/>");
br.setStyleName(CLASSNAME + "-deco");
buttons.add(br);
buttons.add(remove);
panel.add(buttons);
panel.add(selections);
options.addKeyDownHandler(this);
options.addMouseDownHandler(this);
selections.addMouseDownHandler(this);
selections.addKeyDownHandler(this);
}
public HTML getOptionsCaption() {
if (optionsCaption == null) {
optionsCaption = new HTML();
optionsCaption.setStyleName(CLASSNAME + "-options-caption");
optionsCaption.getElement().getStyle()
.setFloat(com.google.gwt.dom.client.Style.Float.LEFT);
captionWrapper.add(optionsCaption);
}
return optionsCaption;
}
public HTML getSelectionsCaption() {
if (selectionsCaption == null) {
selectionsCaption = new HTML();
selectionsCaption.setStyleName(CLASSNAME + "-selections-caption");
selectionsCaption.getElement().getStyle()
.setFloat(com.google.gwt.dom.client.Style.Float.RIGHT);
captionWrapper.add(selectionsCaption);
}
return selectionsCaption;
}
@Override
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Captions are updated before super call to ensure the widths are set
// correctly
updateCaptions(uidl);
super.updateFromUIDL(uidl, client);
// If the server request that a cached instance should be used, do
// nothing
// if (uidl.isCachedComponent()) {
if (uidl.getBooleanAttribute("cached")) {
// Cached update, nothing to do)
return;
}
}
private void updateCaptions(UIDL uidl) {
String leftCaption = (uidl.hasAttribute(ATTRIBUTE_LEFT_CAPTION) ? uidl
.getStringAttribute(ATTRIBUTE_LEFT_CAPTION) : null);
String rightCaption = (uidl.hasAttribute(ATTRIBUTE_RIGHT_CAPTION) ? uidl
.getStringAttribute(ATTRIBUTE_RIGHT_CAPTION) : null);
boolean hasCaptions = (leftCaption != null || rightCaption != null);
if (leftCaption == null) {
removeOptionsCaption();
} else {
getOptionsCaption().setText(leftCaption);
}
if (rightCaption == null) {
removeSelectionsCaption();
} else {
getSelectionsCaption().setText(rightCaption);
}
captionWrapper.setVisible(hasCaptions);
}
private void removeOptionsCaption() {
if (optionsCaption == null) {
return;
}
if (optionsCaption.getParent() != null) {
captionWrapper.remove(optionsCaption);
}
optionsCaption = null;
}
private void removeSelectionsCaption() {
if (selectionsCaption == null) {
return;
}
if (selectionsCaption.getParent() != null) {
captionWrapper.remove(selectionsCaption);
}
selectionsCaption = null;
}
@Override
protected void buildOptions(UIDL uidl) {
final boolean enabled = !isDisabled() && !isReadonly();
options.setMultipleSelect(isMultiselect());
selections.setMultipleSelect(isMultiselect());
options.setEnabled(enabled);
selections.setEnabled(enabled);
add.setEnabled(enabled);
remove.setEnabled(enabled);
options.clear();
selections.clear();
for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {
final UIDL optionUidl = (UIDL) i.next();
if (optionUidl.hasAttribute("selected")) {
selections.addItem(optionUidl.getStringAttribute("caption"),
optionUidl.getStringAttribute("key"));
} else {
options.addItem(optionUidl.getStringAttribute("caption"),
optionUidl.getStringAttribute("key"));
}
}
int cols = -1;
if (getColumns() > 0) {
cols = getColumns();
} else if (!widthSet) {
cols = DEFAULT_COLUMN_COUNT;
}
if (cols >= 0) {
String colWidth = cols + "em";
String containerWidth = (2 * cols + 4) + "em";
// Caption wrapper width == optionsSelect + buttons +
// selectionsSelect
String captionWrapperWidth = (2 * cols + 4 - 0.5) + "em";
options.setWidth(colWidth);
if (optionsCaption != null) {
optionsCaption.setWidth(colWidth);
}
selections.setWidth(colWidth);
if (selectionsCaption != null) {
selectionsCaption.setWidth(colWidth);
}
buttons.setWidth("3.5em");
optionsContainer.setWidth(containerWidth);
captionWrapper.setWidth(captionWrapperWidth);
}
if (getRows() > 0) {
options.setVisibleItemCount(getRows());
selections.setVisibleItemCount(getRows());
}
}
@Override
protected String[] getSelectedItems() {
final ArrayList<String> selectedItemKeys = new ArrayList<String>();
for (int i = 0; i < selections.getItemCount(); i++) {
selectedItemKeys.add(selections.getValue(i));
}
return selectedItemKeys.toArray(new String[selectedItemKeys.size()]);
}
private boolean[] getItemsToAdd() {
final boolean[] selectedIndexes = new boolean[options.getItemCount()];
for (int i = 0; i < options.getItemCount(); i++) {
if (options.isItemSelected(i)) {
selectedIndexes[i] = true;
} else {
selectedIndexes[i] = false;
}
}
return selectedIndexes;
}
private boolean[] getItemsToRemove() {
final boolean[] selectedIndexes = new boolean[selections.getItemCount()];
for (int i = 0; i < selections.getItemCount(); i++) {
if (selections.isItemSelected(i)) {
selectedIndexes[i] = true;
} else {
selectedIndexes[i] = false;
}
}
return selectedIndexes;
}
private void addItem() {
final boolean[] sel = getItemsToAdd();
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
final int optionIndex = i
- (sel.length - options.getItemCount());
selectedKeys.add(options.getValue(optionIndex));
// Move selection to another column
final String text = options.getItemText(optionIndex);
final String value = options.getValue(optionIndex);
selections.addItem(text, value);
selections.setItemSelected(selections.getItemCount() - 1, true);
options.removeItem(optionIndex);
if (options.getItemCount() > 0) {
options.setItemSelected(optionIndex > 0 ? optionIndex - 1
: 0, true);
}
}
}
// If no items are left move the focus to the selections
if (options.getItemCount() == 0) {
selections.setFocus(true);
} else {
options.setFocus(true);
}
client.updateVariable(id, "selected",
selectedKeys.toArray(new String[selectedKeys.size()]),
isImmediate());
}
private void removeItem() {
final boolean[] sel = getItemsToRemove();
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
final int selectionIndex = i
- (sel.length - selections.getItemCount());
selectedKeys.remove(selections.getValue(selectionIndex));
// Move selection to another column
final String text = selections.getItemText(selectionIndex);
final String value = selections.getValue(selectionIndex);
options.addItem(text, value);
options.setItemSelected(options.getItemCount() - 1, true);
selections.removeItem(selectionIndex);
if (selections.getItemCount() > 0) {
selections.setItemSelected(
selectionIndex > 0 ? selectionIndex - 1 : 0, true);
}
}
}
// If no items are left move the focus to the selections
if (selections.getItemCount() == 0) {
options.setFocus(true);
} else {
selections.setFocus(true);
}
client.updateVariable(id, "selected",
selectedKeys.toArray(new String[selectedKeys.size()]),
isImmediate());
}
@Override
public void onClick(ClickEvent event) {
super.onClick(event);
if (event.getSource() == add) {
addItem();
} else if (event.getSource() == remove) {
removeItem();
} else if (event.getSource() == options) {
// unselect all in other list, to avoid mistakes (i.e wrong button)
final int c = selections.getItemCount();
for (int i = 0; i < c; i++) {
selections.setItemSelected(i, false);
}
} else if (event.getSource() == selections) {
// unselect all in other list, to avoid mistakes (i.e wrong button)
final int c = options.getItemCount();
for (int i = 0; i < c; i++) {
options.setItemSelected(i, false);
}
}
}
@Override
public void setHeight(String height) {
super.setHeight(height);
if ("".equals(height)) {
options.setHeight("");
selections.setHeight("");
} else {
setInternalHeights();
}
}
private void setInternalHeights() {
int captionHeight = 0;
int totalHeight;
if (BrowserInfo.get().isIE6()) {
String o = getElement().getStyle().getOverflow();
getElement().getStyle().setOverflow(Overflow.HIDDEN);
totalHeight = getOffsetHeight();
getElement().getStyle().setProperty("overflow", o);
} else {
totalHeight = getOffsetHeight();
}
if (optionsCaption != null) {
captionHeight = Util.getRequiredHeight(optionsCaption);
} else if (selectionsCaption != null) {
captionHeight = Util.getRequiredHeight(selectionsCaption);
}
String selectHeight = (totalHeight - captionHeight) + "px";
selections.setHeight(selectHeight);
options.setHeight(selectHeight);
}
@Override
public void setWidth(String width) {
super.setWidth(width);
if (!"".equals(width) && width != null) {
setInternalWidths();
widthSet = true;
} else {
widthSet = false;
}
}
private void setInternalWidths() {
DOM.setStyleAttribute(getElement(), "position", "relative");
// TODO: Should really take borders/padding/margin into account.
// Compensating for now with a guess.
int buttonsExtraWidth = Util.measureHorizontalPaddingAndBorder(
buttons.getElement(), 0);
int buttonWidth = Util.getRequiredWidth(buttons) + buttonsExtraWidth;
int totalWidth = getOffsetWidth();
int spaceForSelect = (totalWidth - buttonWidth) / 2;
options.setWidth(spaceForSelect + "px");
if (optionsCaption != null) {
optionsCaption.setWidth(spaceForSelect + "px");
}
selections.setWidth(spaceForSelect + "px");
if (selectionsCaption != null) {
selectionsCaption.setWidth(spaceForSelect + "px");
}
captionWrapper.setWidth("100%");
}
@Override
protected void setTabIndex(int tabIndex) {
options.setTabIndex(tabIndex);
selections.setTabIndex(tabIndex);
add.setTabIndex(tabIndex);
remove.setTabIndex(tabIndex);
}
public void focus() {
options.setFocus(true);
}
/**
* Get the key that selects an item in the table. By default it is the Enter
* key but by overriding this you can change the key to whatever you want.
*
* @return
*/
protected int getNavigationSelectKey() {
return KeyCodes.KEY_ENTER;
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
* .event.dom.client.KeyDownEvent)
*/
public void onKeyDown(KeyDownEvent event) {
int keycode = event.getNativeKeyCode();
// Catch tab and move between select:s
if (keycode == KeyCodes.KEY_TAB && event.getSource() == options) {
// Prevent default behavior
event.preventDefault();
// Remove current selections
for (int i = 0; i < options.getItemCount(); i++) {
options.setItemSelected(i, false);
}
// Focus selections
selections.setFocus(true);
}
if (keycode == KeyCodes.KEY_TAB && event.isShiftKeyDown()
&& event.getSource() == selections) {
// Prevent default behavior
event.preventDefault();
// Remove current selections
for (int i = 0; i < selections.getItemCount(); i++) {
selections.setItemSelected(i, false);
}
// Focus options
options.setFocus(true);
}
if (keycode == getNavigationSelectKey()) {
// Prevent default behavior
event.preventDefault();
// Decide which select the selection was made in
if (event.getSource() == options) {
// Prevents the selection to become a single selection when
// using Enter key
// as the selection key (default)
options.setFocus(false);
addItem();
} else if (event.getSource() == selections) {
// Prevents the selection to become a single selection when
// using Enter key
// as the selection key (default)
selections.setFocus(false);
removeItem();
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google
* .gwt.event.dom.client.MouseDownEvent)
*/
public void onMouseDown(MouseDownEvent event) {
// Ensure that items are deselected when selecting
// from a different source. See #3699 for details.
if (event.getSource() == options) {
for (int i = 0; i < selections.getItemCount(); i++) {
selections.setItemSelected(i, false);
}
} else if (event.getSource() == selections) {
for (int i = 0; i < options.getItemCount(); i++) {
options.setItemSelected(i, false);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.DoubleClickHandler#onDoubleClick(com.
* google.gwt.event.dom.client.DoubleClickEvent)
*/
public void onDoubleClick(DoubleClickEvent event) {
if (event.getSource() == options) {
addItem();
options.setSelectedIndex(-1);
options.setFocus(false);
} else if (event.getSource() == selections) {
removeItem();
selections.setSelectedIndex(-1);
selections.setFocus(false);
}
}
private static final String SUBPART_OPTION_SELECT = "leftSelect";
private static final String SUBPART_SELECTION_SELECT = "rightSelect";
private static final String SUBPART_LEFT_CAPTION = "leftCaption";
private static final String SUBPART_RIGHT_CAPTION = "rightCaption";
private static final String SUBPART_ADD_BUTTON = "add";
private static final String SUBPART_REMOVE_BUTTON = "remove";
public Element getSubPartElement(String subPart) {
if (SUBPART_OPTION_SELECT.equals(subPart)) {
return options.getElement();
} else if (SUBPART_SELECTION_SELECT.equals(subPart)) {
return selections.getElement();
} else if (optionsCaption != null
&& SUBPART_LEFT_CAPTION.equals(subPart)) {
return optionsCaption.getElement();
} else if (selectionsCaption != null
&& SUBPART_RIGHT_CAPTION.equals(subPart)) {
return selectionsCaption.getElement();
} else if (SUBPART_ADD_BUTTON.equals(subPart)) {
return add.getElement();
} else if (SUBPART_REMOVE_BUTTON.equals(subPart)) {
return remove.getElement();
}
return null;
}
public String getSubPartName(Element subElement) {
if (optionsCaption != null
&& optionsCaption.getElement().isOrHasChild(subElement)) {
return SUBPART_LEFT_CAPTION;
} else if (selectionsCaption != null
&& selectionsCaption.getElement().isOrHasChild(subElement)) {
return SUBPART_RIGHT_CAPTION;
} else if (options.getElement().isOrHasChild(subElement)) {
return SUBPART_OPTION_SELECT;
} else if (selections.getElement().isOrHasChild(subElement)) {
return SUBPART_SELECTION_SELECT;
} else if (add.getElement().isOrHasChild(subElement)) {
return SUBPART_ADD_BUTTON;
} else if (remove.getElement().isOrHasChild(subElement)) {
return SUBPART_REMOVE_BUTTON;
}
return null;
}
}
| src/com/vaadin/terminal/gwt/client/ui/VTwinColSelect.java | /*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Iterator;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.dom.client.HasDoubleClickHandlers;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
public class VTwinColSelect extends VOptionGroupBase implements KeyDownHandler,
MouseDownHandler, DoubleClickHandler, SubPartAware {
private static final String CLASSNAME = "v-select-twincol";
public static final String ATTRIBUTE_LEFT_CAPTION = "lc";
public static final String ATTRIBUTE_RIGHT_CAPTION = "rc";
private static final int VISIBLE_COUNT = 10;
private static final int DEFAULT_COLUMN_COUNT = 10;
private final DoubleClickListBox options;
private final DoubleClickListBox selections;
private FlowPanel captionWrapper;
private HTML optionsCaption = null;
private HTML selectionsCaption = null;
private final VButton add;
private final VButton remove;
private final FlowPanel buttons;
private final Panel panel;
private boolean widthSet = false;
/**
* A ListBox which catches double clicks
*
*/
public class DoubleClickListBox extends ListBox implements
HasDoubleClickHandlers {
public DoubleClickListBox(boolean isMultipleSelect) {
super(isMultipleSelect);
}
public DoubleClickListBox() {
super();
}
@Override
public HandlerRegistration addDoubleClickHandler(
DoubleClickHandler handler) {
return addDomHandler(handler, DoubleClickEvent.getType());
}
}
public VTwinColSelect() {
super(CLASSNAME);
captionWrapper = new FlowPanel();
options = new DoubleClickListBox();
options.addClickHandler(this);
options.addDoubleClickHandler(this);
options.setVisibleItemCount(VISIBLE_COUNT);
options.setStyleName(CLASSNAME + "-options");
selections = new DoubleClickListBox();
selections.addClickHandler(this);
selections.addDoubleClickHandler(this);
selections.setVisibleItemCount(VISIBLE_COUNT);
selections.setStyleName(CLASSNAME + "-selections");
buttons = new FlowPanel();
buttons.setStyleName(CLASSNAME + "-buttons");
add = new VButton();
add.setText(">>");
add.addClickHandler(this);
remove = new VButton();
remove.setText("<<");
remove.addClickHandler(this);
panel = ((Panel) optionsContainer);
panel.add(captionWrapper);
captionWrapper.getElement().getStyle().setOverflow(Overflow.HIDDEN);
// Hide until there actually is a caption to prevent IE from rendering
// extra empty space
captionWrapper.setVisible(false);
panel.add(options);
buttons.add(add);
final HTML br = new HTML("<span/>");
br.setStyleName(CLASSNAME + "-deco");
buttons.add(br);
buttons.add(remove);
panel.add(buttons);
panel.add(selections);
options.addKeyDownHandler(this);
options.addMouseDownHandler(this);
selections.addMouseDownHandler(this);
selections.addKeyDownHandler(this);
}
public HTML getOptionsCaption() {
if (optionsCaption == null) {
optionsCaption = new HTML();
optionsCaption.setStyleName(CLASSNAME + "-options-caption");
optionsCaption.getElement().getStyle()
.setFloat(com.google.gwt.dom.client.Style.Float.LEFT);
captionWrapper.add(optionsCaption);
}
return optionsCaption;
}
public HTML getSelectionsCaption() {
if (selectionsCaption == null) {
selectionsCaption = new HTML();
selectionsCaption.setStyleName(CLASSNAME + "-selections-caption");
selectionsCaption.getElement().getStyle()
.setFloat(com.google.gwt.dom.client.Style.Float.RIGHT);
captionWrapper.add(selectionsCaption);
}
return selectionsCaption;
}
@Override
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Captions are updated before super call to ensure the widths are set
// correctly
updateCaptions(uidl);
super.updateFromUIDL(uidl, client);
// If the server request that a cached instance should be used, do
// nothing
// if (uidl.isCachedComponent()) {
if (uidl.getBooleanAttribute("cached")) {
// Cached update, nothing to do)
return;
}
}
private void updateCaptions(UIDL uidl) {
String leftCaption = (uidl.hasAttribute(ATTRIBUTE_LEFT_CAPTION) ? uidl
.getStringAttribute(ATTRIBUTE_LEFT_CAPTION) : null);
String rightCaption = (uidl.hasAttribute(ATTRIBUTE_RIGHT_CAPTION) ? uidl
.getStringAttribute(ATTRIBUTE_RIGHT_CAPTION) : null);
boolean hasCaptions = (leftCaption != null || rightCaption != null);
if (leftCaption == null) {
removeOptionsCaption();
} else {
getOptionsCaption().setText(leftCaption);
}
if (rightCaption == null) {
removeSelectionsCaption();
} else {
getSelectionsCaption().setText(rightCaption);
}
captionWrapper.setVisible(hasCaptions);
}
private void removeOptionsCaption() {
if (optionsCaption == null) {
return;
}
if (optionsCaption.getParent() != null) {
captionWrapper.remove(optionsCaption);
}
optionsCaption = null;
}
private void removeSelectionsCaption() {
if (selectionsCaption == null) {
return;
}
if (selectionsCaption.getParent() != null) {
captionWrapper.remove(selectionsCaption);
}
selectionsCaption = null;
}
@Override
protected void buildOptions(UIDL uidl) {
final boolean enabled = !isDisabled() && !isReadonly();
options.setMultipleSelect(isMultiselect());
selections.setMultipleSelect(isMultiselect());
options.setEnabled(enabled);
selections.setEnabled(enabled);
add.setEnabled(enabled);
remove.setEnabled(enabled);
options.clear();
selections.clear();
for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {
final UIDL optionUidl = (UIDL) i.next();
if (optionUidl.hasAttribute("selected")) {
selections.addItem(optionUidl.getStringAttribute("caption"),
optionUidl.getStringAttribute("key"));
} else {
options.addItem(optionUidl.getStringAttribute("caption"),
optionUidl.getStringAttribute("key"));
}
}
int cols = -1;
if (getColumns() > 0) {
cols = getColumns();
} else if (!widthSet) {
cols = DEFAULT_COLUMN_COUNT;
}
if (cols >= 0) {
String colWidth = cols + "em";
String containerWidth = (2 * cols + 4) + "em";
// Caption wrapper width == optionsSelect + buttons +
// selectionsSelect
String captionWrapperWidth = (2 * cols + 4 - 0.5) + "em";
options.setWidth(colWidth);
if (optionsCaption != null) {
optionsCaption.setWidth(colWidth);
}
selections.setWidth(colWidth);
if (selectionsCaption != null) {
selectionsCaption.setWidth(colWidth);
}
buttons.setWidth("3.5em");
optionsContainer.setWidth(containerWidth);
captionWrapper.setWidth(captionWrapperWidth);
}
if (getRows() > 0) {
options.setVisibleItemCount(getRows());
selections.setVisibleItemCount(getRows());
}
}
@Override
protected String[] getSelectedItems() {
final ArrayList<String> selectedItemKeys = new ArrayList<String>();
for (int i = 0; i < selections.getItemCount(); i++) {
selectedItemKeys.add(selections.getValue(i));
}
return selectedItemKeys.toArray(new String[selectedItemKeys.size()]);
}
private boolean[] getItemsToAdd() {
final boolean[] selectedIndexes = new boolean[options.getItemCount()];
for (int i = 0; i < options.getItemCount(); i++) {
if (options.isItemSelected(i)) {
selectedIndexes[i] = true;
} else {
selectedIndexes[i] = false;
}
}
return selectedIndexes;
}
private boolean[] getItemsToRemove() {
final boolean[] selectedIndexes = new boolean[selections.getItemCount()];
for (int i = 0; i < selections.getItemCount(); i++) {
if (selections.isItemSelected(i)) {
selectedIndexes[i] = true;
} else {
selectedIndexes[i] = false;
}
}
return selectedIndexes;
}
private void addItem() {
final boolean[] sel = getItemsToAdd();
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
final int optionIndex = i
- (sel.length - options.getItemCount());
selectedKeys.add(options.getValue(optionIndex));
// Move selection to another column
final String text = options.getItemText(optionIndex);
final String value = options.getValue(optionIndex);
selections.addItem(text, value);
selections.setItemSelected(selections.getItemCount() - 1, true);
options.removeItem(optionIndex);
if (options.getItemCount() > 0) {
options.setItemSelected(optionIndex > 0 ? optionIndex - 1
: 0, true);
}
}
}
// If no items are left move the focus to the selections
if (options.getItemCount() == 0) {
selections.setFocus(true);
} else {
options.setFocus(true);
}
client.updateVariable(id, "selected",
selectedKeys.toArray(new String[selectedKeys.size()]),
isImmediate());
}
private void removeItem() {
final boolean[] sel = getItemsToRemove();
for (int i = 0; i < sel.length; i++) {
if (sel[i]) {
final int selectionIndex = i
- (sel.length - selections.getItemCount());
selectedKeys.remove(selections.getValue(selectionIndex));
// Move selection to another column
final String text = selections.getItemText(selectionIndex);
final String value = selections.getValue(selectionIndex);
options.addItem(text, value);
options.setItemSelected(options.getItemCount() - 1, true);
selections.removeItem(selectionIndex);
if (selections.getItemCount() > 0) {
selections.setItemSelected(
selectionIndex > 0 ? selectionIndex - 1 : 0, true);
}
}
}
// If no items are left move the focus to the selections
if (selections.getItemCount() == 0) {
options.setFocus(true);
} else {
selections.setFocus(true);
}
client.updateVariable(id, "selected",
selectedKeys.toArray(new String[selectedKeys.size()]),
isImmediate());
}
@Override
public void onClick(ClickEvent event) {
super.onClick(event);
if (event.getSource() == add) {
addItem();
} else if (event.getSource() == remove) {
removeItem();
} else if (event.getSource() == options) {
// unselect all in other list, to avoid mistakes (i.e wrong button)
final int c = selections.getItemCount();
for (int i = 0; i < c; i++) {
selections.setItemSelected(i, false);
}
} else if (event.getSource() == selections) {
// unselect all in other list, to avoid mistakes (i.e wrong button)
final int c = options.getItemCount();
for (int i = 0; i < c; i++) {
options.setItemSelected(i, false);
}
}
}
@Override
public void setHeight(String height) {
super.setHeight(height);
if ("".equals(height)) {
options.setHeight("");
selections.setHeight("");
} else {
setInternalHeights();
}
}
private void setInternalHeights() {
int captionHeight = 0;
int totalHeight;
if (BrowserInfo.get().isIE6()) {
String o = getElement().getStyle().getOverflow();
getElement().getStyle().setOverflow(Overflow.HIDDEN);
totalHeight = getOffsetHeight();
getElement().getStyle().setProperty("overflow", o);
} else {
totalHeight = getOffsetHeight();
}
if (optionsCaption != null) {
captionHeight = Util.getRequiredHeight(optionsCaption);
} else if (selectionsCaption != null) {
captionHeight = Util.getRequiredHeight(selectionsCaption);
}
String selectHeight = (totalHeight - captionHeight) + "px";
selections.setHeight(selectHeight);
options.setHeight(selectHeight);
}
@Override
public void setWidth(String width) {
super.setWidth(width);
if (!"".equals(width) && width != null) {
setInternalWidths();
widthSet = true;
} else {
widthSet = false;
}
}
private void setInternalWidths() {
DOM.setStyleAttribute(getElement(), "position", "relative");
// TODO: Should really take borders/padding/margin into account.
// Compensating for now with a guess.
int buttonsExtraWidth = Util.measureHorizontalPaddingAndBorder(
buttons.getElement(), 0);
int buttonWidth = Util.getRequiredWidth(buttons) + +buttonsExtraWidth;
int totalWidth = getOffsetWidth();
int spaceForSelect = (totalWidth - buttonWidth) / 2;
options.setWidth(spaceForSelect + "px");
if (optionsCaption != null) {
optionsCaption.setWidth(spaceForSelect + "px");
}
selections.setWidth(spaceForSelect + "px");
if (selectionsCaption != null) {
selectionsCaption.setWidth(spaceForSelect + "px");
}
captionWrapper.setWidth("100%");
}
@Override
protected void setTabIndex(int tabIndex) {
options.setTabIndex(tabIndex);
selections.setTabIndex(tabIndex);
add.setTabIndex(tabIndex);
remove.setTabIndex(tabIndex);
}
public void focus() {
options.setFocus(true);
}
/**
* Get the key that selects an item in the table. By default it is the Enter
* key but by overriding this you can change the key to whatever you want.
*
* @return
*/
protected int getNavigationSelectKey() {
return KeyCodes.KEY_ENTER;
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
* .event.dom.client.KeyDownEvent)
*/
public void onKeyDown(KeyDownEvent event) {
int keycode = event.getNativeKeyCode();
// Catch tab and move between select:s
if (keycode == KeyCodes.KEY_TAB && event.getSource() == options) {
// Prevent default behavior
event.preventDefault();
// Remove current selections
for (int i = 0; i < options.getItemCount(); i++) {
options.setItemSelected(i, false);
}
// Focus selections
selections.setFocus(true);
}
if (keycode == KeyCodes.KEY_TAB && event.isShiftKeyDown()
&& event.getSource() == selections) {
// Prevent default behavior
event.preventDefault();
// Remove current selections
for (int i = 0; i < selections.getItemCount(); i++) {
selections.setItemSelected(i, false);
}
// Focus options
options.setFocus(true);
}
if (keycode == getNavigationSelectKey()) {
// Prevent default behavior
event.preventDefault();
// Decide which select the selection was made in
if (event.getSource() == options) {
// Prevents the selection to become a single selection when
// using Enter key
// as the selection key (default)
options.setFocus(false);
addItem();
} else if (event.getSource() == selections) {
// Prevents the selection to become a single selection when
// using Enter key
// as the selection key (default)
selections.setFocus(false);
removeItem();
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.MouseDownHandler#onMouseDown(com.google
* .gwt.event.dom.client.MouseDownEvent)
*/
public void onMouseDown(MouseDownEvent event) {
// Ensure that items are deselected when selecting
// from a different source. See #3699 for details.
if (event.getSource() == options) {
for (int i = 0; i < selections.getItemCount(); i++) {
selections.setItemSelected(i, false);
}
} else if (event.getSource() == selections) {
for (int i = 0; i < options.getItemCount(); i++) {
options.setItemSelected(i, false);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.DoubleClickHandler#onDoubleClick(com.
* google.gwt.event.dom.client.DoubleClickEvent)
*/
public void onDoubleClick(DoubleClickEvent event) {
if (event.getSource() == options) {
addItem();
options.setSelectedIndex(-1);
options.setFocus(false);
} else if (event.getSource() == selections) {
removeItem();
selections.setSelectedIndex(-1);
selections.setFocus(false);
}
}
private static final String SUBPART_OPTION_SELECT = "leftSelect";
private static final String SUBPART_SELECTION_SELECT = "rightSelect";
private static final String SUBPART_LEFT_CAPTION = "leftCaption";
private static final String SUBPART_RIGHT_CAPTION = "rightCaption";
private static final String SUBPART_ADD_BUTTON = "add";
private static final String SUBPART_REMOVE_BUTTON = "remove";
public Element getSubPartElement(String subPart) {
if (SUBPART_OPTION_SELECT.equals(subPart)) {
return options.getElement();
} else if (SUBPART_SELECTION_SELECT.equals(subPart)) {
return selections.getElement();
} else if (optionsCaption != null
&& SUBPART_LEFT_CAPTION.equals(subPart)) {
return optionsCaption.getElement();
} else if (selectionsCaption != null
&& SUBPART_RIGHT_CAPTION.equals(subPart)) {
return selectionsCaption.getElement();
} else if (SUBPART_ADD_BUTTON.equals(subPart)) {
return add.getElement();
} else if (SUBPART_REMOVE_BUTTON.equals(subPart)) {
return remove.getElement();
}
return null;
}
public String getSubPartName(Element subElement) {
if (optionsCaption != null
&& optionsCaption.getElement().isOrHasChild(subElement)) {
return SUBPART_LEFT_CAPTION;
} else if (selectionsCaption != null
&& selectionsCaption.getElement().isOrHasChild(subElement)) {
return SUBPART_RIGHT_CAPTION;
} else if (options.getElement().isOrHasChild(subElement)) {
return SUBPART_OPTION_SELECT;
} else if (selections.getElement().isOrHasChild(subElement)) {
return SUBPART_SELECTION_SELECT;
} else if (add.getElement().isOrHasChild(subElement)) {
return SUBPART_ADD_BUTTON;
} else if (remove.getElement().isOrHasChild(subElement)) {
return SUBPART_REMOVE_BUTTON;
}
return null;
}
}
| Fixed typo
svn changeset:16367/svn branch:6.5
| src/com/vaadin/terminal/gwt/client/ui/VTwinColSelect.java | Fixed typo | <ide><path>rc/com/vaadin/terminal/gwt/client/ui/VTwinColSelect.java
<ide> // Compensating for now with a guess.
<ide> int buttonsExtraWidth = Util.measureHorizontalPaddingAndBorder(
<ide> buttons.getElement(), 0);
<del> int buttonWidth = Util.getRequiredWidth(buttons) + +buttonsExtraWidth;
<add> int buttonWidth = Util.getRequiredWidth(buttons) + buttonsExtraWidth;
<ide> int totalWidth = getOffsetWidth();
<ide>
<ide> int spaceForSelect = (totalWidth - buttonWidth) / 2; |
|
Java | apache-2.0 | 1d4d23c194dec3302d70e2a9fa39c764a5e4ea9c | 0 | ronsigal/xerces,jimma/xerces,ronsigal/xerces,jimma/xerces,RackerWilliams/xercesj,jimma/xerces,ronsigal/xerces,RackerWilliams/xercesj,RackerWilliams/xercesj | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Sep 14, 2000:
// Fixed problem with namespace handling. Contributed by
// David Blondeau <[email protected]>
// Sep 14, 2000:
// Fixed serializer to report IO exception directly, instead at
// the end of document processing.
// Reported by Patrick Higgins <[email protected]>
// Aug 21, 2000:
// Fixed bug in startDocument not calling prepare.
// Reported by Mikael Staldal <[email protected]>
// Aug 21, 2000:
// Added ability to omit DOCTYPE declaration.
package org.apache.xml.serialize;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Enumeration;
import org.w3c.dom.*;
import org.xml.sax.DocumentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.AttributeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* Implements an XML serializer supporting both DOM and SAX pretty
* serializing. For usage instructions see {@link Serializer}.
* <p>
* If an output stream is used, the encoding is taken from the
* output format (defaults to <tt>UTF-8</tt>). If a writer is
* used, make sure the writer uses the same encoding (if applies)
* as specified in the output format.
* <p>
* The serializer supports both DOM and SAX. DOM serializing is done
* by calling {@link #serialize} and SAX serializing is done by firing
* SAX events and using the serializer as a document handler.
* <p>
* If an I/O exception occurs while serializing, the serializer
* will not throw an exception directly, but only throw it
* at the end of serializing (either DOM or SAX's {@link
* org.xml.sax.DocumentHandler#endDocument}.
* <p>
* For elements that are not specified as whitespace preserving,
* the serializer will potentially break long text lines at space
* boundaries, indent lines, and serialize elements on separate
* lines. Line terminators will be regarded as spaces, and
* spaces at beginning of line will be stripped.
*
*
* @version $Revision$ $Date$
* @author <a href="mailto:[email protected]">Assaf Arkin</a>
* @see Serializer
*/
public class XMLSerializer
extends BaseMarkupSerializer
{
/**
* Constructs a new serializer. The serializer cannot be used without
* calling {@link #setOutputCharStream} or {@link #setOutputByteStream}
* first.
*/
public XMLSerializer()
{
super( new OutputFormat( Method.XML, null, false ) );
}
/**
* Constructs a new serializer. The serializer cannot be used without
* calling {@link #setOutputCharStream} or {@link #setOutputByteStream}
* first.
*/
public XMLSerializer( OutputFormat format )
{
super( format != null ? format : new OutputFormat( Method.XML, null, false ) );
_format.setMethod( Method.XML );
}
/**
* Constructs a new serializer that writes to the specified writer
* using the specified output format. If <tt>format</tt> is null,
* will use a default output format.
*
* @param writer The writer to use
* @param format The output format to use, null for the default
*/
public XMLSerializer( Writer writer, OutputFormat format )
{
super( format != null ? format : new OutputFormat( Method.XML, null, false ) );
_format.setMethod( Method.XML );
setOutputCharStream( writer );
}
/**
* Constructs a new serializer that writes to the specified output
* stream using the specified output format. If <tt>format</tt>
* is null, will use a default output format.
*
* @param output The output stream to use
* @param format The output format to use, null for the default
*/
public XMLSerializer( OutputStream output, OutputFormat format )
{
super( format != null ? format : new OutputFormat( Method.XML, null, false ) );
_format.setMethod( Method.XML );
setOutputByteStream( output );
}
public void setOutputFormat( OutputFormat format )
{
super.setOutputFormat( format != null ? format : new OutputFormat( Method.XML, null, false ) );
}
//-----------------------------------------//
// SAX content handler serializing methods //
//-----------------------------------------//
public void startElement( String namespaceURI, String localName,
String rawName, Attributes attrs )
throws SAXException
{
int i;
boolean preserveSpace;
ElementState state;
String name;
String value;
boolean addNSAttr = false;
try {
if ( _printer == null )
throw new IllegalStateException( "SER002 No writer supplied for serializer" );
state = getElementState();
if ( isDocumentState() ) {
// If this is the root element handle it differently.
// If the first root element in the document, serialize
// the document's DOCTYPE. Space preserving defaults
// to that of the output format.
if ( ! _started )
startDocument( ( localName == null || localName.length() == 0 ) ? rawName : localName );
} else {
// For any other element, if first in parent, then
// close parent's opening tag and use the parnet's
// space preserving.
if ( state.empty )
_printer.printText( '>' );
// Must leave CData section first
if ( state.inCData )
{
_printer.printText( "]]>" );
state.inCData = false;
}
// Indent this element on a new line if the first
// content of the parent element or immediately
// following an element or a comment
if ( _indenting && ! state.preserveSpace &&
( state.empty || state.afterElement || state.afterComment) )
_printer.breakLine();
}
preserveSpace = state.preserveSpace;
//We remove the namespaces from the attributes list so that they will
//be in _prefixes
attrs = extractNamespaces(attrs);
// Do not change the current element state yet.
// This only happens in endElement().
if ( rawName == null || rawName.length() == 0 ) {
if ( localName == null )
throw new SAXException( "No rawName and localName is null" );
if ( namespaceURI != null && ! namespaceURI.equals( "" ) ) {
String prefix;
prefix = getPrefix( namespaceURI );
if ( prefix != null && prefix.length() > 0 )
rawName = prefix + ":" + localName;
else
rawName = localName;
} else
rawName = localName;
addNSAttr = true;
}
_printer.printText( '<' );
_printer.printText( rawName );
_printer.indent();
// For each attribute print it's name and value as one part,
// separated with a space so the element can be broken on
// multiple lines.
if ( attrs != null ) {
for ( i = 0 ; i < attrs.getLength() ; ++i ) {
_printer.printSpace();
name = attrs.getQName( i );
if ( name != null && name.length() == 0 ) {
String prefix;
String attrURI;
name = attrs.getLocalName( i );
attrURI = attrs.getURI( i );
if ( ( attrURI != null && attrURI.length() != 0 ) &&
( namespaceURI == null || namespaceURI.length() == 0 ||
! attrURI.equals( namespaceURI ) ) ) {
prefix = getPrefix( attrURI );
if ( prefix != null && prefix.length() > 0 )
name = prefix + ":" + name;
}
}
value = attrs.getValue( i );
if ( value == null )
value = "";
_printer.printText( name );
_printer.printText( "=\"" );
printEscaped( value );
_printer.printText( '"' );
// If the attribute xml:space exists, determine whether
// to preserve spaces in this and child nodes based on
// its value.
if ( name.equals( "xml:space" ) ) {
if ( value.equals( "preserve" ) )
preserveSpace = true;
else
preserveSpace = _format.getPreserveSpace();
}
}
}
if ( _prefixes != null ) {
Enumeration enum;
enum = _prefixes.keys();
while ( enum.hasMoreElements() ) {
_printer.printSpace();
value = (String) enum.nextElement();
name = (String) _prefixes.get( value );
if ( name.length() == 0 ) {
_printer.printText( "xmlns=\"" );
printEscaped( value );
_printer.printText( '"' );
} else {
_printer.printText( "xmlns:" );
_printer.printText( name );
_printer.printText( "=\"" );
printEscaped( value );
_printer.printText( '"' );
}
}
}
// Now it's time to enter a new element state
// with the tag name and space preserving.
// We still do not change the curent element state.
state = enterElementState( namespaceURI, localName, rawName, preserveSpace );
name = ( localName == null || localName.length() == 0 ) ? rawName : namespaceURI + "^" + localName;
state.doCData = _format.isCDataElement( name );
state.unescaped = _format.isNonEscapingElement( name );
} catch ( IOException except ) {
throw new SAXException( except );
}
}
public void endElement( String namespaceURI, String localName,
String rawName )
throws SAXException
{
try {
endElementIO( namespaceURI, localName, rawName );
} catch ( IOException except ) {
throw new SAXException( except );
}
}
public void endElementIO( String namespaceURI, String localName,
String rawName )
throws IOException
{
ElementState state;
// Works much like content() with additions for closing
// an element. Note the different checks for the closed
// element's state and the parent element's state.
_printer.unindent();
state = getElementState();
if ( state.empty ) {
_printer.printText( "/>" );
} else {
// Must leave CData section first
if ( state.inCData )
_printer.printText( "]]>" );
// This element is not empty and that last content was
// another element, so print a line break before that
// last element and this element's closing tag.
if ( _indenting && ! state.preserveSpace && (state.afterElement || state.afterComment) )
_printer.breakLine();
_printer.printText( "</" );
_printer.printText( state.rawName );
_printer.printText( '>' );
}
// Leave the element state and update that of the parent
// (if we're not root) to not empty and after element.
state = leaveElementState();
state.afterElement = true;
state.afterComment = false;
state.empty = false;
if ( isDocumentState() )
_printer.flush();
}
//------------------------------------------//
// SAX document handler serializing methods //
//------------------------------------------//
public void startElement( String tagName, AttributeList attrs )
throws SAXException
{
int i;
boolean preserveSpace;
ElementState state;
String name;
String value;
try {
if ( _printer == null )
throw new IllegalStateException( "SER002 No writer supplied for serializer" );
state = getElementState();
if ( isDocumentState() ) {
// If this is the root element handle it differently.
// If the first root element in the document, serialize
// the document's DOCTYPE. Space preserving defaults
// to that of the output format.
if ( ! _started )
startDocument( tagName );
} else {
// For any other element, if first in parent, then
// close parent's opening tag and use the parnet's
// space preserving.
if ( state.empty )
_printer.printText( '>' );
// Must leave CData section first
if ( state.inCData )
{
_printer.printText( "]]>" );
state.inCData = false;
}
// Indent this element on a new line if the first
// content of the parent element or immediately
// following an element.
if ( _indenting && ! state.preserveSpace &&
( state.empty || state.afterElement || state.afterComment) )
_printer.breakLine();
}
preserveSpace = state.preserveSpace;
// Do not change the current element state yet.
// This only happens in endElement().
_printer.printText( '<' );
_printer.printText( tagName );
_printer.indent();
// For each attribute print it's name and value as one part,
// separated with a space so the element can be broken on
// multiple lines.
if ( attrs != null ) {
for ( i = 0 ; i < attrs.getLength() ; ++i ) {
_printer.printSpace();
name = attrs.getName( i );
value = attrs.getValue( i );
if ( value != null ) {
_printer.printText( name );
_printer.printText( "=\"" );
printEscaped( value );
_printer.printText( '"' );
}
// If the attribute xml:space exists, determine whether
// to preserve spaces in this and child nodes based on
// its value.
if ( name.equals( "xml:space" ) ) {
if ( value.equals( "preserve" ) )
preserveSpace = true;
else
preserveSpace = _format.getPreserveSpace();
}
}
}
// Now it's time to enter a new element state
// with the tag name and space preserving.
// We still do not change the curent element state.
state = enterElementState( null, null, tagName, preserveSpace );
state.doCData = _format.isCDataElement( tagName );
state.unescaped = _format.isNonEscapingElement( tagName );
} catch ( IOException except ) {
throw new SAXException( except );
}
}
public void endElement( String tagName )
throws SAXException
{
endElement( null, null, tagName );
}
//------------------------------------------//
// Generic node serializing methods methods //
//------------------------------------------//
/**
* Called to serialize the document's DOCTYPE by the root element.
* The document type declaration must name the root element,
* but the root element is only known when that element is serialized,
* and not at the start of the document.
* <p>
* This method will check if it has not been called before ({@link #_started}),
* will serialize the document type declaration, and will serialize all
* pre-root comments and PIs that were accumulated in the document
* (see {@link #serializePreRoot}). Pre-root will be serialized even if
* this is not the first root element of the document.
*/
protected void startDocument( String rootTagName )
throws IOException
{
int i;
String dtd;
dtd = _printer.leaveDTD();
if ( ! _started ) {
if ( ! _format.getOmitXMLDeclaration() ) {
StringBuffer buffer;
// Serialize the document declaration appreaing at the head
// of very XML document (unless asked not to).
buffer = new StringBuffer( "<?xml version=\"" );
if ( _format.getVersion() != null )
buffer.append( _format.getVersion() );
else
buffer.append( "1.0" );
buffer.append( '"' );
if ( _format.getEncoding() != null ) {
buffer.append( " encoding=\"" );
buffer.append( _format.getEncoding() );
buffer.append( '"' );
}
if ( _format.getStandalone() && _docTypeSystemId == null &&
_docTypePublicId == null )
buffer.append( " standalone=\"yes\"" );
buffer.append( "?>" );
_printer.printText( buffer );
_printer.breakLine();
}
if ( ! _format.getOmitDocumentType() ) {
if ( _docTypeSystemId != null ) {
// System identifier must be specified to print DOCTYPE.
// If public identifier is specified print 'PUBLIC
// <public> <system>', if not, print 'SYSTEM <system>'.
_printer.printText( "<!DOCTYPE " );
_printer.printText( rootTagName );
if ( _docTypePublicId != null ) {
_printer.printText( " PUBLIC " );
printDoctypeURL( _docTypePublicId );
if ( _indenting ) {
_printer.breakLine();
for ( i = 0 ; i < 18 + rootTagName.length() ; ++i )
_printer.printText( " " );
} else
_printer.printText( " " );
printDoctypeURL( _docTypeSystemId );
}
else {
_printer.printText( " SYSTEM " );
printDoctypeURL( _docTypeSystemId );
}
// If we accumulated any DTD contents while printing.
// this would be the place to print it.
if ( dtd != null && dtd.length() > 0 ) {
_printer.printText( " [" );
printText( dtd, true, true );
_printer.printText( ']' );
}
_printer.printText( ">" );
_printer.breakLine();
} else if ( dtd != null && dtd.length() > 0 ) {
_printer.printText( "<!DOCTYPE " );
_printer.printText( rootTagName );
_printer.printText( " [" );
printText( dtd, true, true );
_printer.printText( "]>" );
_printer.breakLine();
}
}
}
_started = true;
// Always serialize these, even if not te first root element.
serializePreRoot();
}
/**
* Called to serialize a DOM element. Equivalent to calling {@link
* #startElement}, {@link #endElement} and serializing everything
* inbetween, but better optimized.
*/
protected void serializeElement( Element elem )
throws IOException
{
Attr attr;
NamedNodeMap attrMap;
int i;
Node child;
ElementState state;
boolean preserveSpace;
String name;
String value;
String tagName;
tagName = elem.getTagName();
state = getElementState();
if ( isDocumentState() ) {
// If this is the root element handle it differently.
// If the first root element in the document, serialize
// the document's DOCTYPE. Space preserving defaults
// to that of the output format.
if ( ! _started )
startDocument( tagName );
} else {
// For any other element, if first in parent, then
// close parent's opening tag and use the parnet's
// space preserving.
if ( state.empty )
_printer.printText( '>' );
// Must leave CData section first
if ( state.inCData )
{
_printer.printText( "]]>" );
state.inCData = false;
}
// Indent this element on a new line if the first
// content of the parent element or immediately
// following an element.
if ( _indenting && ! state.preserveSpace &&
( state.empty || state.afterElement || state.afterComment) )
_printer.breakLine();
}
preserveSpace = state.preserveSpace;
// Do not change the current element state yet.
// This only happens in endElement().
_printer.printText( '<' );
_printer.printText( tagName );
_printer.indent();
// Lookup the element's attribute, but only print specified
// attributes. (Unspecified attributes are derived from the DTD.
// For each attribute print it's name and value as one part,
// separated with a space so the element can be broken on
// multiple lines.
attrMap = elem.getAttributes();
if ( attrMap != null ) {
for ( i = 0 ; i < attrMap.getLength() ; ++i ) {
attr = (Attr) attrMap.item( i );
name = attr.getName();
value = attr.getValue();
if ( value == null )
value = "";
if ( attr.getSpecified() ) {
_printer.printSpace();
_printer.printText( name );
_printer.printText( "=\"" );
printEscaped( value );
_printer.printText( '"' );
}
// If the attribute xml:space exists, determine whether
// to preserve spaces in this and child nodes based on
// its value.
if ( name.equals( "xml:space" ) ) {
if ( value.equals( "preserve" ) )
preserveSpace = true;
else
preserveSpace = _format.getPreserveSpace();
}
}
}
// If element has children, then serialize them, otherwise
// serialize en empty tag.
if ( elem.hasChildNodes() ) {
// Enter an element state, and serialize the children
// one by one. Finally, end the element.
state = enterElementState( null, null, tagName, preserveSpace );
state.doCData = _format.isCDataElement( tagName );
state.unescaped = _format.isNonEscapingElement( tagName );
child = elem.getFirstChild();
while ( child != null ) {
serializeNode( child );
child = child.getNextSibling();
}
endElementIO( null, null, tagName );
} else {
_printer.unindent();
_printer.printText( "/>" );
// After element but parent element is no longer empty.
state.afterElement = true;
state.afterComment = false;
state.empty = false;
if ( isDocumentState() )
_printer.flush();
}
}
protected String getEntityRef( int ch )
{
// Encode special XML characters into the equivalent character references.
// These five are defined by default for all XML documents.
switch ( ch ) {
case '<':
return "lt";
case '>':
return "gt";
case '"':
return "quot";
case '\'':
return "apos";
case '&':
return "amp";
}
return null;
}
/** Retrieve and remove the namespaces declarations from the list of attributes.
*
*/
private Attributes extractNamespaces( Attributes attrs )
throws SAXException
{
AttributesImpl attrsOnly;
String rawName;
int i;
int indexColon;
String prefix;
int length;
length = attrs.getLength();
attrsOnly = new AttributesImpl( attrs );
for ( i = length - 1 ; i >= 0 ; --i ) {
rawName = attrsOnly.getQName( i );
//We have to exclude the namespaces declarations from the attributes
//Append only when the feature http://xml.org/sax/features/namespace-prefixes"
//is TRUE
if ( rawName.startsWith( "xmlns" ) ) {
indexColon = rawName.indexOf( ':' );
//is there a prefix
if ( indexColon != -1 && ( indexColon + 1 ) < rawName.length() )
prefix = rawName.substring( indexColon + 1 );
else
prefix = "";
startPrefixMapping( prefix, attrs.getValue( i ) );
//Remove it
attrsOnly.removeAttribute( i );
}
}
return attrsOnly;
}
}
| src/org/apache/xml/serialize/XMLSerializer.java | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Sep 14, 2000:
// Fixed problem with namespace handling. Contributed by
// David Blondeau <[email protected]>
// Sep 14, 2000:
// Fixed serializer to report IO exception directly, instead at
// the end of document processing.
// Reported by Patrick Higgins <[email protected]>
// Aug 21, 2000:
// Fixed bug in startDocument not calling prepare.
// Reported by Mikael Staldal <[email protected]>
// Aug 21, 2000:
// Added ability to omit DOCTYPE declaration.
package org.apache.xml.serialize;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Enumeration;
import org.w3c.dom.*;
import org.xml.sax.DocumentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.AttributeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* Implements an XML serializer supporting both DOM and SAX pretty
* serializing. For usage instructions see {@link Serializer}.
* <p>
* If an output stream is used, the encoding is taken from the
* output format (defaults to <tt>UTF-8</tt>). If a writer is
* used, make sure the writer uses the same encoding (if applies)
* as specified in the output format.
* <p>
* The serializer supports both DOM and SAX. DOM serializing is done
* by calling {@link #serialize} and SAX serializing is done by firing
* SAX events and using the serializer as a document handler.
* <p>
* If an I/O exception occurs while serializing, the serializer
* will not throw an exception directly, but only throw it
* at the end of serializing (either DOM or SAX's {@link
* org.xml.sax.DocumentHandler#endDocument}.
* <p>
* For elements that are not specified as whitespace preserving,
* the serializer will potentially break long text lines at space
* boundaries, indent lines, and serialize elements on separate
* lines. Line terminators will be regarded as spaces, and
* spaces at beginning of line will be stripped.
*
*
* @version $Revision$ $Date$
* @author <a href="mailto:[email protected]">Assaf Arkin</a>
* @see Serializer
*/
public final class XMLSerializer
extends BaseMarkupSerializer
{
/**
* Constructs a new serializer. The serializer cannot be used without
* calling {@link #setOutputCharStream} or {@link #setOutputByteStream}
* first.
*/
public XMLSerializer()
{
super( new OutputFormat( Method.XML, null, false ) );
}
/**
* Constructs a new serializer. The serializer cannot be used without
* calling {@link #setOutputCharStream} or {@link #setOutputByteStream}
* first.
*/
public XMLSerializer( OutputFormat format )
{
super( format != null ? format : new OutputFormat( Method.XML, null, false ) );
_format.setMethod( Method.XML );
}
/**
* Constructs a new serializer that writes to the specified writer
* using the specified output format. If <tt>format</tt> is null,
* will use a default output format.
*
* @param writer The writer to use
* @param format The output format to use, null for the default
*/
public XMLSerializer( Writer writer, OutputFormat format )
{
super( format != null ? format : new OutputFormat( Method.XML, null, false ) );
_format.setMethod( Method.XML );
setOutputCharStream( writer );
}
/**
* Constructs a new serializer that writes to the specified output
* stream using the specified output format. If <tt>format</tt>
* is null, will use a default output format.
*
* @param output The output stream to use
* @param format The output format to use, null for the default
*/
public XMLSerializer( OutputStream output, OutputFormat format )
{
super( format != null ? format : new OutputFormat( Method.XML, null, false ) );
_format.setMethod( Method.XML );
setOutputByteStream( output );
}
public void setOutputFormat( OutputFormat format )
{
super.setOutputFormat( format != null ? format : new OutputFormat( Method.XML, null, false ) );
}
//-----------------------------------------//
// SAX content handler serializing methods //
//-----------------------------------------//
public void startElement( String namespaceURI, String localName,
String rawName, Attributes attrs )
throws SAXException
{
int i;
boolean preserveSpace;
ElementState state;
String name;
String value;
boolean addNSAttr = false;
try {
if ( _printer == null )
throw new IllegalStateException( "SER002 No writer supplied for serializer" );
state = getElementState();
if ( isDocumentState() ) {
// If this is the root element handle it differently.
// If the first root element in the document, serialize
// the document's DOCTYPE. Space preserving defaults
// to that of the output format.
if ( ! _started )
startDocument( ( localName == null || localName.length() == 0 ) ? rawName : localName );
} else {
// For any other element, if first in parent, then
// close parent's opening tag and use the parnet's
// space preserving.
if ( state.empty )
_printer.printText( '>' );
// Must leave CData section first
if ( state.inCData )
{
_printer.printText( "]]>" );
state.inCData = false;
}
// Indent this element on a new line if the first
// content of the parent element or immediately
// following an element or a comment
if ( _indenting && ! state.preserveSpace &&
( state.empty || state.afterElement || state.afterComment) )
_printer.breakLine();
}
preserveSpace = state.preserveSpace;
//We remove the namespaces from the attributes list so that they will
//be in _prefixes
attrs = extractNamespaces(attrs);
// Do not change the current element state yet.
// This only happens in endElement().
if ( rawName == null || rawName.length() == 0 ) {
if ( localName == null )
throw new SAXException( "No rawName and localName is null" );
if ( namespaceURI != null && ! namespaceURI.equals( "" ) ) {
String prefix;
prefix = getPrefix( namespaceURI );
if ( prefix != null && prefix.length() > 0 )
rawName = prefix + ":" + localName;
else
rawName = localName;
} else
rawName = localName;
addNSAttr = true;
}
_printer.printText( '<' );
_printer.printText( rawName );
_printer.indent();
// For each attribute print it's name and value as one part,
// separated with a space so the element can be broken on
// multiple lines.
if ( attrs != null ) {
for ( i = 0 ; i < attrs.getLength() ; ++i ) {
_printer.printSpace();
name = attrs.getQName( i );
if ( name != null && name.length() == 0 ) {
String prefix;
String attrURI;
name = attrs.getLocalName( i );
attrURI = attrs.getURI( i );
if ( ( attrURI != null && attrURI.length() != 0 ) &&
( namespaceURI == null || namespaceURI.length() == 0 ||
! attrURI.equals( namespaceURI ) ) ) {
prefix = getPrefix( attrURI );
if ( prefix != null && prefix.length() > 0 )
name = prefix + ":" + name;
}
}
value = attrs.getValue( i );
if ( value == null )
value = "";
_printer.printText( name );
_printer.printText( "=\"" );
printEscaped( value );
_printer.printText( '"' );
// If the attribute xml:space exists, determine whether
// to preserve spaces in this and child nodes based on
// its value.
if ( name.equals( "xml:space" ) ) {
if ( value.equals( "preserve" ) )
preserveSpace = true;
else
preserveSpace = _format.getPreserveSpace();
}
}
}
if ( _prefixes != null ) {
Enumeration enum;
enum = _prefixes.keys();
while ( enum.hasMoreElements() ) {
_printer.printSpace();
value = (String) enum.nextElement();
name = (String) _prefixes.get( value );
if ( name.length() == 0 ) {
_printer.printText( "xmlns=\"" );
printEscaped( value );
_printer.printText( '"' );
} else {
_printer.printText( "xmlns:" );
_printer.printText( name );
_printer.printText( "=\"" );
printEscaped( value );
_printer.printText( '"' );
}
}
}
// Now it's time to enter a new element state
// with the tag name and space preserving.
// We still do not change the curent element state.
state = enterElementState( namespaceURI, localName, rawName, preserveSpace );
name = ( localName == null || localName.length() == 0 ) ? rawName : namespaceURI + "^" + localName;
state.doCData = _format.isCDataElement( name );
state.unescaped = _format.isNonEscapingElement( name );
} catch ( IOException except ) {
throw new SAXException( except );
}
}
public void endElement( String namespaceURI, String localName,
String rawName )
throws SAXException
{
try {
endElementIO( namespaceURI, localName, rawName );
} catch ( IOException except ) {
throw new SAXException( except );
}
}
public void endElementIO( String namespaceURI, String localName,
String rawName )
throws IOException
{
ElementState state;
// Works much like content() with additions for closing
// an element. Note the different checks for the closed
// element's state and the parent element's state.
_printer.unindent();
state = getElementState();
if ( state.empty ) {
_printer.printText( "/>" );
} else {
// Must leave CData section first
if ( state.inCData )
_printer.printText( "]]>" );
// This element is not empty and that last content was
// another element, so print a line break before that
// last element and this element's closing tag.
if ( _indenting && ! state.preserveSpace && (state.afterElement || state.afterComment) )
_printer.breakLine();
_printer.printText( "</" );
_printer.printText( state.rawName );
_printer.printText( '>' );
}
// Leave the element state and update that of the parent
// (if we're not root) to not empty and after element.
state = leaveElementState();
state.afterElement = true;
state.afterComment = false;
state.empty = false;
if ( isDocumentState() )
_printer.flush();
}
//------------------------------------------//
// SAX document handler serializing methods //
//------------------------------------------//
public void startElement( String tagName, AttributeList attrs )
throws SAXException
{
int i;
boolean preserveSpace;
ElementState state;
String name;
String value;
try {
if ( _printer == null )
throw new IllegalStateException( "SER002 No writer supplied for serializer" );
state = getElementState();
if ( isDocumentState() ) {
// If this is the root element handle it differently.
// If the first root element in the document, serialize
// the document's DOCTYPE. Space preserving defaults
// to that of the output format.
if ( ! _started )
startDocument( tagName );
} else {
// For any other element, if first in parent, then
// close parent's opening tag and use the parnet's
// space preserving.
if ( state.empty )
_printer.printText( '>' );
// Must leave CData section first
if ( state.inCData )
{
_printer.printText( "]]>" );
state.inCData = false;
}
// Indent this element on a new line if the first
// content of the parent element or immediately
// following an element.
if ( _indenting && ! state.preserveSpace &&
( state.empty || state.afterElement || state.afterComment) )
_printer.breakLine();
}
preserveSpace = state.preserveSpace;
// Do not change the current element state yet.
// This only happens in endElement().
_printer.printText( '<' );
_printer.printText( tagName );
_printer.indent();
// For each attribute print it's name and value as one part,
// separated with a space so the element can be broken on
// multiple lines.
if ( attrs != null ) {
for ( i = 0 ; i < attrs.getLength() ; ++i ) {
_printer.printSpace();
name = attrs.getName( i );
value = attrs.getValue( i );
if ( value != null ) {
_printer.printText( name );
_printer.printText( "=\"" );
printEscaped( value );
_printer.printText( '"' );
}
// If the attribute xml:space exists, determine whether
// to preserve spaces in this and child nodes based on
// its value.
if ( name.equals( "xml:space" ) ) {
if ( value.equals( "preserve" ) )
preserveSpace = true;
else
preserveSpace = _format.getPreserveSpace();
}
}
}
// Now it's time to enter a new element state
// with the tag name and space preserving.
// We still do not change the curent element state.
state = enterElementState( null, null, tagName, preserveSpace );
state.doCData = _format.isCDataElement( tagName );
state.unescaped = _format.isNonEscapingElement( tagName );
} catch ( IOException except ) {
throw new SAXException( except );
}
}
public void endElement( String tagName )
throws SAXException
{
endElement( null, null, tagName );
}
//------------------------------------------//
// Generic node serializing methods methods //
//------------------------------------------//
/**
* Called to serialize the document's DOCTYPE by the root element.
* The document type declaration must name the root element,
* but the root element is only known when that element is serialized,
* and not at the start of the document.
* <p>
* This method will check if it has not been called before ({@link #_started}),
* will serialize the document type declaration, and will serialize all
* pre-root comments and PIs that were accumulated in the document
* (see {@link #serializePreRoot}). Pre-root will be serialized even if
* this is not the first root element of the document.
*/
protected void startDocument( String rootTagName )
throws IOException
{
int i;
String dtd;
dtd = _printer.leaveDTD();
if ( ! _started ) {
if ( ! _format.getOmitXMLDeclaration() ) {
StringBuffer buffer;
// Serialize the document declaration appreaing at the head
// of very XML document (unless asked not to).
buffer = new StringBuffer( "<?xml version=\"" );
if ( _format.getVersion() != null )
buffer.append( _format.getVersion() );
else
buffer.append( "1.0" );
buffer.append( '"' );
if ( _format.getEncoding() != null ) {
buffer.append( " encoding=\"" );
buffer.append( _format.getEncoding() );
buffer.append( '"' );
}
if ( _format.getStandalone() && _docTypeSystemId == null &&
_docTypePublicId == null )
buffer.append( " standalone=\"yes\"" );
buffer.append( "?>" );
_printer.printText( buffer );
_printer.breakLine();
}
if ( ! _format.getOmitDocumentType() ) {
if ( _docTypeSystemId != null ) {
// System identifier must be specified to print DOCTYPE.
// If public identifier is specified print 'PUBLIC
// <public> <system>', if not, print 'SYSTEM <system>'.
_printer.printText( "<!DOCTYPE " );
_printer.printText( rootTagName );
if ( _docTypePublicId != null ) {
_printer.printText( " PUBLIC " );
printDoctypeURL( _docTypePublicId );
if ( _indenting ) {
_printer.breakLine();
for ( i = 0 ; i < 18 + rootTagName.length() ; ++i )
_printer.printText( " " );
} else
_printer.printText( " " );
printDoctypeURL( _docTypeSystemId );
}
else {
_printer.printText( " SYSTEM " );
printDoctypeURL( _docTypeSystemId );
}
// If we accumulated any DTD contents while printing.
// this would be the place to print it.
if ( dtd != null && dtd.length() > 0 ) {
_printer.printText( " [" );
printText( dtd, true, true );
_printer.printText( ']' );
}
_printer.printText( ">" );
_printer.breakLine();
} else if ( dtd != null && dtd.length() > 0 ) {
_printer.printText( "<!DOCTYPE " );
_printer.printText( rootTagName );
_printer.printText( " [" );
printText( dtd, true, true );
_printer.printText( "]>" );
_printer.breakLine();
}
}
}
_started = true;
// Always serialize these, even if not te first root element.
serializePreRoot();
}
/**
* Called to serialize a DOM element. Equivalent to calling {@link
* #startElement}, {@link #endElement} and serializing everything
* inbetween, but better optimized.
*/
protected void serializeElement( Element elem )
throws IOException
{
Attr attr;
NamedNodeMap attrMap;
int i;
Node child;
ElementState state;
boolean preserveSpace;
String name;
String value;
String tagName;
tagName = elem.getTagName();
state = getElementState();
if ( isDocumentState() ) {
// If this is the root element handle it differently.
// If the first root element in the document, serialize
// the document's DOCTYPE. Space preserving defaults
// to that of the output format.
if ( ! _started )
startDocument( tagName );
} else {
// For any other element, if first in parent, then
// close parent's opening tag and use the parnet's
// space preserving.
if ( state.empty )
_printer.printText( '>' );
// Must leave CData section first
if ( state.inCData )
{
_printer.printText( "]]>" );
state.inCData = false;
}
// Indent this element on a new line if the first
// content of the parent element or immediately
// following an element.
if ( _indenting && ! state.preserveSpace &&
( state.empty || state.afterElement || state.afterComment) )
_printer.breakLine();
}
preserveSpace = state.preserveSpace;
// Do not change the current element state yet.
// This only happens in endElement().
_printer.printText( '<' );
_printer.printText( tagName );
_printer.indent();
// Lookup the element's attribute, but only print specified
// attributes. (Unspecified attributes are derived from the DTD.
// For each attribute print it's name and value as one part,
// separated with a space so the element can be broken on
// multiple lines.
attrMap = elem.getAttributes();
if ( attrMap != null ) {
for ( i = 0 ; i < attrMap.getLength() ; ++i ) {
attr = (Attr) attrMap.item( i );
name = attr.getName();
value = attr.getValue();
if ( value == null )
value = "";
if ( attr.getSpecified() ) {
_printer.printSpace();
_printer.printText( name );
_printer.printText( "=\"" );
printEscaped( value );
_printer.printText( '"' );
}
// If the attribute xml:space exists, determine whether
// to preserve spaces in this and child nodes based on
// its value.
if ( name.equals( "xml:space" ) ) {
if ( value.equals( "preserve" ) )
preserveSpace = true;
else
preserveSpace = _format.getPreserveSpace();
}
}
}
// If element has children, then serialize them, otherwise
// serialize en empty tag.
if ( elem.hasChildNodes() ) {
// Enter an element state, and serialize the children
// one by one. Finally, end the element.
state = enterElementState( null, null, tagName, preserveSpace );
state.doCData = _format.isCDataElement( tagName );
state.unescaped = _format.isNonEscapingElement( tagName );
child = elem.getFirstChild();
while ( child != null ) {
serializeNode( child );
child = child.getNextSibling();
}
endElementIO( null, null, tagName );
} else {
_printer.unindent();
_printer.printText( "/>" );
// After element but parent element is no longer empty.
state.afterElement = true;
state.afterComment = false;
state.empty = false;
if ( isDocumentState() )
_printer.flush();
}
}
protected String getEntityRef( int ch )
{
// Encode special XML characters into the equivalent character references.
// These five are defined by default for all XML documents.
switch ( ch ) {
case '<':
return "lt";
case '>':
return "gt";
case '"':
return "quot";
case '\'':
return "apos";
case '&':
return "amp";
}
return null;
}
/** Retrieve and remove the namespaces declarations from the list of attributes.
*
*/
private Attributes extractNamespaces( Attributes attrs )
throws SAXException
{
AttributesImpl attrsOnly;
String rawName;
int i;
int indexColon;
String prefix;
int length;
length = attrs.getLength();
attrsOnly = new AttributesImpl( attrs );
for ( i = length - 1 ; i >= 0 ; --i ) {
rawName = attrsOnly.getQName( i );
//We have to exclude the namespaces declarations from the attributes
//Append only when the feature http://xml.org/sax/features/namespace-prefixes"
//is TRUE
if ( rawName.startsWith( "xmlns" ) ) {
indexColon = rawName.indexOf( ':' );
//is there a prefix
if ( indexColon != -1 && ( indexColon + 1 ) < rawName.length() )
prefix = rawName.substring( indexColon + 1 );
else
prefix = "";
startPrefixMapping( prefix, attrs.getValue( i ) );
//Remove it
attrsOnly.removeAttribute( i );
}
}
return attrsOnly;
}
}
| fix for bug #2010
git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@317226 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/xml/serialize/XMLSerializer.java | fix for bug #2010 | <ide><path>rc/org/apache/xml/serialize/XMLSerializer.java
<ide> * @author <a href="mailto:[email protected]">Assaf Arkin</a>
<ide> * @see Serializer
<ide> */
<del>public final class XMLSerializer
<add>public class XMLSerializer
<ide> extends BaseMarkupSerializer
<ide> {
<ide> |
|
JavaScript | apache-2.0 | 246a128be0e5e83a193dc73b8be1400867ceeca4 | 0 | dOpensource/dsiprouter,dOpensource/dsiprouter,dOpensource/dsiprouter,dOpensource/dsiprouter,dOpensource/dsiprouter | //Add EndpointGroup
function addEndpointGroup(action) {
// The default action is a POST (creating a new EndpointGroup)
if (action == undefined) {
action = "POST";
selector = "#add";
modal_body = $(selector + ' .modal-body');
url = "/api/v1/endpointgroups";
}
// Grab the Gateway Group ID if updating usinga PUT
else if (action == "PUT") {
selector = "#edit";
modal_body = $(selector + ' .modal-body');
gwgroupid = modal_body.find(".gwgroupid").val();
url = "/api/v1/endpointgroups/" + gwgroupid;
}
var requestPayload = new Object();
requestPayload.name = modal_body.find(".name").val();
requestPayload.calllimit = modal_body.find(".calllimit").val();
var auth = new Object();
if (action == "POST") {
if ($('input#ip.authtype').is(':checked')) {
auth.type = "ip";
}
else {
auth.type = "userpwd";
auth.pass = modal_body.find("#auth_password").val();
}
}
else if (action == "PUT") {
if ($('input#ip2.authtype').is(':checked')) {
auth.type = "ip";
}
else {
auth.type = "userpwd";
auth.pass = modal_body.find("#auth_password2").val();
}
}
auth.user = modal_body.find(".auth_username").val();
auth.domain = modal_body.find(".auth_domain").val();
requestPayload.auth = auth;
requestPayload.strip = modal_body.find(".strip").val();
requestPayload.prefix = modal_body.find(".prefix").val();
notifications = {};
notifications.overmaxcalllimit = modal_body.find(".email_over_max_calls").val();
notifications.endpointfailure = modal_body.find(".email_endpoint_failure").val();
requestPayload.notifications = notifications;
cdr = {};
cdr.cdr_email = modal_body.find(".cdr_email").val();
cdr.cdr_send_date = modal_body.find(".cdr_send_date").val();
requestPayload.cdr = cdr
fusionpbx = {};
fusionpbx.enabled = modal_body.find(".fusionpbx_db_enabled").val();
fusionpbx.dbhost = modal_body.find(".fusionpbx_db_server").val();
fusionpbx.dbuser = modal_body.find(".fusionpbx_db_username").val();
fusionpbx.dbpass = modal_body.find(".fusionpbx_db_password").val();
requestPayload.fusionpbx = fusionpbx;
/* Process endpoints */
endpoints = [];
$("tr.endpoint").each(function(i, row) {
endpoint = {};
endpoint.gwid = $(this).find('td').eq(0).text();
endpoint.hostname = $(this).find('td').eq(1).text();
endpoint.description = $(this).find('td').eq(2).text();
//endpoint.maintmode = $(this).find('td').eq(3).text();
endpoints.push(endpoint);
});
requestPayload.endpoints = endpoints;
// Put into JSON Message and send over
$.ajax({
type: action,
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
if (msg.status == 200) {
// Update the Add Button to say saved
if (action == "POST") {
var btn = $('#add .modal-footer').find('#addButton');
btn.removeClass("btn-primary");
}
else {
var btn = $('#edit .modal-footer').find('#updateButton');
btn.removeClass("btn-warning");
}
btn.addClass("btn-success");
btn.html("<span class='glyphicon glyphicon-check'></span>Saved!");
btn.attr("disabled", true);
//Uncheck the Checkbox
reloadkamrequired();
$('#endpointgroups').DataTable().ajax.reload();
}
else {
console.log("error during endpointgroup update");
}
},
data: JSON.stringify(requestPayload)
})
}
function updateEndpointGroup() {
addEndpointGroup("PUT");
}
function clearEndpointGroupModal(modal_selector) {
/** Clear out the modal */
var modal_body = $(modal_selector).find('.modal-body');
modal_body.find(".gwgroupid").val('');
modal_body.find(".name").val('');
modal_body.find(".ip_addr").val('');
modal_body.find(".strip").val('');
modal_body.find(".prefix").val('');
modal_body.find(".fusionpbx_db_server").val('');
modal_body.find(".fusionpbx_db_username").val('fusionpbx');
modal_body.find(".fusionpbx_db_password").val('');
modal_body.find(".authtype[value='ip']").trigger('click');
modal_body.find(".auth_username").val('');
modal_body.find(".auth_password").val('');
modal_body.find(".auth_domain").val('');
modal_body.find(".calllimit").val('');
modal_body.find(".email_over_max_calls").val('');
modal_body.find(".email_endpoint_failure").val('');
modal_body.find('.FusionPBXDomainOptions').addClass("hidden");
modal_body.find('.updateButton').attr("disabled", false);
// Clear out update button in add footer
var modal_footer = modal_body.find('.modal-footer');
modal_footer.find("#addButton").attr("disabled", false);
// Clear out update button in add footer
modal_footer.find("#updateButton").attr("disabled", false);
if (modal_selector == "#add") {
var btn = $('#add .modal-footer').find('#addButton');
btn.html("<span class='glyphicon glyphicon-ok-sign'></span>Add");
btn.removeClass("btn-success");
btn.addClass("btn-primary");
}
else {
var btn = $('#edit .modal-footer').find('#updateButton');
btn.html("<span class='glyphicon glyphicon-ok-sign'></span>Update");
}
btn.attr('disabled',false);
// Remove Endpont Rows
$("tr.endpoint").each(function(i, row) {
$(this).remove();
})
// Make the Auth tab the default
modal_body.find(".auth-tab").addClass("active");
// make sure userpwd options not shown
modal_body.find('.userpwd').addClass('hidden');
/* make sure ip_addr not disabled */
toggleElemDisabled(modal_body.find('.ip_addr'), false);
}
function displayEndpointGroup(msg) {
var modal_body = $('#edit .modal-body');
modal_body.find(".name").val(msg.name);
modal_body.find(".gwgroupid").val(msg.gwgroupid);
modal_body.find(".calllimit").val(msg.calllimit);
if (msg.auth.type == "ip") {
$('#ip2.authtype').prop('checked', true);
$("#userpwd_enabled2").addClass('hidden');
$("#userpwd_enabled").addClass('hidden');
}
else {
$('#userpwd2.authtype').prop('checked', true);
$("#userpwd_enabled2").removeClass('hidden');
$("#userpwd_enabled").removeClass('hidden');
}
modal_body.find(".auth_username").val(msg.auth.user);
modal_body.find("#auth_password2").val(msg.auth.pass);
modal_body.find("#auth_password").val(msg.auth.pass);
modal_body.find(".auth_domain").val(msg.auth.domain);
modal_body.find(".strip").val(msg.strip);
modal_body.find(".prefix").val(msg.prefix);
modal_body.find(".email_over_max_calls").val(msg.notifications.overmaxcalllimit);
modal_body.find(".email_endpoint_failure").val(msg.notifications.endpointfailure);
modal_body.find(".cdr_email").val(msg.cdr.cdr_email);
modal_body.find(".cdr_send_date").val(msg.cdr.cdr_send_date);
modal_body.find(".fusionpbx_db_enabled").val(msg.fusionpbx.enabled);
modal_body.find(".fusionpbx_db_server").val(msg.fusionpbx.dbhost);
modal_body.find(".fusionpbx_db_username").val(msg.fusionpbx.dbuser);
modal_body.find(".fusionpbx_db_password").val(msg.fusionpbx.dbpass);
/* reset the save button*/
updatebtn = $('#edit .modal-footer').find("#updateButton");
updatebtn.removeClass("btn-success");
updatebtn.addClass("btn-warning");
updatebtn.html("<span class='glyphicon glyphicon-ok-sign'></span>Update");
if (msg.endpoints) {
var table = $('#endpoint-table');
var body = $('#endpoint-tablebody');
for (endpoint in msg.endpoints) {
row = '<tr class="endpoint"><td name="gwid">' + msg.endpoints[endpoint].gwid + '</td>';
row += '<td name="hostname">' + msg.endpoints[endpoint].hostname + '</td>';
row += '<td name="description">' + msg.endpoints[endpoint].description + '</td></tr>';
table.append($(row));
}
table.data('Tabledit').reload();
}
if (msg.fusionpbx.enabled) {
modal_body.find(".toggleFusionPBXDomain").bootstrapToggle('on');
}
else {
modal_body.find(".toggleFusionPBXDomain").bootstrapToggle('off');
}
if (msg.auth.type == "userpwd") {
/* userpwd auth enabled, Set the radio button to true */
modal_body.find('.authtype[data-toggle="userpwd_enabled"]').trigger('click');
}
else {
/* ip auth enabled, Set the radio button to true */
modal_body.find('.authtype[data-toggle="ip_enabled"]').trigger('click');
}
}
function deleteEndpointGroup() {
$.ajax({
type: "DELETE",
url: "/api/v1/endpointgroups/" + gwgroupid,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
reloadkamrequired();
}
});
$('#delete').modal('hide');
$('#edit').modal('hide');
$('#endpointgroups').DataTable().ajax.reload();
}
$(document).ready(function() {
// datatable init
$('#endpointgroups').DataTable({
"ajax": {
"url": "/api/v1/endpointgroups",
"dataSrc": "endpointgroups"
},
"columns": [
{"data": "name"},
{"data": "gwgroupid"}
//{ "data": "gwlist", visible: false },
],
"order": [[1, 'asc']]
});
// datepicker init
var date_input = $('input[name="cdr_send_date"]'); //our date input has the name "date"
var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";
date_input.datepicker({
format: 'mm/dd/yyyy',
container: 'cdr-toggle',
todayHighlight: true,
autoclose: true,
});
$('#endpointgroups tbody').on('click', 'tr', function() {
//Turn off selected on any other rows
$('#endpointgroups').find('tr').removeClass('selected');
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
//table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
gwgroupid = $(this).find('td').eq(1).text()
//console.log(gwgroupid);
$('#edit').modal('show');
}
});
$('#endpoint-table').Tabledit({
//url: 'example.php',
columns: {
identifier: [0, 'gwid'],
editable: [[1, 'hostname'], [2, 'description']],
saveButton: true,
},
onAlways: function() {
console.log("In Always");
$('.tabledit-deleted-row').each(function(index, element) {
$(this).remove();
});
}
});
$('#endpoint-table2').Tabledit({
//url: 'example.php',
columns: {
identifier: [0, 'gwid'],
editable: [[1, 'hostname'], [2, 'description']],
saveButton: true,
},
onAlways: function() {
console.log("In Always");
$('.tabledit-deleted-row').each(function(index, element) {
$(this).remove();
});
}
});
$('#edit').on('show.bs.modal', function() {
clearEndpointGroupModal('#edit');
// Show the auth tab by default when the modal shows
var modal_body = $('#edit .modal-body');
modal_body.find("[name='auth-toggle']").trigger('click');
// Put into JSON Message and send over
$.ajax({
type: "GET",
url: "/api/v1/endpointgroups/" + gwgroupid,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
displayEndpointGroup(msg)
}
})
});
$('#addEndpointRow').click(function() {
var table = $('#endpoint-table2');
var body = $('#endpoint-tablebody2');
//var nextId = body.find('tr').length + 1;
table.append($('<tr class="endpoint"><td name="gwid"></td><td name="hostname"></td><td name="description"></td></tr>'));
table.data('Tabledit').reload();
$("#endpoint-table2" + " tbody tr:last td:last .tabledit-edit-button").trigger("click");
});
$('#updateEndpointRow').click(function() {
var table = $('#endpoint-table');
var body = $('#endpoint-tablebody');
//var nextId = body.find('tr').length + 1;
table.append($('<tr class="endpoint"><td name="gwid"></td><td name="hostname"></td><td name="description"></td></tr>'));
table.data('Tabledit').reload();
$("#endpoint-table" + " tbody tr:last td:last .tabledit-edit-button").trigger("click");
});
$(".toggle-password").click(function() {
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
$(this).removeClass("glyphicon glyphicon-eye-close");
$(this).addClass("glyphicon glyphicon-eye-open");
}
else {
input.attr("type", "password");
$(this).removeClass("glyphicon glyphicon-eye-open");
$(this).addClass("glyphicon glyphicon-eye-close");
}
});
$("#authoptions :input").change(function() {
var userpwd_div = $('#userpwd_enabled');
var authpwd_inp = $("#auth_password");
var togglepwd_span = $(".toggle-password");
if ($('#ip').is(':checked')) {
userpwd_div.addClass('hidden');
}
else {
$.ajax({
type: "GET",
url: "/api/v1/sys/generatepassword",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
authpwd_inp.attr("type", "text");
authpwd_inp.val(msg.password)
togglepwd_span.removeClass("glyphicon glyphicon-eye-close");
togglepwd_span.addClass("glyphicon glyphicon-eye-open");
}
});
userpwd_div.removeClass('hidden');
}
});
$("#authoptions2 :input").change(function() {
var userpwd_div = $('#userpwd_enabled2');
if ($('#ip2').is(':checked')) {
userpwd_div.addClass('hidden');
}
else {
userpwd_div.removeClass('hidden');
}
});
$('#open-EndpointGroupsAdd').click(function() {
clearEndpointGroupModal('#add');
});
});
| gui/static/js/endpointgroups.js | //Add EndpointGroup
function addEndpointGroup(action) {
/** Get data from the modal */
var modal_body = $(selector + ' .modal-body');
// The default action is a POST (creating a new EndpointGroup)
if (action == undefined) {
action = "POST";
selector = "#add";
url = "/api/v1/endpointgroups";
}
// Grab the Gateway Group ID if updating usinga PUT
else if (action == "PUT") {
selector = "#edit";
gwgroupid = modal_body.find(".gwgroupid").val();
url = "/api/v1/endpointgroups/" + gwgroupid;
}
var requestPayload = new Object();
requestPayload.name = modal_body.find(".name").val();
requestPayload.calllimit = modal_body.find(".calllimit").val();
var auth = new Object();
if (action == "POST") {
if ($('input#ip.authtype').is(':checked')) {
auth.type = "ip";
}
else {
auth.type = "userpwd";
auth.pass = modal_body.find("#auth_password").val();
}
}
else if (action == "PUT") {
if ($('input#ip2.authtype').is(':checked')) {
auth.type = "ip";
}
else {
auth.type = "userpwd";
auth.pass = modal_body.find("#auth_password2").val();
}
}
auth.user = modal_body.find(".auth_username").val();
auth.domain = modal_body.find(".auth_domain").val();
requestPayload.auth = auth;
requestPayload.strip = modal_body.find(".strip").val();
requestPayload.prefix = modal_body.find(".prefix").val();
notifications = {};
notifications.overmaxcalllimit = modal_body.find(".email_over_max_calls").val();
notifications.endpointfailure = modal_body.find(".email_endpoint_failure").val();
requestPayload.notifications = notifications;
cdr = {};
cdr.cdr_email = modal_body.find(".cdr_email").val();
cdr.cdr_send_date = modal_body.find(".cdr_send_date").val();
requestPayload.cdr = cdr
fusionpbx = {};
fusionpbx.enabled = modal_body.find(".fusionpbx_db_enabled").val();
fusionpbx.dbhost = modal_body.find(".fusionpbx_db_server").val();
fusionpbx.dbuser = modal_body.find(".fusionpbx_db_username").val();
fusionpbx.dbpass = modal_body.find(".fusionpbx_db_password").val();
requestPayload.fusionpbx = fusionpbx;
/* Process endpoints */
endpoints = [];
$("tr.endpoint").each(function(i, row) {
endpoint = {};
endpoint.gwid = $(this).find('td').eq(0).text();
endpoint.hostname = $(this).find('td').eq(1).text();
endpoint.description = $(this).find('td').eq(2).text();
//endpoint.maintmode = $(this).find('td').eq(3).text();
endpoints.push(endpoint);
});
requestPayload.endpoints = endpoints;
// Put into JSON Message and send over
$.ajax({
type: action,
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
if (msg.status == 200) {
// Update the Add Button to say saved
if (action == "POST") {
var btn = $('#add .modal-footer').find('#addButton');
btn.removeClass("btn-primary");
}
else {
var btn = $('#edit .modal-footer').find('#updateButton');
btn.removeClass("btn-warning");
}
btn.addClass("btn-success");
btn.html("<span class='glyphicon glyphicon-check'></span>Saved!");
btn.attr("disabled", true);
//Uncheck the Checkbox
reloadkamrequired();
$('#endpointgroups').DataTable().ajax.reload();
}
else {
console.log("error during endpointgroup update");
}
},
data: JSON.stringify(requestPayload)
})
}
function updateEndpointGroup() {
addEndpointGroup("PUT");
}
function clearEndpointGroupModal(modal_selector) {
/** Clear out the modal */
var modal_body = $(modal_selector).find('.modal-body');
modal_body.find(".gwgroupid").val('');
modal_body.find(".name").val('');
modal_body.find(".ip_addr").val('');
modal_body.find(".strip").val('');
modal_body.find(".prefix").val('');
modal_body.find(".fusionpbx_db_server").val('');
modal_body.find(".fusionpbx_db_username").val('fusionpbx');
modal_body.find(".fusionpbx_db_password").val('');
modal_body.find(".authtype[value='ip']").trigger('click');
modal_body.find(".auth_username").val('');
modal_body.find(".auth_password").val('');
modal_body.find(".auth_domain").val('');
modal_body.find(".calllimit").val('');
modal_body.find(".email_over_max_calls").val('');
modal_body.find(".email_endpoint_failure").val('');
modal_body.find('.FusionPBXDomainOptions').addClass("hidden");
modal_body.find('.updateButton').attr("disabled", false);
// Clear out update button in add footer
var modal_footer = modal_body.find('.modal-footer');
modal_footer.find("#addButton").attr("disabled", false);
// Clear out update button in add footer
modal_footer.find("#updateButton").attr("disabled", false);
// Remove Endpont Rows
$("tr.endpoint").each(function(i, row) {
$(this).remove();
})
// Make the Auth tab the default
modal_body.find(".auth-tab").addClass("active");
// make sure userpwd options not shown
modal_body.find('.userpwd').addClass('hidden');
/* make sure ip_addr not disabled */
toggleElemDisabled(modal_body.find('.ip_addr'), false);
}
function displayEndpointGroup(msg) {
var modal_body = $('#edit .modal-body');
modal_body.find(".name").val(msg.name);
modal_body.find(".gwgroupid").val(msg.gwgroupid);
modal_body.find(".calllimit").val(msg.calllimit);
if (msg.auth.type == "ip") {
$('#ip2.authtype').prop('checked', true);
$("#userpwd_enabled2").addClass('hidden');
$("#userpwd_enabled").addClass('hidden');
}
else {
$('#userpwd2.authtype').prop('checked', true);
$("#userpwd_enabled2").removeClass('hidden');
$("#userpwd_enabled").removeClass('hidden');
}
modal_body.find(".auth_username").val(msg.auth.user);
modal_body.find("#auth_password2").val(msg.auth.pass);
modal_body.find("#auth_password").val(msg.auth.pass);
modal_body.find(".auth_domain").val(msg.auth.domain);
modal_body.find(".strip").val(msg.strip);
modal_body.find(".prefix").val(msg.prefix);
modal_body.find(".email_over_max_calls").val(msg.notifications.overmaxcalllimit);
modal_body.find(".email_endpoint_failure").val(msg.notifications.endpointfailure);
modal_body.find(".cdr_email").val(msg.cdr.cdr_email);
modal_body.find(".cdr_send_date").val(msg.cdr.cdr_send_date);
modal_body.find(".fusionpbx_db_enabled").val(msg.fusionpbx.enabled);
modal_body.find(".fusionpbx_db_server").val(msg.fusionpbx.dbhost);
modal_body.find(".fusionpbx_db_username").val(msg.fusionpbx.dbuser);
modal_body.find(".fusionpbx_db_password").val(msg.fusionpbx.dbpass);
/* reset the save button*/
updatebtn = $('#edit .modal-footer').find("#updateButton");
updatebtn.removeClass("btn-success");
updatebtn.addClass("btn-warning");
updatebtn.html("<span class='glyphicon glyphicon-ok-sign'></span>Update");
if (msg.endpoints) {
var table = $('#endpoint-table');
var body = $('#endpoint-tablebody');
for (endpoint in msg.endpoints) {
row = '<tr class="endpoint"><td name="gwid">' + msg.endpoints[endpoint].gwid + '</td>';
row += '<td name="hostname">' + msg.endpoints[endpoint].hostname + '</td>';
row += '<td name="description">' + msg.endpoints[endpoint].description + '</td></tr>';
table.append($(row));
}
table.data('Tabledit').reload();
}
if (msg.fusionpbx.enabled) {
modal_body.find(".toggleFusionPBXDomain").bootstrapToggle('on');
}
else {
modal_body.find(".toggleFusionPBXDomain").bootstrapToggle('off');
}
if (msg.auth.type == "userpwd") {
/* userpwd auth enabled, Set the radio button to true */
modal_body.find('.authtype[data-toggle="userpwd_enabled"]').trigger('click');
}
else {
/* ip auth enabled, Set the radio button to true */
modal_body.find('.authtype[data-toggle="ip_enabled"]').trigger('click');
}
}
function deleteEndpointGroup() {
$.ajax({
type: "DELETE",
url: "/api/v1/endpointgroups/" + gwgroupid,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
reloadkamrequired();
}
});
$('#delete').modal('hide');
$('#edit').modal('hide');
$('#endpointgroups').DataTable().ajax.reload();
}
$(document).ready(function() {
// datatable init
$('#endpointgroups').DataTable({
"ajax": {
"url": "/api/v1/endpointgroups",
"dataSrc": "endpointgroups"
},
"columns": [
{"data": "name"},
{"data": "gwgroupid"}
//{ "data": "gwlist", visible: false },
],
"order": [[1, 'asc']]
});
// datepicker init
var date_input = $('input[name="cdr_send_date"]'); //our date input has the name "date"
var container = $('.bootstrap-iso form').length > 0 ? $('.bootstrap-iso form').parent() : "body";
date_input.datepicker({
format: 'mm/dd/yyyy',
container: 'cdr-toggle',
todayHighlight: true,
autoclose: true,
});
$('#endpointgroups tbody').on('click', 'tr', function() {
//Turn off selected on any other rows
$('#endpointgroups').find('tr').removeClass('selected');
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
//table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
gwgroupid = $(this).find('td').eq(1).text()
//console.log(gwgroupid);
$('#edit').modal('show');
}
});
$('#endpoint-table').Tabledit({
//url: 'example.php',
columns: {
identifier: [0, 'gwid'],
editable: [[1, 'hostname'], [2, 'description']],
saveButton: true,
},
onAlways: function() {
console.log("In Always");
$('.tabledit-deleted-row').each(function(index, element) {
$(this).remove();
});
}
});
$('#endpoint-table2').Tabledit({
//url: 'example.php',
columns: {
identifier: [0, 'gwid'],
editable: [[1, 'hostname'], [2, 'description']],
saveButton: true,
},
onAlways: function() {
console.log("In Always");
$('.tabledit-deleted-row').each(function(index, element) {
$(this).remove();
});
}
});
$('#edit').on('show.bs.modal', function() {
clearEndpointGroupModal('#edit');
// Show the auth tab by default when the modal shows
var modal_body = $('#edit .modal-body');
modal_body.find("[name='auth-toggle']").trigger('click');
// Put into JSON Message and send over
$.ajax({
type: "GET",
url: "/api/v1/endpointgroups/" + gwgroupid,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
displayEndpointGroup(msg)
}
})
});
$('#addEndpointRow').click(function() {
var table = $('#endpoint-table2');
var body = $('#endpoint-tablebody2');
//var nextId = body.find('tr').length + 1;
table.append($('<tr class="endpoint"><td name="gwid"></td><td name="hostname"></td><td name="description"></td></tr>'));
table.data('Tabledit').reload();
$("#endpoint-table2" + " tbody tr:last td:last .tabledit-edit-button").trigger("click");
});
$('#updateEndpointRow').click(function() {
var table = $('#endpoint-table');
var body = $('#endpoint-tablebody');
//var nextId = body.find('tr').length + 1;
table.append($('<tr class="endpoint"><td name="gwid"></td><td name="hostname"></td><td name="description"></td></tr>'));
table.data('Tabledit').reload();
$("#endpoint-table" + " tbody tr:last td:last .tabledit-edit-button").trigger("click");
});
$(".toggle-password").click(function() {
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
$(this).removeClass("glyphicon glyphicon-eye-close");
$(this).addClass("glyphicon glyphicon-eye-open");
}
else {
input.attr("type", "password");
$(this).removeClass("glyphicon glyphicon-eye-open");
$(this).addClass("glyphicon glyphicon-eye-close");
}
});
$("#authoptions :input").change(function() {
var userpwd_div = $('#userpwd_enabled');
var authpwd_inp = $("#auth_password");
var togglepwd_span = $(".toggle-password");
if ($('#ip').is(':checked')) {
userpwd_div.addClass('hidden');
}
else {
$.ajax({
type: "GET",
url: "/api/v1/sys/generatepassword",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
authpwd_inp.attr("type", "text");
authpwd_inp.val(msg.password)
togglepwd_span.removeClass("glyphicon glyphicon-eye-close");
togglepwd_span.addClass("glyphicon glyphicon-eye-open");
}
});
userpwd_div.removeClass('hidden');
}
});
$("#authoptions2 :input").change(function() {
var userpwd_div = $('#userpwd_enabled2');
if ($('#ip2').is(':checked')) {
userpwd_div.addClass('hidden');
}
else {
userpwd_div.removeClass('hidden');
}
});
$('#open-EndpointGroupsAdd').click(function() {
clearEndpointGroupModal('#add');
});
});
| Fixed issue with endpointgroup regressions
| gui/static/js/endpointgroups.js | Fixed issue with endpointgroup regressions | <ide><path>ui/static/js/endpointgroups.js
<ide> //Add EndpointGroup
<ide> function addEndpointGroup(action) {
<ide>
<del> /** Get data from the modal */
<del> var modal_body = $(selector + ' .modal-body');
<ide>
<ide> // The default action is a POST (creating a new EndpointGroup)
<ide> if (action == undefined) {
<ide> action = "POST";
<ide> selector = "#add";
<add> modal_body = $(selector + ' .modal-body');
<ide> url = "/api/v1/endpointgroups";
<ide> }
<ide> // Grab the Gateway Group ID if updating usinga PUT
<ide> else if (action == "PUT") {
<ide> selector = "#edit";
<add> modal_body = $(selector + ' .modal-body');
<ide> gwgroupid = modal_body.find(".gwgroupid").val();
<ide> url = "/api/v1/endpointgroups/" + gwgroupid;
<ide> }
<ide>
<ide> // Clear out update button in add footer
<ide> modal_footer.find("#updateButton").attr("disabled", false);
<add>
<add> if (modal_selector == "#add") {
<add> var btn = $('#add .modal-footer').find('#addButton');
<add> btn.html("<span class='glyphicon glyphicon-ok-sign'></span>Add");
<add> btn.removeClass("btn-success");
<add> btn.addClass("btn-primary");
<add> }
<add> else {
<add> var btn = $('#edit .modal-footer').find('#updateButton');
<add> btn.html("<span class='glyphicon glyphicon-ok-sign'></span>Update");
<add> }
<add> btn.attr('disabled',false);
<add>
<ide>
<ide> // Remove Endpont Rows
<ide> $("tr.endpoint").each(function(i, row) { |
|
JavaScript | mit | 6125fedf574a2916c5c48bc711da86984ed13a6f | 0 | pshevtsov/dygraphs,cavorite/dygraphs,kbaggott/dygraphs,jmptrader/dygraphs,jmptrader/dygraphs,vhotspur/dygraphs,Akiyah/dygraphs,socib/dygraphs,Yong-Lee/dygraphs,pshevtsov/dygraphs,jmptrader/dygraphs,Akiyah/dygraphs,klausw/dygraphs,vhotspur/dygraphs,reinert/dygraphs,petechap/dygraphs,danvk/dygraphs,vhotspur/dygraphs,Yong-Lee/dygraphs,mcanthony/dygraphs,mariolll/dygraphs,petechap/dygraphs,timeu/dygraphs,pshevtsov/dygraphs,petechap/dygraphs,davidmsibley/dygraphs,vhotspur/dygraphs,grantadesign/dygraphs,witsa/dygraphs,jmptrader/dygraphs,grantadesign/dygraphs,Yong-Lee/dygraphs,reinert/dygraphs,vhotspur/dygraphs,socib/dygraphs,davidmsibley/dygraphs,panuhorsmalahti/dygraphs,klausw/dygraphs,grantadesign/dygraphs,danvk/dygraphs,danvk/dygraphs,timeu/dygraphs,panuhorsmalahti/dygraphs,Yong-Lee/dygraphs,Yong-Lee/dygraphs,pshevtsov/dygraphs,cavorite/dygraphs,grantadesign/dygraphs,Akiyah/dygraphs,panuhorsmalahti/dygraphs,mariolll/dygraphs,mantyr/dygraphs,danvk/dygraphs,reinert/dygraphs,panuhorsmalahti/dygraphs,mantyr/dygraphs,mcanthony/dygraphs,witsa/dygraphs,davidmsibley/dygraphs,cavorite/dygraphs,kbaggott/dygraphs,mariolll/dygraphs,grantadesign/dygraphs,davidmsibley/dygraphs,petechap/dygraphs,cavorite/dygraphs,mantyr/dygraphs,danvk/dygraphs,reinert/dygraphs,mariolll/dygraphs,kbaggott/dygraphs,mantyr/dygraphs,witsa/dygraphs,reinert/dygraphs,socib/dygraphs,witsa/dygraphs,davidmsibley/dygraphs,panuhorsmalahti/dygraphs,kbaggott/dygraphs,Akiyah/dygraphs,timeu/dygraphs,timeu/dygraphs,mcanthony/dygraphs,kbaggott/dygraphs,jmptrader/dygraphs,klausw/dygraphs,Akiyah/dygraphs,mcanthony/dygraphs,mcanthony/dygraphs,mantyr/dygraphs,pshevtsov/dygraphs,witsa/dygraphs,mariolll/dygraphs,socib/dygraphs,petechap/dygraphs,klausw/dygraphs,timeu/dygraphs,klausw/dygraphs | /**
* @license
* Copyright 2011 Robert Konigsberg ([email protected])
* MIT-licensed (http://opensource.org/licenses/MIT)
*/
/**
* @fileoverview The default interaction model for Dygraphs. This is kept out
* of dygraph.js for better navigability.
* @author Robert Konigsberg ([email protected])
*/
/*jshint globalstrict: true */
/*global Dygraph:false */
"use strict";
/**
* A collection of functions to facilitate build custom interaction models.
* @class
*/
Dygraph.Interaction = {};
/**
* Called in response to an interaction model operation that
* should start the default panning behavior.
*
* It's used in the default callback for "mousedown" operations.
* Custom interaction model builders can use it to provide the default
* panning behavior.
*
* @param { Event } event the event object which led to the startPan call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.startPan = function(event, g, context) {
var i, axis;
context.isPanning = true;
var xRange = g.xAxisRange();
context.dateRange = xRange[1] - xRange[0];
context.initialLeftmostDate = xRange[0];
context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1);
if (g.attr_("panEdgeFraction")) {
var maxXPixelsToDraw = g.width_ * g.attr_("panEdgeFraction");
var xExtremes = g.xAxisExtremes(); // I REALLY WANT TO CALL THIS xTremes!
var boundedLeftX = g.toDomXCoord(xExtremes[0]) - maxXPixelsToDraw;
var boundedRightX = g.toDomXCoord(xExtremes[1]) + maxXPixelsToDraw;
var boundedLeftDate = g.toDataXCoord(boundedLeftX);
var boundedRightDate = g.toDataXCoord(boundedRightX);
context.boundedDates = [boundedLeftDate, boundedRightDate];
var boundedValues = [];
var maxYPixelsToDraw = g.height_ * g.attr_("panEdgeFraction");
for (i = 0; i < g.axes_.length; i++) {
axis = g.axes_[i];
var yExtremes = axis.extremeRange;
var boundedTopY = g.toDomYCoord(yExtremes[0], i) + maxYPixelsToDraw;
var boundedBottomY = g.toDomYCoord(yExtremes[1], i) - maxYPixelsToDraw;
var boundedTopValue = g.toDataYCoord(boundedTopY);
var boundedBottomValue = g.toDataYCoord(boundedBottomY);
boundedValues[i] = [boundedTopValue, boundedBottomValue];
}
context.boundedValues = boundedValues;
}
// Record the range of each y-axis at the start of the drag.
// If any axis has a valueRange or valueWindow, then we want a 2D pan.
// We can't store data directly in g.axes_, because it does not belong to us
// and could change out from under us during a pan (say if there's a data
// update).
context.is2DPan = false;
context.axes = [];
for (i = 0; i < g.axes_.length; i++) {
axis = g.axes_[i];
var axis_data = {};
var yRange = g.yAxisRange(i);
// TODO(konigsberg): These values should be in |context|.
// In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
if (axis.logscale) {
axis_data.initialTopValue = Dygraph.log10(yRange[1]);
axis_data.dragValueRange = Dygraph.log10(yRange[1]) - Dygraph.log10(yRange[0]);
} else {
axis_data.initialTopValue = yRange[1];
axis_data.dragValueRange = yRange[1] - yRange[0];
}
axis_data.unitsPerPixel = axis_data.dragValueRange / (g.plotter_.area.h - 1);
context.axes.push(axis_data);
// While calculating axes, set 2dpan.
if (axis.valueWindow || axis.valueRange) context.is2DPan = true;
}
};
/**
* Called in response to an interaction model operation that
* responds to an event that pans the view.
*
* It's used in the default callback for "mousemove" operations.
* Custom interaction model builders can use it to provide the default
* panning behavior.
*
* @param { Event } event the event object which led to the movePan call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.movePan = function(event, g, context) {
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var minDate = context.initialLeftmostDate -
(context.dragEndX - context.dragStartX) * context.xUnitsPerPixel;
if (context.boundedDates) {
minDate = Math.max(minDate, context.boundedDates[0]);
}
var maxDate = minDate + context.dateRange;
if (context.boundedDates) {
if (maxDate > context.boundedDates[1]) {
// Adjust minDate, and recompute maxDate.
minDate = minDate - (maxDate - context.boundedDates[1]);
maxDate = minDate + context.dateRange;
}
}
g.dateWindow_ = [minDate, maxDate];
// y-axis scaling is automatic unless this is a full 2D pan.
if (context.is2DPan) {
// Adjust each axis appropriately.
for (var i = 0; i < g.axes_.length; i++) {
var axis = g.axes_[i];
var axis_data = context.axes[i];
var pixelsDragged = context.dragEndY - context.dragStartY;
var unitsDragged = pixelsDragged * axis_data.unitsPerPixel;
var boundedValue = context.boundedValues ? context.boundedValues[i] : null;
// In log scale, maxValue and minValue are the logs of those values.
var maxValue = axis_data.initialTopValue + unitsDragged;
if (boundedValue) {
maxValue = Math.min(maxValue, boundedValue[1]);
}
var minValue = maxValue - axis_data.dragValueRange;
if (boundedValue) {
if (minValue < boundedValue[0]) {
// Adjust maxValue, and recompute minValue.
maxValue = maxValue - (minValue - boundedValue[0]);
minValue = maxValue - axis_data.dragValueRange;
}
}
if (axis.logscale) {
axis.valueWindow = [ Math.pow(Dygraph.LOG_SCALE, minValue),
Math.pow(Dygraph.LOG_SCALE, maxValue) ];
} else {
axis.valueWindow = [ minValue, maxValue ];
}
}
}
g.drawGraph_(false);
};
/**
* Called in response to an interaction model operation that
* responds to an event that ends panning.
*
* It's used in the default callback for "mouseup" operations.
* Custom interaction model builders can use it to provide the default
* panning behavior.
*
* @param { Event } event the event object which led to the endPan call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.endPan = function(event, g, context) {
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
if (regionWidth < 2 && regionHeight < 2 &&
g.lastx_ !== undefined && g.lastx_ != -1) {
Dygraph.Interaction.treatMouseOpAsClick(g, event, context);
}
// TODO(konigsberg): mouseup should just delete the
// context object, and mousedown should create a new one.
context.isPanning = false;
context.is2DPan = false;
context.initialLeftmostDate = null;
context.dateRange = null;
context.valueRange = null;
context.boundedDates = null;
context.boundedValues = null;
context.axes = null;
};
/**
* Called in response to an interaction model operation that
* responds to an event that starts zooming.
*
* It's used in the default callback for "mousedown" operations.
* Custom interaction model builders can use it to provide the default
* zooming behavior.
*
* @param { Event } event the event object which led to the startZoom call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.startZoom = function(event, g, context) {
context.isZooming = true;
};
/**
* Called in response to an interaction model operation that
* responds to an event that defines zoom boundaries.
*
* It's used in the default callback for "mousemove" operations.
* Custom interaction model builders can use it to provide the default
* zooming behavior.
*
* @param { Event } event the event object which led to the moveZoom call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.moveZoom = function(event, g, context) {
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var xDelta = Math.abs(context.dragStartX - context.dragEndX);
var yDelta = Math.abs(context.dragStartY - context.dragEndY);
// drag direction threshold for y axis is twice as large as x axis
context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL;
g.drawZoomRect_(
context.dragDirection,
context.dragStartX,
context.dragEndX,
context.dragStartY,
context.dragEndY,
context.prevDragDirection,
context.prevEndX,
context.prevEndY);
context.prevEndX = context.dragEndX;
context.prevEndY = context.dragEndY;
context.prevDragDirection = context.dragDirection;
};
Dygraph.Interaction.treatMouseOpAsClick = function(g, event, context) {
var clickCallback = g.attr_('clickCallback');
var pointClickCallback = g.attr_('pointClickCallback');
var selectedPoint = null;
// Find out if the click occurs on a point. This only matters if there's a pointClickCallback.
if (pointClickCallback) {
var closestIdx = -1;
var closestDistance = Number.MAX_VALUE;
// check if the click was on a particular point.
for (var i = 0; i < g.selPoints_.length; i++) {
var p = g.selPoints_[i];
var distance = Math.pow(p.canvasx - context.dragEndX, 2) +
Math.pow(p.canvasy - context.dragEndY, 2);
if (!isNaN(distance) &&
(closestIdx == -1 || distance < closestDistance)) {
closestDistance = distance;
closestIdx = i;
}
}
// Allow any click within two pixels of the dot.
var radius = g.attr_('highlightCircleSize') + 2;
if (closestDistance <= radius * radius) {
selectedPoint = g.selPoints_[closestIdx];
}
}
if (selectedPoint) {
pointClickCallback(event, selectedPoint);
}
// TODO(danvk): pass along more info about the points, e.g. 'x'
if (clickCallback) {
clickCallback(event, g.lastx_, g.selPoints_);
}
};
/**
* Called in response to an interaction model operation that
* responds to an event that performs a zoom based on previously defined
* bounds..
*
* It's used in the default callback for "mouseup" operations.
* Custom interaction model builders can use it to provide the default
* zooming behavior.
*
* @param { Event } event the event object which led to the endZoom call.
* @param { Dygraph} g The dygraph on which to end the zoom.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.endZoom = function(event, g, context) {
context.isZooming = false;
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
if (regionWidth < 2 && regionHeight < 2 &&
g.lastx_ !== undefined && g.lastx_ != -1) {
Dygraph.Interaction.treatMouseOpAsClick(g, event, context);
}
if (regionWidth >= 10 && context.dragDirection == Dygraph.HORIZONTAL) {
g.doZoomX_(Math.min(context.dragStartX, context.dragEndX),
Math.max(context.dragStartX, context.dragEndX));
} else if (regionHeight >= 10 && context.dragDirection == Dygraph.VERTICAL) {
g.doZoomY_(Math.min(context.dragStartY, context.dragEndY),
Math.max(context.dragStartY, context.dragEndY));
} else {
g.clearZoomRect_();
}
context.dragStartX = null;
context.dragStartY = null;
};
/**
* @private
*/
Dygraph.Interaction.startTouch = function(event, g, context) {
event.preventDefault(); // touch browsers are all nice.
var touches = [];
for (var i = 0; i < event.touches.length; i++) {
var t = event.touches[i];
// we dispense with 'dragGetX_' because all touchBrowsers support pageX
touches.push({
pageX: t.pageX,
pageY: t.pageY,
dataX: g.toDataXCoord(t.pageX),
dataY: g.toDataYCoord(t.pageY)
// identifier: t.identifier
});
}
context.initialTouches = touches;
if (touches.length == 1) {
// This is just a swipe.
context.initialPinchCenter = touches[0];
context.touchDirections = { x: true, y: true };
} else if (touches.length == 2) {
// It's become a pinch!
// only screen coordinates can be averaged (data coords could be log scale).
context.initialPinchCenter = {
pageX: 0.5 * (touches[0].pageX + touches[1].pageX),
pageY: 0.5 * (touches[0].pageY + touches[1].pageY),
// TODO(danvk): remove
dataX: 0.5 * (touches[0].dataX + touches[1].dataX),
dataY: 0.5 * (touches[0].dataY + touches[1].dataY),
};
// Make pinches in a 45-degree swath around either axis 1-dimensional zooms.
var initialAngle = 180 / Math.PI * Math.atan2(
context.initialPinchCenter.pageY - touches[0].pageY,
touches[0].pageX - context.initialPinchCenter.pageX);
// use symmetry to get it into the first quadrant.
initialAngle = Math.abs(initialAngle);
if (initialAngle > 90) initialAngle = 90 - initialAngle;
context.touchDirections = {
x: (initialAngle < (90 - 45/2)),
y: (initialAngle > 45/2)
};
}
// save the full x & y ranges.
context.initialRange = {
x: g.xAxisRange(),
y: g.yAxisRange()
};
};
/**
* @private
*/
Dygraph.Interaction.moveTouch = function(event, g, context) {
var touches = [];
for (var i = 0; i < event.touches.length; i++) {
var t = event.touches[i];
touches.push({
pageX: t.pageX,
pageY: t.pageY,
});
}
var initialTouches = context.initialTouches;
var c_now;
// old and new centers.
var c_init = context.initialPinchCenter;
if (touches.length == 1) {
c_now = touches[0];
} else {
c_now = {
pageX: 0.5 * (touches[0].pageX + touches[1].pageX),
pageY: 0.5 * (touches[0].pageY + touches[1].pageY)
};
}
// this is the "swipe" component
// we toss it out for now, but could use it in the future.
var swipe = {
pageX: c_now.pageX - c_init.pageX,
pageY: c_now.pageY - c_init.pageY,
};
var dataWidth = context.initialRange.x[1] - context.initialRange.x[0];
var dataHeight = context.initialRange.y[0] - context.initialRange.y[1];
swipe.dataX = (swipe.pageX / g.plotter_.area.w) * dataWidth;
swipe.dataY = (swipe.pageY / g.plotter_.area.h) * dataHeight;
var xScale, yScale;
// The residual bits are usually split into scale & rotate bits, but we split
// them into x-scale and y-scale bits.
if (touches.length == 1) {
xScale = 1.0;
yScale = 1.0;
} else if (touches.length == 2) {
var initHalfWidth = (initialTouches[1].pageX - c_init.pageX);
xScale = (touches[1].pageX - c_now.pageX) / initHalfWidth;
var initHalfHeight = (initialTouches[1].pageY - c_init.pageY);
yScale = (touches[1].pageY - c_now.pageY) / initHalfHeight;
}
// Clip scaling to [1/8, 8] to prevent too much blowup.
xScale = Math.min(8, Math.max(0.125, xScale));
yScale = Math.min(8, Math.max(0.125, yScale));
if (context.touchDirections.x) {
g.dateWindow_ = [
c_init.dataX - swipe.dataX + (context.initialRange.x[0] - c_init.dataX) / xScale,
c_init.dataX - swipe.dataX + (context.initialRange.x[1] - c_init.dataX) / xScale,
];
}
if (context.touchDirections.y) {
for (var i = 0; i < 1 /*g.axes_.length*/; i++) {
var axis = g.axes_[i];
if (axis.logscale) {
// TODO(danvk): implement
} else {
axis.valueWindow = [
c_init.dataY - swipe.dataY + (context.initialRange.y[0] - c_init.dataY) / yScale,
c_init.dataY - swipe.dataY + (context.initialRange.y[1] - c_init.dataY) / yScale,
];
}
}
}
g.drawGraph_(false);
};
/**
* @private
*/
Dygraph.Interaction.endTouch = function(event, g, context) {
if (event.touches.length != 0) {
// this is effectively a "reset"
Dygraph.Interaction.startTouch(event, g, context);
}
};
/**
* Default interation model for dygraphs. You can refer to specific elements of
* this when constructing your own interaction model, e.g.:
* g.updateOptions( {
* interactionModel: {
* mousedown: Dygraph.defaultInteractionModel.mousedown
* }
* } );
*/
Dygraph.Interaction.defaultModel = {
// Track the beginning of drag events
mousedown: function(event, g, context) {
context.initializeMouseDown(event, g, context);
if (event.altKey || event.shiftKey) {
Dygraph.startPan(event, g, context);
} else {
Dygraph.startZoom(event, g, context);
}
},
// Draw zoom rectangles when the mouse is down and the user moves around
mousemove: function(event, g, context) {
if (context.isZooming) {
Dygraph.moveZoom(event, g, context);
} else if (context.isPanning) {
Dygraph.movePan(event, g, context);
}
},
mouseup: function(event, g, context) {
if (context.isZooming) {
Dygraph.endZoom(event, g, context);
} else if (context.isPanning) {
Dygraph.endPan(event, g, context);
}
},
touchstart: function(event, g, context) {
Dygraph.Interaction.startTouch(event, g, context);
},
touchmove: function(event, g, context) {
Dygraph.Interaction.moveTouch(event, g, context);
},
touchend: function(event, g, context) {
Dygraph.Interaction.endTouch(event, g, context);
},
// Temporarily cancel the dragging event when the mouse leaves the graph
mouseout: function(event, g, context) {
if (context.isZooming) {
context.dragEndX = null;
context.dragEndY = null;
}
},
// Disable zooming out if panning.
dblclick: function(event, g, context) {
if (event.altKey || event.shiftKey) {
return;
}
// TODO(konigsberg): replace g.doUnzoom()_ with something that is
// friendlier to public use.
g.doUnzoom_();
}
};
Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.Interaction.defaultModel;
// old ways of accessing these methods/properties
Dygraph.defaultInteractionModel = Dygraph.Interaction.defaultModel;
Dygraph.endZoom = Dygraph.Interaction.endZoom;
Dygraph.moveZoom = Dygraph.Interaction.moveZoom;
Dygraph.startZoom = Dygraph.Interaction.startZoom;
Dygraph.endPan = Dygraph.Interaction.endPan;
Dygraph.movePan = Dygraph.Interaction.movePan;
Dygraph.startPan = Dygraph.Interaction.startPan;
Dygraph.Interaction.nonInteractiveModel_ = {
mousedown: function(event, g, context) {
context.initializeMouseDown(event, g, context);
},
mouseup: function(event, g, context) {
// TODO(danvk): this logic is repeated in Dygraph.Interaction.endZoom
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
if (regionWidth < 2 && regionHeight < 2 &&
g.lastx_ !== undefined && g.lastx_ != -1) {
Dygraph.Interaction.treatMouseOpAsClick(g, event, context);
}
}
};
// Default interaction model when using the range selector.
Dygraph.Interaction.dragIsPanInteractionModel = {
mousedown: function(event, g, context) {
context.initializeMouseDown(event, g, context);
Dygraph.startPan(event, g, context);
},
mousemove: function(event, g, context) {
if (context.isPanning) {
Dygraph.movePan(event, g, context);
}
},
mouseup: function(event, g, context) {
if (context.isPanning) {
Dygraph.endPan(event, g, context);
}
}
};
| dygraph-interaction-model.js | /**
* @license
* Copyright 2011 Robert Konigsberg ([email protected])
* MIT-licensed (http://opensource.org/licenses/MIT)
*/
/**
* @fileoverview The default interaction model for Dygraphs. This is kept out
* of dygraph.js for better navigability.
* @author Robert Konigsberg ([email protected])
*/
/*jshint globalstrict: true */
/*global Dygraph:false */
"use strict";
/**
* A collection of functions to facilitate build custom interaction models.
* @class
*/
Dygraph.Interaction = {};
/**
* Called in response to an interaction model operation that
* should start the default panning behavior.
*
* It's used in the default callback for "mousedown" operations.
* Custom interaction model builders can use it to provide the default
* panning behavior.
*
* @param { Event } event the event object which led to the startPan call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.startPan = function(event, g, context) {
var i, axis;
context.isPanning = true;
var xRange = g.xAxisRange();
context.dateRange = xRange[1] - xRange[0];
context.initialLeftmostDate = xRange[0];
context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1);
if (g.attr_("panEdgeFraction")) {
var maxXPixelsToDraw = g.width_ * g.attr_("panEdgeFraction");
var xExtremes = g.xAxisExtremes(); // I REALLY WANT TO CALL THIS xTremes!
var boundedLeftX = g.toDomXCoord(xExtremes[0]) - maxXPixelsToDraw;
var boundedRightX = g.toDomXCoord(xExtremes[1]) + maxXPixelsToDraw;
var boundedLeftDate = g.toDataXCoord(boundedLeftX);
var boundedRightDate = g.toDataXCoord(boundedRightX);
context.boundedDates = [boundedLeftDate, boundedRightDate];
var boundedValues = [];
var maxYPixelsToDraw = g.height_ * g.attr_("panEdgeFraction");
for (i = 0; i < g.axes_.length; i++) {
axis = g.axes_[i];
var yExtremes = axis.extremeRange;
var boundedTopY = g.toDomYCoord(yExtremes[0], i) + maxYPixelsToDraw;
var boundedBottomY = g.toDomYCoord(yExtremes[1], i) - maxYPixelsToDraw;
var boundedTopValue = g.toDataYCoord(boundedTopY);
var boundedBottomValue = g.toDataYCoord(boundedBottomY);
boundedValues[i] = [boundedTopValue, boundedBottomValue];
}
context.boundedValues = boundedValues;
}
// Record the range of each y-axis at the start of the drag.
// If any axis has a valueRange or valueWindow, then we want a 2D pan.
// We can't store data directly in g.axes_, because it does not belong to us
// and could change out from under us during a pan (say if there's a data
// update).
context.is2DPan = false;
context.axes = [];
for (i = 0; i < g.axes_.length; i++) {
axis = g.axes_[i];
var axis_data = {};
var yRange = g.yAxisRange(i);
// TODO(konigsberg): These values should be in |context|.
// In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
if (axis.logscale) {
axis_data.initialTopValue = Dygraph.log10(yRange[1]);
axis_data.dragValueRange = Dygraph.log10(yRange[1]) - Dygraph.log10(yRange[0]);
} else {
axis_data.initialTopValue = yRange[1];
axis_data.dragValueRange = yRange[1] - yRange[0];
}
axis_data.unitsPerPixel = axis_data.dragValueRange / (g.plotter_.area.h - 1);
context.axes.push(axis_data);
// While calculating axes, set 2dpan.
if (axis.valueWindow || axis.valueRange) context.is2DPan = true;
}
};
/**
* Called in response to an interaction model operation that
* responds to an event that pans the view.
*
* It's used in the default callback for "mousemove" operations.
* Custom interaction model builders can use it to provide the default
* panning behavior.
*
* @param { Event } event the event object which led to the movePan call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.movePan = function(event, g, context) {
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var minDate = context.initialLeftmostDate -
(context.dragEndX - context.dragStartX) * context.xUnitsPerPixel;
if (context.boundedDates) {
minDate = Math.max(minDate, context.boundedDates[0]);
}
var maxDate = minDate + context.dateRange;
if (context.boundedDates) {
if (maxDate > context.boundedDates[1]) {
// Adjust minDate, and recompute maxDate.
minDate = minDate - (maxDate - context.boundedDates[1]);
maxDate = minDate + context.dateRange;
}
}
g.dateWindow_ = [minDate, maxDate];
// y-axis scaling is automatic unless this is a full 2D pan.
if (context.is2DPan) {
// Adjust each axis appropriately.
for (var i = 0; i < g.axes_.length; i++) {
var axis = g.axes_[i];
var axis_data = context.axes[i];
var pixelsDragged = context.dragEndY - context.dragStartY;
var unitsDragged = pixelsDragged * axis_data.unitsPerPixel;
var boundedValue = context.boundedValues ? context.boundedValues[i] : null;
// In log scale, maxValue and minValue are the logs of those values.
var maxValue = axis_data.initialTopValue + unitsDragged;
if (boundedValue) {
maxValue = Math.min(maxValue, boundedValue[1]);
}
var minValue = maxValue - axis_data.dragValueRange;
if (boundedValue) {
if (minValue < boundedValue[0]) {
// Adjust maxValue, and recompute minValue.
maxValue = maxValue - (minValue - boundedValue[0]);
minValue = maxValue - axis_data.dragValueRange;
}
}
if (axis.logscale) {
axis.valueWindow = [ Math.pow(Dygraph.LOG_SCALE, minValue),
Math.pow(Dygraph.LOG_SCALE, maxValue) ];
} else {
axis.valueWindow = [ minValue, maxValue ];
}
}
}
g.drawGraph_(false);
};
/**
* Called in response to an interaction model operation that
* responds to an event that ends panning.
*
* It's used in the default callback for "mouseup" operations.
* Custom interaction model builders can use it to provide the default
* panning behavior.
*
* @param { Event } event the event object which led to the startZoom call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.endPan = function(event, g, context) {
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
if (regionWidth < 2 && regionHeight < 2 &&
g.lastx_ !== undefined && g.lastx_ != -1) {
Dygraph.Interaction.treatMouseOpAsClick(g, event, context);
}
// TODO(konigsberg): mouseup should just delete the
// context object, and mousedown should create a new one.
context.isPanning = false;
context.is2DPan = false;
context.initialLeftmostDate = null;
context.dateRange = null;
context.valueRange = null;
context.boundedDates = null;
context.boundedValues = null;
context.axes = null;
};
/**
* Called in response to an interaction model operation that
* responds to an event that starts zooming.
*
* It's used in the default callback for "mousedown" operations.
* Custom interaction model builders can use it to provide the default
* zooming behavior.
*
* @param { Event } event the event object which led to the startZoom call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.startZoom = function(event, g, context) {
context.isZooming = true;
};
/**
* Called in response to an interaction model operation that
* responds to an event that defines zoom boundaries.
*
* It's used in the default callback for "mousemove" operations.
* Custom interaction model builders can use it to provide the default
* zooming behavior.
*
* @param { Event } event the event object which led to the moveZoom call.
* @param { Dygraph} g The dygraph on which to act.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.moveZoom = function(event, g, context) {
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var xDelta = Math.abs(context.dragStartX - context.dragEndX);
var yDelta = Math.abs(context.dragStartY - context.dragEndY);
// drag direction threshold for y axis is twice as large as x axis
context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL;
g.drawZoomRect_(
context.dragDirection,
context.dragStartX,
context.dragEndX,
context.dragStartY,
context.dragEndY,
context.prevDragDirection,
context.prevEndX,
context.prevEndY);
context.prevEndX = context.dragEndX;
context.prevEndY = context.dragEndY;
context.prevDragDirection = context.dragDirection;
};
Dygraph.Interaction.treatMouseOpAsClick = function(g, event, context) {
var clickCallback = g.attr_('clickCallback');
var pointClickCallback = g.attr_('pointClickCallback');
var selectedPoint = null;
// Find out if the click occurs on a point. This only matters if there's a pointClickCallback.
if (pointClickCallback) {
var closestIdx = -1;
var closestDistance = Number.MAX_VALUE;
// check if the click was on a particular point.
for (var i = 0; i < g.selPoints_.length; i++) {
var p = g.selPoints_[i];
var distance = Math.pow(p.canvasx - context.dragEndX, 2) +
Math.pow(p.canvasy - context.dragEndY, 2);
if (!isNaN(distance) &&
(closestIdx == -1 || distance < closestDistance)) {
closestDistance = distance;
closestIdx = i;
}
}
// Allow any click within two pixels of the dot.
var radius = g.attr_('highlightCircleSize') + 2;
if (closestDistance <= radius * radius) {
selectedPoint = g.selPoints_[closestIdx];
}
}
if (selectedPoint) {
pointClickCallback(event, selectedPoint);
}
// TODO(danvk): pass along more info about the points, e.g. 'x'
if (clickCallback) {
clickCallback(event, g.lastx_, g.selPoints_);
}
};
/**
* Called in response to an interaction model operation that
* responds to an event that performs a zoom based on previously defined
* bounds..
*
* It's used in the default callback for "mouseup" operations.
* Custom interaction model builders can use it to provide the default
* zooming behavior.
*
* @param { Event } event the event object which led to the endZoom call.
* @param { Dygraph} g The dygraph on which to end the zoom.
* @param { Object} context The dragging context object (with
* dragStartX/dragStartY/etc. properties). This function modifies the context.
*/
Dygraph.Interaction.endZoom = function(event, g, context) {
context.isZooming = false;
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
if (regionWidth < 2 && regionHeight < 2 &&
g.lastx_ !== undefined && g.lastx_ != -1) {
Dygraph.Interaction.treatMouseOpAsClick(g, event, context);
}
if (regionWidth >= 10 && context.dragDirection == Dygraph.HORIZONTAL) {
g.doZoomX_(Math.min(context.dragStartX, context.dragEndX),
Math.max(context.dragStartX, context.dragEndX));
} else if (regionHeight >= 10 && context.dragDirection == Dygraph.VERTICAL) {
g.doZoomY_(Math.min(context.dragStartY, context.dragEndY),
Math.max(context.dragStartY, context.dragEndY));
} else {
g.clearZoomRect_();
}
context.dragStartX = null;
context.dragStartY = null;
};
/**
* Default interation model for dygraphs. You can refer to specific elements of
* this when constructing your own interaction model, e.g.:
* g.updateOptions( {
* interactionModel: {
* mousedown: Dygraph.defaultInteractionModel.mousedown
* }
* } );
*/
Dygraph.Interaction.defaultModel = {
// Track the beginning of drag events
mousedown: function(event, g, context) {
context.initializeMouseDown(event, g, context);
if (event.altKey || event.shiftKey) {
Dygraph.startPan(event, g, context);
} else {
Dygraph.startZoom(event, g, context);
}
},
// Draw zoom rectangles when the mouse is down and the user moves around
mousemove: function(event, g, context) {
if (context.isZooming) {
Dygraph.moveZoom(event, g, context);
} else if (context.isPanning) {
Dygraph.movePan(event, g, context);
}
},
mouseup: function(event, g, context) {
if (context.isZooming) {
Dygraph.endZoom(event, g, context);
} else if (context.isPanning) {
Dygraph.endPan(event, g, context);
}
},
// Temporarily cancel the dragging event when the mouse leaves the graph
mouseout: function(event, g, context) {
if (context.isZooming) {
context.dragEndX = null;
context.dragEndY = null;
}
},
// Disable zooming out if panning.
dblclick: function(event, g, context) {
if (event.altKey || event.shiftKey) {
return;
}
// TODO(konigsberg): replace g.doUnzoom()_ with something that is
// friendlier to public use.
g.doUnzoom_();
}
};
Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.Interaction.defaultModel;
// old ways of accessing these methods/properties
Dygraph.defaultInteractionModel = Dygraph.Interaction.defaultModel;
Dygraph.endZoom = Dygraph.Interaction.endZoom;
Dygraph.moveZoom = Dygraph.Interaction.moveZoom;
Dygraph.startZoom = Dygraph.Interaction.startZoom;
Dygraph.endPan = Dygraph.Interaction.endPan;
Dygraph.movePan = Dygraph.Interaction.movePan;
Dygraph.startPan = Dygraph.Interaction.startPan;
Dygraph.Interaction.nonInteractiveModel_ = {
mousedown: function(event, g, context) {
context.initializeMouseDown(event, g, context);
},
mouseup: function(event, g, context) {
// TODO(danvk): this logic is repeated in Dygraph.Interaction.endZoom
context.dragEndX = g.dragGetX_(event, context);
context.dragEndY = g.dragGetY_(event, context);
var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
if (regionWidth < 2 && regionHeight < 2 &&
g.lastx_ !== undefined && g.lastx_ != -1) {
Dygraph.Interaction.treatMouseOpAsClick(g, event, context);
}
}
};
// Default interaction model when using the range selector.
Dygraph.Interaction.dragIsPanInteractionModel = {
mousedown: function(event, g, context) {
context.initializeMouseDown(event, g, context);
Dygraph.startPan(event, g, context);
},
mousemove: function(event, g, context) {
if (context.isPanning) {
Dygraph.movePan(event, g, context);
}
},
mouseup: function(event, g, context) {
if (context.isPanning) {
Dygraph.endPan(event, g, context);
}
}
};
| Add support for touch gestures: swipe & pinch-to-zoom.
The interactions are a bit slow at the moment, but we can work on that.
| dygraph-interaction-model.js | Add support for touch gestures: swipe & pinch-to-zoom. | <ide><path>ygraph-interaction-model.js
<ide> * Custom interaction model builders can use it to provide the default
<ide> * panning behavior.
<ide> *
<del> * @param { Event } event the event object which led to the startZoom call.
<add> * @param { Event } event the event object which led to the endPan call.
<ide> * @param { Dygraph} g The dygraph on which to act.
<ide> * @param { Object} context The dragging context object (with
<ide> * dragStartX/dragStartY/etc. properties). This function modifies the context.
<ide> };
<ide>
<ide> /**
<add> * @private
<add> */
<add>Dygraph.Interaction.startTouch = function(event, g, context) {
<add> event.preventDefault(); // touch browsers are all nice.
<add> var touches = [];
<add> for (var i = 0; i < event.touches.length; i++) {
<add> var t = event.touches[i];
<add> // we dispense with 'dragGetX_' because all touchBrowsers support pageX
<add> touches.push({
<add> pageX: t.pageX,
<add> pageY: t.pageY,
<add> dataX: g.toDataXCoord(t.pageX),
<add> dataY: g.toDataYCoord(t.pageY)
<add> // identifier: t.identifier
<add> });
<add> }
<add> context.initialTouches = touches;
<add>
<add> if (touches.length == 1) {
<add> // This is just a swipe.
<add> context.initialPinchCenter = touches[0];
<add> context.touchDirections = { x: true, y: true };
<add> } else if (touches.length == 2) {
<add> // It's become a pinch!
<add>
<add> // only screen coordinates can be averaged (data coords could be log scale).
<add> context.initialPinchCenter = {
<add> pageX: 0.5 * (touches[0].pageX + touches[1].pageX),
<add> pageY: 0.5 * (touches[0].pageY + touches[1].pageY),
<add>
<add> // TODO(danvk): remove
<add> dataX: 0.5 * (touches[0].dataX + touches[1].dataX),
<add> dataY: 0.5 * (touches[0].dataY + touches[1].dataY),
<add> };
<add>
<add> // Make pinches in a 45-degree swath around either axis 1-dimensional zooms.
<add> var initialAngle = 180 / Math.PI * Math.atan2(
<add> context.initialPinchCenter.pageY - touches[0].pageY,
<add> touches[0].pageX - context.initialPinchCenter.pageX);
<add>
<add> // use symmetry to get it into the first quadrant.
<add> initialAngle = Math.abs(initialAngle);
<add> if (initialAngle > 90) initialAngle = 90 - initialAngle;
<add>
<add> context.touchDirections = {
<add> x: (initialAngle < (90 - 45/2)),
<add> y: (initialAngle > 45/2)
<add> };
<add> }
<add>
<add> // save the full x & y ranges.
<add> context.initialRange = {
<add> x: g.xAxisRange(),
<add> y: g.yAxisRange()
<add> };
<add>};
<add>
<add>/**
<add> * @private
<add> */
<add>Dygraph.Interaction.moveTouch = function(event, g, context) {
<add> var touches = [];
<add> for (var i = 0; i < event.touches.length; i++) {
<add> var t = event.touches[i];
<add> touches.push({
<add> pageX: t.pageX,
<add> pageY: t.pageY,
<add> });
<add> }
<add> var initialTouches = context.initialTouches;
<add>
<add> var c_now;
<add>
<add> // old and new centers.
<add> var c_init = context.initialPinchCenter;
<add> if (touches.length == 1) {
<add> c_now = touches[0];
<add> } else {
<add> c_now = {
<add> pageX: 0.5 * (touches[0].pageX + touches[1].pageX),
<add> pageY: 0.5 * (touches[0].pageY + touches[1].pageY)
<add> };
<add> }
<add>
<add> // this is the "swipe" component
<add> // we toss it out for now, but could use it in the future.
<add> var swipe = {
<add> pageX: c_now.pageX - c_init.pageX,
<add> pageY: c_now.pageY - c_init.pageY,
<add> };
<add> var dataWidth = context.initialRange.x[1] - context.initialRange.x[0];
<add> var dataHeight = context.initialRange.y[0] - context.initialRange.y[1];
<add> swipe.dataX = (swipe.pageX / g.plotter_.area.w) * dataWidth;
<add> swipe.dataY = (swipe.pageY / g.plotter_.area.h) * dataHeight;
<add> var xScale, yScale;
<add>
<add> // The residual bits are usually split into scale & rotate bits, but we split
<add> // them into x-scale and y-scale bits.
<add> if (touches.length == 1) {
<add> xScale = 1.0;
<add> yScale = 1.0;
<add> } else if (touches.length == 2) {
<add> var initHalfWidth = (initialTouches[1].pageX - c_init.pageX);
<add> xScale = (touches[1].pageX - c_now.pageX) / initHalfWidth;
<add>
<add> var initHalfHeight = (initialTouches[1].pageY - c_init.pageY);
<add> yScale = (touches[1].pageY - c_now.pageY) / initHalfHeight;
<add> }
<add>
<add> // Clip scaling to [1/8, 8] to prevent too much blowup.
<add> xScale = Math.min(8, Math.max(0.125, xScale));
<add> yScale = Math.min(8, Math.max(0.125, yScale));
<add>
<add> if (context.touchDirections.x) {
<add> g.dateWindow_ = [
<add> c_init.dataX - swipe.dataX + (context.initialRange.x[0] - c_init.dataX) / xScale,
<add> c_init.dataX - swipe.dataX + (context.initialRange.x[1] - c_init.dataX) / xScale,
<add> ];
<add> }
<add>
<add> if (context.touchDirections.y) {
<add> for (var i = 0; i < 1 /*g.axes_.length*/; i++) {
<add> var axis = g.axes_[i];
<add> if (axis.logscale) {
<add> // TODO(danvk): implement
<add> } else {
<add> axis.valueWindow = [
<add> c_init.dataY - swipe.dataY + (context.initialRange.y[0] - c_init.dataY) / yScale,
<add> c_init.dataY - swipe.dataY + (context.initialRange.y[1] - c_init.dataY) / yScale,
<add> ];
<add> }
<add> }
<add> }
<add>
<add> g.drawGraph_(false);
<add>};
<add>
<add>/**
<add> * @private
<add> */
<add>Dygraph.Interaction.endTouch = function(event, g, context) {
<add> if (event.touches.length != 0) {
<add> // this is effectively a "reset"
<add> Dygraph.Interaction.startTouch(event, g, context);
<add> }
<add>};
<add>
<add>/**
<ide> * Default interation model for dygraphs. You can refer to specific elements of
<ide> * this when constructing your own interaction model, e.g.:
<ide> * g.updateOptions( {
<ide> } else if (context.isPanning) {
<ide> Dygraph.endPan(event, g, context);
<ide> }
<add> },
<add>
<add> touchstart: function(event, g, context) {
<add> Dygraph.Interaction.startTouch(event, g, context);
<add> },
<add> touchmove: function(event, g, context) {
<add> Dygraph.Interaction.moveTouch(event, g, context);
<add> },
<add> touchend: function(event, g, context) {
<add> Dygraph.Interaction.endTouch(event, g, context);
<ide> },
<ide>
<ide> // Temporarily cancel the dragging event when the mouse leaves the graph |
|
Java | mit | 5d47d4591f38ab2e8da0fcc12c6230fd97177fdb | 0 | bjornenalfa/LudumDare32 | package ludumdare32mapeditor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;
public class LudumDare32MapEditor extends JFrame {
static TileSet tileSet = new TileSet("img/Spritesheet/cloudy.png", 16, 1);
World[] worlds = {World.loadFromFile(".//..//src//ludumdare32/levels//test.png", tileSet), World.loadFromFile(".//..//src//ludumdare32/levels//test2.png", tileSet)};
int selectedWorld = 0;
MapPanel mapPanel = new MapPanel(worlds, selectedWorld);
TilePanel tilePanel = new TilePanel();
JLabel label = new JLabel("");
public LudumDare32MapEditor() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
Logger.getLogger(LudumDare32MapEditor.class.getName()).log(Level.SEVERE, null, ex);
}
//Tile.loadTileSet("img/Spritesheet/cloudy.png", 16, 1);
//World.setTileSet(tileSet);
//World.loadFromFile("levels/test.jpg");
worlds[1].setOffset(700, 0);
setTitle("LudumDare32 Map Editor");
JButton button1 = new JButton("NEW");
button1.addActionListener(newIMG());
JButton button2 = new JButton("SAVE");
button2.addActionListener(save());
JButton button3 = new JButton("LOAD");
button2.addActionListener(load());
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
CheckBoxPanel checkBoxPanel = new CheckBoxPanel();
JPanel inPanel = new JPanel(new BorderLayout());
inPanel.setPreferredSize(new Dimension(1600, 20));
inPanel.add(buttonPanel, BorderLayout.WEST);
inPanel.add(label, BorderLayout.CENTER);
inPanel.add(checkBoxPanel, BorderLayout.EAST);
//JSplitPane tileCollisionPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tilePanel, );
//tileCollisionPane.setResizeWeight(0.75);
//tileCollisionPane.setOneTouchExpandable(true);
//tileCollisionPane.setContinuousLayout(true);
//tileCollisionPane.setDividerSize(6);
//JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mapPanel, tileCollisionPane);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mapPanel, tilePanel);
splitPane.setResizeWeight(0.75);
splitPane.setOneTouchExpandable(true);
splitPane.setContinuousLayout(true);
splitPane.setDividerSize(6);
JPanel toolPanel = new ToolPanel();
JPanel anotherPanel = new JPanel(new BorderLayout());
anotherPanel.add(toolPanel, BorderLayout.WEST);
anotherPanel.add(splitPane, BorderLayout.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add(anotherPanel, BorderLayout.CENTER);
panel.add(inPanel, BorderLayout.NORTH);
setContentPane(panel);
getContentPane().setPreferredSize(new Dimension(1600, 608));
setResizable(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private Action save() {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter pngFilter = new FileNameExtensionFilter("PNG", "png");
FileNameExtensionFilter jpegFilter = new FileNameExtensionFilter("JPEG", "jpeg");
chooser.setFileFilter(jpegFilter);
chooser.setFileFilter(pngFilter);
chooser.setCurrentDirectory(new File(".//..//src//ludumdare32/levels//"));
if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
String saveFormat = "";
File file = chooser.getSelectedFile();
if (chooser.getFileFilter() == pngFilter) {
if (!file.getAbsolutePath().toLowerCase().endsWith(".png")) {
file = new File(file.getAbsolutePath() + ".png");
}
saveFormat = "png";
} else if (chooser.getFileFilter() == jpegFilter) {
if (!file.getAbsolutePath().toLowerCase().endsWith(".jpeg")) {
file = new File(file.getAbsolutePath() + ".jpeg");
}
saveFormat = "jpeg";
}
try {
ImageIO.write(worlds[selectedWorld].getImage(), saveFormat, file);
} catch (IOException ex) {
System.out.println(ex);
}
System.out.println("Saving: " + file);
}
}
};
}
private Action load() {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(".//..//src//ludumdare32/levels//"));
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
double x = worlds[selectedWorld].xOffset;
double y = worlds[selectedWorld].yOffset;
worlds[selectedWorld] = World.loadFromImage(ImageIO.read(file), tileSet);
worlds[selectedWorld].setOffset(x, y);
repaint();
} catch (IOException ex) {
System.out.println(ex);
}
System.out.println("Loading: " + file);
}
}
};
}
private Action newIMG() {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
NumberFormat intOnly;
intOnly = NumberFormat.getIntegerInstance();
intOnly.setMaximumFractionDigits(0);
JFormattedTextField width = new JFormattedTextField(intOnly);
JFormattedTextField height =new JFormattedTextField(intOnly);
Object[] message = {
"Width: ", width,
"Height: ", height
};
if (JOptionPane.showConfirmDialog(null, message, "Input size", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
System.out.println(Integer.parseInt(width.getText()) + " " + Integer.parseInt(height.getText()));
} else {
}
}
};
}
public static void main(String[] args) {
new LudumDare32MapEditor();
}
}
| LudumDare32MapEditor/src/ludumdare32mapeditor/LudumDare32MapEditor.java | package ludumdare32mapeditor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;
public class LudumDare32MapEditor extends JFrame {
static TileSet tileSet = new TileSet("img/Spritesheet/cloudy.png", 16, 1);
World[] worlds = {World.loadFromFile(".//..//src//ludumdare32/levels//test.png", tileSet), World.loadFromFile(".//..//src//ludumdare32/levels//test2.png", tileSet)};
int selectedWorld = 0;
MapPanel mapPanel = new MapPanel(worlds, selectedWorld);
TilePanel tilePanel = new TilePanel();
JLabel label = new JLabel("");
public LudumDare32MapEditor() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
Logger.getLogger(LudumDare32MapEditor.class.getName()).log(Level.SEVERE, null, ex);
}
//Tile.loadTileSet("img/Spritesheet/cloudy.png", 16, 1);
//World.setTileSet(tileSet);
//World.loadFromFile("levels/test.jpg");
worlds[1].setOffset(700, 0);
setTitle("LudumDare32 Map Editor");
JButton button1 = new JButton("SAVE");
button1.addActionListener(save());
JButton button2 = new JButton("LOAD");
button2.addActionListener(load());
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.add(button1);
buttonPanel.add(button2);
CheckBoxPanel checkBoxPanel = new CheckBoxPanel();
JPanel inPanel = new JPanel(new BorderLayout());
inPanel.setPreferredSize(new Dimension(1600, 20));
inPanel.add(buttonPanel, BorderLayout.WEST);
inPanel.add(label, BorderLayout.CENTER);
inPanel.add(checkBoxPanel, BorderLayout.EAST);
//JSplitPane tileCollisionPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tilePanel, );
//tileCollisionPane.setResizeWeight(0.75);
//tileCollisionPane.setOneTouchExpandable(true);
//tileCollisionPane.setContinuousLayout(true);
//tileCollisionPane.setDividerSize(6);
//JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mapPanel, tileCollisionPane);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mapPanel, tilePanel);
splitPane.setResizeWeight(0.75);
splitPane.setOneTouchExpandable(true);
splitPane.setContinuousLayout(true);
splitPane.setDividerSize(6);
JPanel toolPanel = new ToolPanel();
JPanel anotherPanel = new JPanel(new BorderLayout());
anotherPanel.add(toolPanel, BorderLayout.WEST);
anotherPanel.add(splitPane, BorderLayout.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add(anotherPanel, BorderLayout.CENTER);
panel.add(inPanel, BorderLayout.NORTH);
setContentPane(panel);
getContentPane().setPreferredSize(new Dimension(1600, 608));
setResizable(true);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private Action save() {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter pngFilter = new FileNameExtensionFilter("PNG", "png");
FileNameExtensionFilter jpegFilter = new FileNameExtensionFilter("JPEG", "jpeg");
chooser.setFileFilter(jpegFilter);
chooser.setFileFilter(pngFilter);
chooser.setCurrentDirectory(new File(".//..//src//ludumdare32/levels//"));
if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
String saveFormat = "";
File file = chooser.getSelectedFile();
if (chooser.getFileFilter() == pngFilter) {
if (!file.getAbsolutePath().toLowerCase().endsWith(".png")) {
file = new File(file.getAbsolutePath() + ".png");
}
saveFormat = "png";
} else if (chooser.getFileFilter() == jpegFilter) {
if (!file.getAbsolutePath().toLowerCase().endsWith(".jpeg")) {
file = new File(file.getAbsolutePath() + ".jpeg");
}
saveFormat = "jpeg";
}
try {
ImageIO.write(worlds[selectedWorld].getImage(), saveFormat, file);
} catch (IOException ex) {
System.out.println(ex);
}
System.out.println("Saving: " + file);
}
}
};
}
private Action load() {
return new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(".//..//src//ludumdare32/levels//"));
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
double x = worlds[selectedWorld].xOffset;
double y = worlds[selectedWorld].yOffset;
worlds[selectedWorld] = World.loadFromImage(ImageIO.read(file), tileSet);
worlds[selectedWorld].setOffset(x, y);
repaint();
} catch (IOException ex) {
System.out.println(ex);
}
System.out.println("Loading: " + file);
}
}
};
}
public static void main(String[] args) {
new LudumDare32MapEditor();
}
}
| "NEW" BUTTON! :D WIP
| LudumDare32MapEditor/src/ludumdare32mapeditor/LudumDare32MapEditor.java | "NEW" BUTTON! :D WIP | <ide><path>udumDare32MapEditor/src/ludumdare32mapeditor/LudumDare32MapEditor.java
<ide> import java.awt.event.ActionEvent;
<ide> import java.io.File;
<ide> import java.io.IOException;
<add>import java.text.NumberFormat;
<ide> import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide> import javax.imageio.ImageIO;
<ide> import javax.swing.BoxLayout;
<ide> import javax.swing.JButton;
<ide> import javax.swing.JFileChooser;
<add>import javax.swing.JFormattedTextField;
<ide> import javax.swing.JFrame;
<ide> import javax.swing.JLabel;
<add>import javax.swing.JOptionPane;
<ide> import javax.swing.JPanel;
<ide> import javax.swing.JSplitPane;
<ide> import javax.swing.UIManager;
<ide>
<ide> setTitle("LudumDare32 Map Editor");
<ide>
<del> JButton button1 = new JButton("SAVE");
<del> button1.addActionListener(save());
<del> JButton button2 = new JButton("LOAD");
<add> JButton button1 = new JButton("NEW");
<add> button1.addActionListener(newIMG());
<add> JButton button2 = new JButton("SAVE");
<add> button2.addActionListener(save());
<add> JButton button3 = new JButton("LOAD");
<ide> button2.addActionListener(load());
<ide> JPanel buttonPanel = new JPanel();
<ide> buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
<ide> buttonPanel.add(button1);
<ide> buttonPanel.add(button2);
<add> buttonPanel.add(button3);
<ide>
<ide> CheckBoxPanel checkBoxPanel = new CheckBoxPanel();
<ide>
<ide> }
<ide> };
<ide> }
<add>
<add> private Action newIMG() {
<add> return new AbstractAction() {
<add> @Override
<add> public void actionPerformed(ActionEvent e) {
<add> NumberFormat intOnly;
<add> intOnly = NumberFormat.getIntegerInstance();
<add> intOnly.setMaximumFractionDigits(0);
<add> JFormattedTextField width = new JFormattedTextField(intOnly);
<add> JFormattedTextField height =new JFormattedTextField(intOnly);
<add> Object[] message = {
<add> "Width: ", width,
<add> "Height: ", height
<add> };
<add> if (JOptionPane.showConfirmDialog(null, message, "Input size", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
<add> System.out.println(Integer.parseInt(width.getText()) + " " + Integer.parseInt(height.getText()));
<add> } else {
<add>
<add> }
<add> }
<add> };
<add> }
<ide>
<ide> public static void main(String[] args) {
<ide> new LudumDare32MapEditor(); |
|
Java | mit | 29a83a4542929c41dc9b7307b00a18f4c238fc25 | 0 | bitcoin-solutions/multibit-hardware,martin-lizner/trezor-ssh-agent | package org.multibit.hd.hardware.core.fsm;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.eventbus.Subscribe;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicHierarchy;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.wallet.KeyChain;
import org.multibit.hd.hardware.core.HardwareWalletClient;
import org.multibit.hd.hardware.core.events.HardwareWalletEventType;
import org.multibit.hd.hardware.core.events.HardwareWalletEvents;
import org.multibit.hd.hardware.core.events.MessageEvent;
import org.multibit.hd.hardware.core.events.MessageEvents;
import org.multibit.hd.hardware.core.messages.Features;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* <p>State context to provide the following to hardware wallet finite state machine:</p>
* <ul>
* <li>Provision of state context and parameters</li>
* </ul>
*
* <p>The finite state machine (FSM) for the hardware wallet requires and tracks various
* input parameters from the user and from the external environment. This context provides
* a single location to store these values during state transitions.</p>
*
* @since 0.0.1
*
*/
public class HardwareWalletContext {
private static final Logger log = LoggerFactory.getLogger(HardwareWalletContext.class);
/**
* The hardware wallet client handling outgoing messages and generating low level
* message events
*/
private final HardwareWalletClient client;
/**
* The current state should start by assuming an attached device and progress from there
* to either detached or connected
*/
private HardwareWalletState currentState = HardwareWalletStates.newAttachedState();
/**
* We begin at the start
*/
private ContextUseCase currentUseCase = ContextUseCase.START;
/**
* Provide contextual information for the current wallet creation use case
*/
private Optional<CreateWalletSpecification> createWalletSpecification = Optional.absent();
/**
* Provide contextual information for the current wallet load use case
*/
private Optional<LoadWalletSpecification> loadWalletSpecification = Optional.absent();
/**
* Provide the features
*/
private Optional<Features> features = Optional.absent();
/**
* Provide the transaction forming the basis for the "sign transaction" use case
*/
private Optional<Transaction> transaction = Optional.absent();
/**
* Keep track of all the signatures for the "sign transaction" use case
*/
private Map<Integer, byte[]> signatures = Maps.newHashMap();
/**
* Keep track of any transaction serialization bytes coming back from the device
*/
private ByteArrayOutputStream serializedTx = new ByteArrayOutputStream();
/**
* A map keyed on TxInput index and the associated path to the receiving address on that input
* This is used during Trezor transaction signing for fast addressN lookup
*/
private Map<Integer, ImmutableList<ChildNumber>> receivingAddressPathMap;
/**
* A map keyed on TxOutput Address and the associated path to the change address on that output
* This is used during Trezor transaction signing for fast addressN lookup, removes the need
* to confirm a change address and ensures the transaction balance is correct on the display
*/
private Map<Address, ImmutableList<ChildNumber>> changeAddressPathMap;
/**
* Provide a list of child numbers defining the HD path required.
* In the case of an extended public key this will result in multiple calls to retrieve each parent
* due to hardening.
*
* The end result can be found in {@link #deterministicHierarchy}.
*/
private Optional<List<ChildNumber>> childNumbers = Optional.absent();
/**
* Provide a deterministic key representing the root node of the current HD path.
* As the child numbers are explored one by one this deterministic key maintains the chain
* of keys derived from the base 58 xpub.
*
* The end result can be found in {@link #deterministicHierarchy}.
*/
private Optional<DeterministicKey> deterministicKey = Optional.absent();
/**
* Provide a deterministic hierarchy containing all hardened extended public keys so that a
* watching wallet can be created
*/
private Optional<DeterministicHierarchy> deterministicHierarchy = Optional.absent();
/**
* Entropy returned from the Trezor (result of encryption of fixed text
*/
private Optional<byte[]> entropy = Optional.absent();
/**
* The time when the device was last wiped by MBHD
*/
private Optional<Date> lastWipeTime = Optional.absent();
/**
* @param client The hardware wallet client
*/
public HardwareWalletContext(HardwareWalletClient client) {
this.client = client;
// Ensure the service is subscribed to low level message events from the client
MessageEvents.subscribe(this);
// Verify the environment
if (!client.attach()) {
log.warn("Cannot start the service due to a failed environment.");
throw new IllegalStateException("Cannot start the service due to a failed environment.");
}
}
/**
* @return The wallet features (e.g. PIN required, label etc)
*/
public Optional<Features> getFeatures() {
return features;
}
public void setFeatures(Features features) {
this.features = Optional.fromNullable(features);
}
/**
* @return The transaction for the "sign transaction" use case
*/
public Optional<Transaction> getTransaction() {
return transaction;
}
/**
* @return The current hardware wallet state
*/
public HardwareWalletState getState() {
return currentState;
}
/**
* <p>Note: When adding this signature using the builder setScriptSig() you'll need to append the SIGHASH 0x01 byte</p>
*
* @return The map of ECDSA signatures provided by the device during "sign transaction" keyed on the input index
*/
public Map<Integer, byte[]> getSignatures() {
return signatures;
}
/**
* This value cannot be considered complete until the "SHOW_OPERATION_SUCCESSFUL" message has been received
* since it can be built up over several incoming messages
*
* @return The serialized transaction provided by the device during "sign transaction"
*/
public ByteArrayOutputStream getSerializedTx() {
return serializedTx;
}
/**
* <p>Reset all context state to ensure a fresh context</p>
*/
private void resetAll() {
createWalletSpecification = Optional.absent();
loadWalletSpecification = Optional.absent();
features = Optional.absent();
transaction = Optional.absent();
signatures = Maps.newHashMap();
serializedTx = new ByteArrayOutputStream();
receivingAddressPathMap = Maps.newHashMap();
changeAddressPathMap = Maps.newHashMap();
childNumbers = Optional.absent();
deterministicKey = Optional.absent();
deterministicHierarchy = Optional.absent();
entropy = Optional.absent();
}
/**
* <p>Reset all context state, excepting Features, to ensure a fresh context</p>
*/
private void resetAllButFeatures() {
Optional<Features> originalFeatures = this.features;
resetAll();
this.features = originalFeatures;
}
/**
* <p>Reset the context into a stopped state (the service will have to be stopped and a new one started)</p>
*/
public void resetToStopped() {
log.debug("Reset to 'stopped'");
// Clear relevant information
resetAllButFeatures();
// Issue a hard detach - we are done
client.hardDetach();
// Unsubscribe from events
MessageEvents.unsubscribe(this);
// Perform the state change
currentState = HardwareWalletStates.newStoppedState();
// Fire the high level event
HardwareWalletEvents.fireHardwareWalletEvent(HardwareWalletEventType.SHOW_DEVICE_STOPPED);
}
/**
* <p>Reset the context back to a failed state (retain device information but prevent further communication)</p>
*/
public void resetToFailed() {
log.debug("Reset to 'failed'");
// Clear relevant information
resetAllButFeatures();
// Perform the state change
currentState = HardwareWalletStates.newFailedState();
// Fire the high level event
HardwareWalletEvents.fireHardwareWalletEvent(HardwareWalletEventType.SHOW_DEVICE_FAILED);
}
/**
* <p>Reset the context back to a detached state (no device information)</p>
*/
public void resetToDetached() {
log.debug("Reset to 'detached'");
// Clear relevant information
resetAll();
// Perform the state change
currentState = HardwareWalletStates.newDetachedState();
// Fire the high level event
HardwareWalletEvents.fireHardwareWalletEvent(HardwareWalletEventType.SHOW_DEVICE_DETACHED);
}
/**
* <p>Reset the context back to an attached state (clear device information and transition to connected)</p>
*/
public void resetToAttached() {
log.debug("Reset to 'attached'");
// Clear relevant information
resetAll();
// Perform the state change
currentState = HardwareWalletStates.newAttachedState();
// No high level event for this state
}
/**
* <p>Reset the context back to a connected state (clear device information and transition to initialised)</p>
*/
public void resetToConnected() {
log.debug("Reset to 'connected'");
// Clear relevant information
resetAll();
// Perform the state change
currentState = HardwareWalletStates.newConnectedState();
// No high level event for this state
}
/**
* <p>Reset the context back to a disconnected state (device is attached but communication has not been established)</p>
*/
public void resetToDisconnected() {
log.debug("Reset to 'disconnected'");
// Clear relevant information
resetAll();
// Perform the state change
currentState = HardwareWalletStates.newDisconnectedState();
// No high level event for this state
}
/**
* <p>Reset the context back to the initialised state (standard awaiting state with features)</p>
*/
public void resetToInitialised() {
log.debug("Reset to 'initialised'");
// Clear relevant information
resetAllButFeatures();
// Perform the state change
currentState = HardwareWalletStates.newInitialisedState();
// Fire the high level event
HardwareWalletEvents.fireHardwareWalletEvent(HardwareWalletEventType.SHOW_DEVICE_READY, features.get());
}
/**
* @return The hardware wallet client
*/
public HardwareWalletClient getClient() {
return client;
}
/**
* @return The create wallet specification
*/
public Optional<CreateWalletSpecification> getCreateWalletSpecification() {
return createWalletSpecification;
}
/**
* @return The load wallet specification
*/
public Optional<LoadWalletSpecification> getLoadWalletSpecification() {
return loadWalletSpecification;
}
/**
* @return The map of paths for our receiving addresses on the current transaction (key input index, value deterministic path to receiving address)
*/
public Map<Integer, ImmutableList<ChildNumber>> getReceivingAddressPathMap() {
return receivingAddressPathMap;
}
/**
* @return The map of paths for the change address (key address, value deterministic path to change address)
*/
public Map<Address, ImmutableList<ChildNumber>> getChangeAddressPathMap() {
return changeAddressPathMap;
}
/**
* @return The list of child numbers representing a HD path for the current use case
*/
public Optional<List<ChildNumber>> getChildNumbers() {
return childNumbers;
}
/**
* @return The deterministic key derived from the xpub of the given child numbers for the current use case
*/
public Optional<DeterministicKey> getDeterministicKey() {
return deterministicKey;
}
public void setDeterministicKey(DeterministicKey deterministicKey) {
log.debug("Setting deterministic key to be {}", deterministicKey);
this.deterministicKey = Optional.fromNullable(deterministicKey);
}
/**
* @return The deterministic hierarchy based on the deterministic key for the current use case
*/
public Optional<DeterministicHierarchy> getDeterministicHierarchy() {
return deterministicHierarchy;
}
public void setDeterministicHierarchy(DeterministicHierarchy deterministicHierarchy) {
this.deterministicHierarchy = Optional.fromNullable(deterministicHierarchy);
}
/**
* @return The current use case
*/
public ContextUseCase getCurrentUseCase() {
return currentUseCase;
}
/**
* @param event The low level message event
*/
@Subscribe
public void onMessageEvent(MessageEvent event) {
log.debug("Received message event: '{}'.'{}'", event.getEventType().name(), event.getMessage());
// Perform a state transition as a result of this event
try {
currentState.transition(client, this, event);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets to "confirm reset" state
*/
public void setToConfirmResetState() {
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmResetState();
// Expect the specification to be in place
CreateWalletSpecification specification = createWalletSpecification.get();
// Issue starting message to elicit the event
client.resetDevice(
specification.getLanguage(),
specification.getLabel(),
specification.isDisplayRandom(),
specification.isPinProtection(),
specification.getStrength()
);
}
/**
* Sets to "confirm load" state
*/
public void setToConfirmLoadState() {
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmLoadState();
// Expect the specification to be in place
LoadWalletSpecification specification = loadWalletSpecification.get();
// Issue starting message to elicit the event
client.loadDevice(
specification.getLanguage(),
specification.getLabel(),
specification.getSeedPhrase(),
specification.getPin()
);
}
/**
* <p>Change or remove the device PIN.</p>
*
* @param remove True if an existing PIN should be removed
*/
public void beginChangePIN(boolean remove) {
log.debug("Begin 'change PIN' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.CHANGE_PIN;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmChangePINState();
// Issue starting message to elicit the event
client.changePIN(remove);
}
/**
* <p>Continue the "change PIN" use case with the provision of the current PIN</p>
*
* @param pin The PIN
*/
public void continueChangePIN_PIN(String pin) {
log.debug("Continue 'change PIN' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmChangePINState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Begin the "wipe device" use case</p>
*/
public void beginWipeDeviceUseCase() {
log.debug("Begin 'wipe device' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.WIPE_DEVICE;
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmWipeState();
// Issue starting message to elicit the event
client.wipeDevice();
}
/**
* <p>Begin the "get address" use case</p>
*
* @param account The plain account number (0 gives maximum compatibility)
* @param keyPurpose The key purpose (RECEIVE_FUNDS,CHANGE,REFUND,AUTHENTICATION etc)
* @param index The plain index of the required address
* @param showDisplay True if the device should display the same address to allow the user to verify no tampering has occurred (recommended).
*/
public void beginGetAddressUseCase(int account, KeyChain.KeyPurpose keyPurpose, int index, boolean showDisplay) {
log.debug("Begin 'get address' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.REQUEST_ADDRESS;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmGetAddressState();
// Issue starting message to elicit the event
client.getAddress(
account,
keyPurpose,
index,
showDisplay
);
}
/**
* <p>Begin the "get public key" use case</p>
*
* @param account The plain account number (0 gives maximum compatibility)
* @param keyPurpose The key purpose (RECEIVE_FUNDS,CHANGE,REFUND,AUTHENTICATION etc)
* @param index The plain index of the required address
*/
public void beginGetPublicKeyUseCase(int account, KeyChain.KeyPurpose keyPurpose, int index) {
log.debug("Begin 'get public key' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.REQUEST_PUBLIC_KEY;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmGetPublicKeyState();
// Issue starting message to elicit the event
client.getPublicKey(
account,
keyPurpose,
index
);
}
/**
* <p>Begin the "get deterministic hierarchy" use case</p>
*
* @param childNumbers The child numbers describing the required chain from the master node including hardening bits
*/
public void beginGetDeterministicHierarchyUseCase(List<ChildNumber> childNumbers) {
log.debug("Begin 'get deterministic hierarchy' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.REQUEST_DETERMINISTIC_HIERARCHY;
// Store the overall context parameters
this.childNumbers = Optional.of(childNumbers);
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmGetDeterministicHierarchyState();
// Issue starting message to elicit the event
// In this case we start with the master node (empty list) to enable building up a complete
// hierarchy in case of hardened child numbers that require private keys to create
client.getDeterministicHierarchy(Lists.<ChildNumber>newArrayList());
}
/**
* <p>Begin the "sign message key use case</p>
*
* @param account The plain account number (0 gives maximum compatibility)
* @param keyPurpose The key purpose (RECEIVE_FUNDS,CHANGE,REFUND,AUTHENTICATION etc)
* @param index The plain index of the required address
* @param message The message for signing
*/
public void beginSignMessageUseCase(
int account,
KeyChain.KeyPurpose keyPurpose,
int index,
byte[] message
) {
log.debug("Begin 'sign message' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.SIGN_MESSAGE;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmSignMessageState();
// Issue starting message to elicit the event
client.signMessage(
account,
keyPurpose,
index,
message
);
}
/**
* <p>Continue the "sign message" use case with the provision of the current PIN</p>
*
* @param pin The PIN
*/
public void continueSignMessage_PIN(String pin) {
log.debug("Continue 'sign message' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmSignMessageState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Begin the "cipher key" use case</p>
*
* @param account The plain account number (0 gives maximum compatibility)
* @param keyPurpose The key purpose (RECEIVE_FUNDS,CHANGE,REFUND,AUTHENTICATION etc)
* @param index The plain index of the required address
* @param key The cipher key (e.g. "Some text")
* @param keyValue The key value (e.g. "[16 bytes of random data]")
* @param isEncrypting True if encrypting
* @param askOnDecrypt True if device should ask on decrypting
* @param askOnEncrypt True if device should ask on encrypting
*/
public void beginCipherKeyUseCase(
int account,
KeyChain.KeyPurpose keyPurpose,
int index,
byte[] key,
byte[] keyValue,
boolean isEncrypting,
boolean askOnDecrypt,
boolean askOnEncrypt
) {
log.debug("Begin 'cipher key' use case");
// Track the use case
currentUseCase = ContextUseCase.REQUEST_CIPHER_KEY;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmCipherKeyState();
// Issue starting message to elicit the event
client.cipherKeyValue(
account,
keyPurpose,
index,
key,
keyValue,
isEncrypting,
askOnDecrypt,
askOnEncrypt
);
}
/**
* <p>Continue the "cipher key" use case with the provision of the current PIN</p>
*
* @param pin The PIN
*/
public void continueCipherKey_PIN(String pin) {
log.debug("Continue 'cipher key' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmCipherKeyState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Begin the "load wallet" use case</p>
*
* @param specification The specification describing the use of PIN, seed strength etc
*/
public void beginLoadWallet(LoadWalletSpecification specification) {
log.debug("Begin 'load wallet' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.LOAD_WALLET;
// Store the overall context parameters
this.loadWalletSpecification = Optional.fromNullable(specification);
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmWipeState();
// Issue starting message to elicit the event
client.wipeDevice();
}
/**
* <p>Continue the "load wallet" use case with the provision of a PIN (either first or second)</p>
*
* @param pin The PIN
*/
public void continueLoadWallet_PIN(String pin) {
log.debug("Continue 'create wallet on device' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmPINState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Begin the "create wallet on device" use case</p>
*
* @param specification The specification describing the use of PIN, seed strength etc
*/
public void beginCreateWallet(CreateWalletSpecification specification) {
log.debug("Begin 'create wallet on device' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.CREATE_WALLET;
// Store the overall context parameters
this.createWalletSpecification = Optional.fromNullable(specification);
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmWipeState();
// Issue starting message to elicit the event
client.wipeDevice();
}
/**
* <p>Continue the "create wallet on device" use case with the provision of a PIN (either first or second)</p>
*
* @param pin The PIN
*/
public void continueCreateWallet_PIN(String pin) {
log.debug("Continue 'create wallet on device' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmPINState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Continue the "create wallet on device" use case with the provision of entropy</p>
*
* @param entropy The 256 bits of entropy to include
*/
public void continueCreateWallet_Entropy(byte[] entropy) {
log.debug("Continue 'create wallet on device' use case (provide entropy)");
// Track the use case
currentUseCase = ContextUseCase.PROVIDE_ENTROPY;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmEntropyState();
// Issue starting message to elicit the event
client.entropyAck(entropy);
}
/**
* <p>Begin the "sign transaction" use case</p>
*
* @param transaction The transaction containing the inputs and outputs
* @param receivingAddressPathMap The map of paths for our receiving addresses
* @param changeAddressPathMap The map paths for our change address
*/
public void beginSignTxUseCase(Transaction transaction, Map<Integer, ImmutableList<ChildNumber>> receivingAddressPathMap, Map<Address, ImmutableList<ChildNumber>> changeAddressPathMap) {
log.debug("Begin 'sign transaction' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.SIGN_TX;
// Store the overall context parameters
this.transaction = Optional.of(transaction);
this.receivingAddressPathMap = receivingAddressPathMap;
this.changeAddressPathMap = changeAddressPathMap;
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmSignTxState();
// Issue starting message to elicit the event
client.signTx(transaction);
}
/**
* <p>Continue the "sign transaction" use case with the provision of the current PIN</p>
*
* @param pin The PIN
*/
public void continueSignTx_PIN(String pin) {
log.debug("Continue 'sign tx' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmSignTxState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
public Optional<byte[]> getEntropy() {
return entropy;
}
public void setEntropy(Optional<byte[]> entropy) {
this.entropy = entropy;
}
public Optional<Date> getLastWipeTime() {
return lastWipeTime;
}
public void setLastWipeTime(Optional<Date> lastWipeTime) {
this.lastWipeTime = lastWipeTime;
}
}
| core/src/main/java/org/multibit/hd/hardware/core/fsm/HardwareWalletContext.java | package org.multibit.hd.hardware.core.fsm;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.eventbus.Subscribe;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicHierarchy;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.wallet.KeyChain;
import org.multibit.hd.hardware.core.HardwareWalletClient;
import org.multibit.hd.hardware.core.events.HardwareWalletEventType;
import org.multibit.hd.hardware.core.events.HardwareWalletEvents;
import org.multibit.hd.hardware.core.events.MessageEvent;
import org.multibit.hd.hardware.core.events.MessageEvents;
import org.multibit.hd.hardware.core.messages.Features;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
/**
* <p>State context to provide the following to hardware wallet finite state machine:</p>
* <ul>
* <li>Provision of state context and parameters</li>
* </ul>
*
* <p>The finite state machine (FSM) for the hardware wallet requires and tracks various
* input parameters from the user and from the external environment. This context provides
* a single location to store these values during state transitions.</p>
*
* @since 0.0.1
*
*/
public class HardwareWalletContext {
private static final Logger log = LoggerFactory.getLogger(HardwareWalletContext.class);
/**
* The hardware wallet client handling outgoing messages and generating low level
* message events
*/
private final HardwareWalletClient client;
/**
* The current state should start by assuming an attached device and progress from there
* to either detached or connected
*/
private HardwareWalletState currentState = HardwareWalletStates.newAttachedState();
/**
* We begin at the start
*/
private ContextUseCase currentUseCase = ContextUseCase.START;
/**
* Provide contextual information for the current wallet creation use case
*/
private Optional<CreateWalletSpecification> createWalletSpecification = Optional.absent();
/**
* Provide contextual information for the current wallet load use case
*/
private Optional<LoadWalletSpecification> loadWalletSpecification = Optional.absent();
/**
* Provide the features
*/
private Optional<Features> features = Optional.absent();
/**
* Provide the transaction forming the basis for the "sign transaction" use case
*/
private Optional<Transaction> transaction = Optional.absent();
/**
* Keep track of all the signatures for the "sign transaction" use case
*/
private Map<Integer, byte[]> signatures = Maps.newHashMap();
/**
* Keep track of any transaction serialization bytes coming back from the device
*/
private ByteArrayOutputStream serializedTx = new ByteArrayOutputStream();
/**
* A map keyed on TxInput index and the associated path to the receiving address on that input
* This is used during Trezor transaction signing for fast addressN lookup
*/
private Map<Integer, ImmutableList<ChildNumber>> receivingAddressPathMap;
/**
* A map keyed on TxOutput Address and the associated path to the change address on that output
* This is used during Trezor transaction signing for fast addressN lookup, removes the need
* to confirm a change address and ensures the transaction balance is correct on the display
*/
private Map<Address, ImmutableList<ChildNumber>> changeAddressPathMap;
/**
* Provide a list of child numbers defining the HD path required.
* In the case of an extended public key this will result in multiple calls to retrieve each parent
* due to hardening.
*
* The end result can be found in {@link #deterministicHierarchy}.
*/
private Optional<List<ChildNumber>> childNumbers = Optional.absent();
/**
* Provide a deterministic key representing the root node of the current HD path.
* As the child numbers are explored one by one this deterministic key maintains the chain
* of keys derived from the base 58 xpub.
*
* The end result can be found in {@link #deterministicHierarchy}.
*/
private Optional<DeterministicKey> deterministicKey = Optional.absent();
/**
* Provide a deterministic hierarchy containing all hardened extended public keys so that a
* watching wallet can be created
*/
private Optional<DeterministicHierarchy> deterministicHierarchy = Optional.absent();
/**
* Entropy returned from the Trezor (result of encryption of fixed text
*/
private Optional<byte[]> entropy = Optional.absent();
/**
* @param client The hardware wallet client
*/
public HardwareWalletContext(HardwareWalletClient client) {
this.client = client;
// Ensure the service is subscribed to low level message events from the client
MessageEvents.subscribe(this);
// Verify the environment
if (!client.attach()) {
log.warn("Cannot start the service due to a failed environment.");
throw new IllegalStateException("Cannot start the service due to a failed environment.");
}
}
/**
* @return The wallet features (e.g. PIN required, label etc)
*/
public Optional<Features> getFeatures() {
return features;
}
public void setFeatures(Features features) {
this.features = Optional.fromNullable(features);
}
/**
* @return The transaction for the "sign transaction" use case
*/
public Optional<Transaction> getTransaction() {
return transaction;
}
/**
* @return The current hardware wallet state
*/
public HardwareWalletState getState() {
return currentState;
}
/**
* <p>Note: When adding this signature using the builder setScriptSig() you'll need to append the SIGHASH 0x01 byte</p>
*
* @return The map of ECDSA signatures provided by the device during "sign transaction" keyed on the input index
*/
public Map<Integer, byte[]> getSignatures() {
return signatures;
}
/**
* This value cannot be considered complete until the "SHOW_OPERATION_SUCCESSFUL" message has been received
* since it can be built up over several incoming messages
*
* @return The serialized transaction provided by the device during "sign transaction"
*/
public ByteArrayOutputStream getSerializedTx() {
return serializedTx;
}
/**
* <p>Reset all context state to ensure a fresh context</p>
*/
private void resetAll() {
createWalletSpecification = Optional.absent();
loadWalletSpecification = Optional.absent();
features = Optional.absent();
transaction = Optional.absent();
signatures = Maps.newHashMap();
serializedTx = new ByteArrayOutputStream();
receivingAddressPathMap = Maps.newHashMap();
changeAddressPathMap = Maps.newHashMap();
childNumbers = Optional.absent();
deterministicKey = Optional.absent();
deterministicHierarchy = Optional.absent();
entropy = Optional.absent();
}
/**
* <p>Reset all context state, excepting Features, to ensure a fresh context</p>
*/
private void resetAllButFeatures() {
Optional<Features> originalFeatures = this.features;
resetAll();
this.features = originalFeatures;
}
/**
* <p>Reset the context into a stopped state (the service will have to be stopped and a new one started)</p>
*/
public void resetToStopped() {
log.debug("Reset to 'stopped'");
// Clear relevant information
resetAllButFeatures();
// Issue a hard detach - we are done
client.hardDetach();
// Unsubscribe from events
MessageEvents.unsubscribe(this);
// Perform the state change
currentState = HardwareWalletStates.newStoppedState();
// Fire the high level event
HardwareWalletEvents.fireHardwareWalletEvent(HardwareWalletEventType.SHOW_DEVICE_STOPPED);
}
/**
* <p>Reset the context back to a failed state (retain device information but prevent further communication)</p>
*/
public void resetToFailed() {
log.debug("Reset to 'failed'");
// Clear relevant information
resetAllButFeatures();
// Perform the state change
currentState = HardwareWalletStates.newFailedState();
// Fire the high level event
HardwareWalletEvents.fireHardwareWalletEvent(HardwareWalletEventType.SHOW_DEVICE_FAILED);
}
/**
* <p>Reset the context back to a detached state (no device information)</p>
*/
public void resetToDetached() {
log.debug("Reset to 'detached'");
// Clear relevant information
resetAll();
// Perform the state change
currentState = HardwareWalletStates.newDetachedState();
// Fire the high level event
HardwareWalletEvents.fireHardwareWalletEvent(HardwareWalletEventType.SHOW_DEVICE_DETACHED);
}
/**
* <p>Reset the context back to an attached state (clear device information and transition to connected)</p>
*/
public void resetToAttached() {
log.debug("Reset to 'attached'");
// Clear relevant information
resetAll();
// Perform the state change
currentState = HardwareWalletStates.newAttachedState();
// No high level event for this state
}
/**
* <p>Reset the context back to a connected state (clear device information and transition to initialised)</p>
*/
public void resetToConnected() {
log.debug("Reset to 'connected'");
// Clear relevant information
resetAll();
// Perform the state change
currentState = HardwareWalletStates.newConnectedState();
// No high level event for this state
}
/**
* <p>Reset the context back to a disconnected state (device is attached but communication has not been established)</p>
*/
public void resetToDisconnected() {
log.debug("Reset to 'disconnected'");
// Clear relevant information
resetAll();
// Perform the state change
currentState = HardwareWalletStates.newDisconnectedState();
// No high level event for this state
}
/**
* <p>Reset the context back to the initialised state (standard awaiting state with features)</p>
*/
public void resetToInitialised() {
log.debug("Reset to 'initialised'");
// Clear relevant information
resetAllButFeatures();
// Perform the state change
currentState = HardwareWalletStates.newInitialisedState();
// Fire the high level event
HardwareWalletEvents.fireHardwareWalletEvent(HardwareWalletEventType.SHOW_DEVICE_READY, features.get());
}
/**
* @return The hardware wallet client
*/
public HardwareWalletClient getClient() {
return client;
}
/**
* @return The create wallet specification
*/
public Optional<CreateWalletSpecification> getCreateWalletSpecification() {
return createWalletSpecification;
}
/**
* @return The load wallet specification
*/
public Optional<LoadWalletSpecification> getLoadWalletSpecification() {
return loadWalletSpecification;
}
/**
* @return The map of paths for our receiving addresses on the current transaction (key input index, value deterministic path to receiving address)
*/
public Map<Integer, ImmutableList<ChildNumber>> getReceivingAddressPathMap() {
return receivingAddressPathMap;
}
/**
* @return The map of paths for the change address (key address, value deterministic path to change address)
*/
public Map<Address, ImmutableList<ChildNumber>> getChangeAddressPathMap() {
return changeAddressPathMap;
}
/**
* @return The list of child numbers representing a HD path for the current use case
*/
public Optional<List<ChildNumber>> getChildNumbers() {
return childNumbers;
}
/**
* @return The deterministic key derived from the xpub of the given child numbers for the current use case
*/
public Optional<DeterministicKey> getDeterministicKey() {
return deterministicKey;
}
public void setDeterministicKey(DeterministicKey deterministicKey) {
log.debug("Setting deterministic key to be {}", deterministicKey);
this.deterministicKey = Optional.fromNullable(deterministicKey);
}
/**
* @return The deterministic hierarchy based on the deterministic key for the current use case
*/
public Optional<DeterministicHierarchy> getDeterministicHierarchy() {
return deterministicHierarchy;
}
public void setDeterministicHierarchy(DeterministicHierarchy deterministicHierarchy) {
this.deterministicHierarchy = Optional.fromNullable(deterministicHierarchy);
}
/**
* @return The current use case
*/
public ContextUseCase getCurrentUseCase() {
return currentUseCase;
}
/**
* @param event The low level message event
*/
@Subscribe
public void onMessageEvent(MessageEvent event) {
log.debug("Received message event: '{}'.'{}'", event.getEventType().name(), event.getMessage());
// Perform a state transition as a result of this event
try {
currentState.transition(client, this, event);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sets to "confirm reset" state
*/
public void setToConfirmResetState() {
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmResetState();
// Expect the specification to be in place
CreateWalletSpecification specification = createWalletSpecification.get();
// Issue starting message to elicit the event
client.resetDevice(
specification.getLanguage(),
specification.getLabel(),
specification.isDisplayRandom(),
specification.isPinProtection(),
specification.getStrength()
);
}
/**
* Sets to "confirm load" state
*/
public void setToConfirmLoadState() {
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmLoadState();
// Expect the specification to be in place
LoadWalletSpecification specification = loadWalletSpecification.get();
// Issue starting message to elicit the event
client.loadDevice(
specification.getLanguage(),
specification.getLabel(),
specification.getSeedPhrase(),
specification.getPin()
);
}
/**
* <p>Change or remove the device PIN.</p>
*
* @param remove True if an existing PIN should be removed
*/
public void beginChangePIN(boolean remove) {
log.debug("Begin 'change PIN' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.CHANGE_PIN;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmChangePINState();
// Issue starting message to elicit the event
client.changePIN(remove);
}
/**
* <p>Continue the "change PIN" use case with the provision of the current PIN</p>
*
* @param pin The PIN
*/
public void continueChangePIN_PIN(String pin) {
log.debug("Continue 'change PIN' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmChangePINState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Begin the "wipe device" use case</p>
*/
public void beginWipeDeviceUseCase() {
log.debug("Begin 'wipe device' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.WIPE_DEVICE;
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmWipeState();
// Issue starting message to elicit the event
client.wipeDevice();
}
/**
* <p>Begin the "get address" use case</p>
*
* @param account The plain account number (0 gives maximum compatibility)
* @param keyPurpose The key purpose (RECEIVE_FUNDS,CHANGE,REFUND,AUTHENTICATION etc)
* @param index The plain index of the required address
* @param showDisplay True if the device should display the same address to allow the user to verify no tampering has occurred (recommended).
*/
public void beginGetAddressUseCase(int account, KeyChain.KeyPurpose keyPurpose, int index, boolean showDisplay) {
log.debug("Begin 'get address' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.REQUEST_ADDRESS;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmGetAddressState();
// Issue starting message to elicit the event
client.getAddress(
account,
keyPurpose,
index,
showDisplay
);
}
/**
* <p>Begin the "get public key" use case</p>
*
* @param account The plain account number (0 gives maximum compatibility)
* @param keyPurpose The key purpose (RECEIVE_FUNDS,CHANGE,REFUND,AUTHENTICATION etc)
* @param index The plain index of the required address
*/
public void beginGetPublicKeyUseCase(int account, KeyChain.KeyPurpose keyPurpose, int index) {
log.debug("Begin 'get public key' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.REQUEST_PUBLIC_KEY;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmGetPublicKeyState();
// Issue starting message to elicit the event
client.getPublicKey(
account,
keyPurpose,
index
);
}
/**
* <p>Begin the "get deterministic hierarchy" use case</p>
*
* @param childNumbers The child numbers describing the required chain from the master node including hardening bits
*/
public void beginGetDeterministicHierarchyUseCase(List<ChildNumber> childNumbers) {
log.debug("Begin 'get deterministic hierarchy' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.REQUEST_DETERMINISTIC_HIERARCHY;
// Store the overall context parameters
this.childNumbers = Optional.of(childNumbers);
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmGetDeterministicHierarchyState();
// Issue starting message to elicit the event
// In this case we start with the master node (empty list) to enable building up a complete
// hierarchy in case of hardened child numbers that require private keys to create
client.getDeterministicHierarchy(Lists.<ChildNumber>newArrayList());
}
/**
* <p>Begin the "sign message key use case</p>
*
* @param account The plain account number (0 gives maximum compatibility)
* @param keyPurpose The key purpose (RECEIVE_FUNDS,CHANGE,REFUND,AUTHENTICATION etc)
* @param index The plain index of the required address
* @param message The message for signing
*/
public void beginSignMessageUseCase(
int account,
KeyChain.KeyPurpose keyPurpose,
int index,
byte[] message
) {
log.debug("Begin 'sign message' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.SIGN_MESSAGE;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmSignMessageState();
// Issue starting message to elicit the event
client.signMessage(
account,
keyPurpose,
index,
message
);
}
/**
* <p>Continue the "sign message" use case with the provision of the current PIN</p>
*
* @param pin The PIN
*/
public void continueSignMessage_PIN(String pin) {
log.debug("Continue 'sign message' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmSignMessageState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Begin the "cipher key" use case</p>
*
* @param account The plain account number (0 gives maximum compatibility)
* @param keyPurpose The key purpose (RECEIVE_FUNDS,CHANGE,REFUND,AUTHENTICATION etc)
* @param index The plain index of the required address
* @param key The cipher key (e.g. "Some text")
* @param keyValue The key value (e.g. "[16 bytes of random data]")
* @param isEncrypting True if encrypting
* @param askOnDecrypt True if device should ask on decrypting
* @param askOnEncrypt True if device should ask on encrypting
*/
public void beginCipherKeyUseCase(
int account,
KeyChain.KeyPurpose keyPurpose,
int index,
byte[] key,
byte[] keyValue,
boolean isEncrypting,
boolean askOnDecrypt,
boolean askOnEncrypt
) {
log.debug("Begin 'cipher key' use case");
// Track the use case
currentUseCase = ContextUseCase.REQUEST_CIPHER_KEY;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmCipherKeyState();
// Issue starting message to elicit the event
client.cipherKeyValue(
account,
keyPurpose,
index,
key,
keyValue,
isEncrypting,
askOnDecrypt,
askOnEncrypt
);
}
/**
* <p>Continue the "cipher key" use case with the provision of the current PIN</p>
*
* @param pin The PIN
*/
public void continueCipherKey_PIN(String pin) {
log.debug("Continue 'cipher key' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmCipherKeyState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Begin the "load wallet" use case</p>
*
* @param specification The specification describing the use of PIN, seed strength etc
*/
public void beginLoadWallet(LoadWalletSpecification specification) {
log.debug("Begin 'load wallet' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.LOAD_WALLET;
// Store the overall context parameters
this.loadWalletSpecification = Optional.fromNullable(specification);
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmWipeState();
// Issue starting message to elicit the event
client.wipeDevice();
}
/**
* <p>Continue the "load wallet" use case with the provision of a PIN (either first or second)</p>
*
* @param pin The PIN
*/
public void continueLoadWallet_PIN(String pin) {
log.debug("Continue 'create wallet on device' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmPINState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Begin the "create wallet on device" use case</p>
*
* @param specification The specification describing the use of PIN, seed strength etc
*/
public void beginCreateWallet(CreateWalletSpecification specification) {
log.debug("Begin 'create wallet on device' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.CREATE_WALLET;
// Store the overall context parameters
this.createWalletSpecification = Optional.fromNullable(specification);
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmWipeState();
// Issue starting message to elicit the event
client.wipeDevice();
}
/**
* <p>Continue the "create wallet on device" use case with the provision of a PIN (either first or second)</p>
*
* @param pin The PIN
*/
public void continueCreateWallet_PIN(String pin) {
log.debug("Continue 'create wallet on device' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmPINState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
/**
* <p>Continue the "create wallet on device" use case with the provision of entropy</p>
*
* @param entropy The 256 bits of entropy to include
*/
public void continueCreateWallet_Entropy(byte[] entropy) {
log.debug("Continue 'create wallet on device' use case (provide entropy)");
// Track the use case
currentUseCase = ContextUseCase.PROVIDE_ENTROPY;
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmEntropyState();
// Issue starting message to elicit the event
client.entropyAck(entropy);
}
/**
* <p>Begin the "sign transaction" use case</p>
*
* @param transaction The transaction containing the inputs and outputs
* @param receivingAddressPathMap The map of paths for our receiving addresses
* @param changeAddressPathMap The map paths for our change address
*/
public void beginSignTxUseCase(Transaction transaction, Map<Integer, ImmutableList<ChildNumber>> receivingAddressPathMap, Map<Address, ImmutableList<ChildNumber>> changeAddressPathMap) {
log.debug("Begin 'sign transaction' use case");
// Clear relevant information
resetAllButFeatures();
// Track the use case
currentUseCase = ContextUseCase.SIGN_TX;
// Store the overall context parameters
this.transaction = Optional.of(transaction);
this.receivingAddressPathMap = receivingAddressPathMap;
this.changeAddressPathMap = changeAddressPathMap;
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmSignTxState();
// Issue starting message to elicit the event
client.signTx(transaction);
}
/**
* <p>Continue the "sign transaction" use case with the provision of the current PIN</p>
*
* @param pin The PIN
*/
public void continueSignTx_PIN(String pin) {
log.debug("Continue 'sign tx' use case (provide PIN)");
// Store the overall context parameters
// Set the event receiving state
currentState = HardwareWalletStates.newConfirmSignTxState();
// Issue starting message to elicit the event
client.pinMatrixAck(pin);
}
public Optional<byte[]> getEntropy() {
return entropy;
}
public void setEntropy(Optional<byte[]> entropy) {
this.entropy = entropy;
}
}
| added last wipe time
| core/src/main/java/org/multibit/hd/hardware/core/fsm/HardwareWalletContext.java | added last wipe time | <ide><path>ore/src/main/java/org/multibit/hd/hardware/core/fsm/HardwareWalletContext.java
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> import java.io.ByteArrayOutputStream;
<add>import java.util.Date;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> private Optional<byte[]> entropy = Optional.absent();
<ide>
<ide> /**
<add> * The time when the device was last wiped by MBHD
<add> */
<add> private Optional<Date> lastWipeTime = Optional.absent();
<add>
<add> /**
<ide> * @param client The hardware wallet client
<ide> */
<ide> public HardwareWalletContext(HardwareWalletClient client) {
<ide> public void setEntropy(Optional<byte[]> entropy) {
<ide> this.entropy = entropy;
<ide> }
<add>
<add>
<add> public Optional<Date> getLastWipeTime() {
<add> return lastWipeTime;
<add> }
<add>
<add> public void setLastWipeTime(Optional<Date> lastWipeTime) {
<add> this.lastWipeTime = lastWipeTime;
<add> }
<add>
<ide> } |
|
Java | artistic-2.0 | 1fede7369bb6bf608855ed9eebf68ba0774351fa | 0 | speakeasy/SKYEngine | /*
* Copyright 2016 Kevin Owen Burress <[email protected]>.
*
* 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.speakeasy.skyengine.core.timer;
/**
*
* @author SpeaKeasY
*/
public class Timing {
protected Timing timing;
protected final long nanoseconds;
protected int times;
protected long timeleftns;
private long lasttimens;
private long lasttimensB;
private Timing(int microseconds, int seconds, int minutes, int hours, int times) {
if (microseconds < 0) {
microseconds = 0;
}
if (seconds < 0) {
seconds = 0;
}
if (minutes < 0) {
minutes = 0;
}
if (hours < 0) {
hours = 0;
}
long ns = getNanoSeconds(microseconds, seconds, minutes, hours);
if (ns < 5000) {
ns = 5000;
}
this.nanoseconds = ns;
this.lasttimens = System.nanoTime();
this.timeleftns = 0;
if (times == 0) {
times--;
}
this.times = times;
}
public Timing newTiming(int times) {
timing = new Timing(0, 0, 0, 0, times);
return timing;
}
public Timing newTiming(int microseconds, int times) {
timing = new Timing(microseconds, 0, 0, 0, times);
return timing;
}
public Timing newTiming(int microseconds, int seconds, int times) {
timing = new Timing(microseconds, seconds, 0, 0, times);
return timing;
}
public Timing newTiming(int microseconds, int seconds, int minutes, int times) {
timing = new Timing(microseconds, seconds, minutes, 0, times);
return timing;
}
public Timing newTiming(int microseconds, int seconds, int minutes, int hours, int times) {
timing = new Timing(microseconds, seconds, minutes, hours, times);
return timing;
}
public long getTimeRemaining() {
lasttimensB = System.nanoTime();
timeleftns -= (lasttimensB - lasttimens);
lasttimens = lasttimensB;
return timeleftns;
}
public int update() {
lasttimensB = System.nanoTime();
timeleftns -= (lasttimensB - lasttimens);
lasttimens = lasttimensB;
if (timeleftns <= 0.5) {
if (times > 0 || times == -1) {
timeleftns = nanoseconds - timeleftns;
if (times > 0) {
times--;
return times;
}
return 1;
}
}
return times;
}
public final long getNanoSeconds(int microseconds, int seconds, int minutes, int hours) {
return ((long) (((long) microseconds * 10000000.0) + ((long) seconds * 1000000000.0) + ((long) minutes * 60000000000.0) + ((long) hours * 3600000000000.0)));
}
}
| src/com/speakeasy/skyengine/core/timer/Timing.java | /*
* Copyright 2016 Kevin Owen Burress <[email protected]>.
*
* 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.speakeasy.skyengine.core.timer;
/**
*
* @author SpeaKeasY
*/
public class Timing {
protected Timing timing;
protected final long nanoseconds;
protected int times;
protected long timeleftns;
private long lasttimens;
private long lasttimensB;
private Timing(int microseconds, int seconds, int minutes, int hours, int times) {
if (microseconds < 0) {
microseconds = 0;
}
if (seconds < 0) {
seconds = 0;
}
if (minutes < 0) {
minutes = 0;
}
if (hours < 0) {
hours = 0;
}
long ns = getNanoSeconds(microseconds, seconds, minutes, hours);
if (ns < 5000) {
ns = 5000;
}
this.nanoseconds = ns;
this.lasttimens = System.nanoTime();
this.timeleftns = 0;
if (times == 0) {
times--;
}
this.times = times;
}
public Timing newTiming(int times) {
timing = new Timing(0, 0, 0, 0, times);
return timing;
}
public Timing newTiming(int microseconds, int times) {
timing = new Timing(microseconds, 0, 0, 0, times);
return timing;
}
public Timing newTiming(int microseconds, int seconds, int times) {
timing = new Timing(microseconds, seconds, 0, 0, times);
return timing;
}
public Timing newTiming(int microseconds, int seconds, int minutes, int times) {
timing = new Timing(microseconds, seconds, minutes, 0, times);
return timing;
}
public Timing newTiming(int microseconds, int seconds, int minutes, int hours, int times) {
timing = new Timing(microseconds, seconds, minutes, hours, times);
return timing;
}
public long getTimeRemaining() {
lasttimensB = System.nanoTime();
timeleftns -= (lasttimensB - lasttimens);
lasttimens = lasttimensB;
return timeleftns;
}
public int update() {
lasttimensB = System.nanoTime();
timeleftns -= (lasttimensB - lasttimens);
lasttimens = lasttimensB;
if (timeleftns <= 0.5) {
if (times > 0 || times == -1) {
timeleftns = nanoseconds - timeleftns;
if (times > 0) {
times--;
return times;
}
return 1;
}
}
return times;
}
public final long getNanoSeconds(int microseconds, int seconds, int minutes, int hours) {
return ((long) (((long) microseconds * 10000000.0) + ((long) seconds * 1000000000.0) + ((long) minutes * 60000000000.0) + ((long) hours * 3600000000000.0)));
}
}
| Return times on update. | src/com/speakeasy/skyengine/core/timer/Timing.java | Return times on update. | <ide><path>rc/com/speakeasy/skyengine/core/timer/Timing.java
<ide> if (times == 0) {
<ide> times--;
<ide> }
<add>
<ide> this.times = times;
<ide> }
<ide> |
|
Java | mit | 359217e7d37f27024727a49dbeb2b04a99081442 | 0 | archimatetool/archi,archimatetool/archi,archimatetool/archi | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.osgi.service.datalocation.Location;
import com.archimatetool.editor.utils.FileUtils;
import com.archimatetool.editor.utils.ZipUtils;
/**
* Installs Plug-ins
*
* @author Phillip Beauvoir
*/
public class PluginInstaller {
static final String INSTALL_FOLDER = ".install"; //$NON-NLS-1$
static final String MAGIC_ENTRY = "archi-plugin"; //$NON-NLS-1$
/**
* @param file
* @return True if the file is an Archi plugin Zip file
* @throws IOException
*/
public static boolean isPluginZipFile(File file) throws IOException {
return ZipUtils.isZipFile(file) && ZipUtils.hasZipEntry(file, MAGIC_ENTRY);
}
/**
* Unzip the zip file to the install folder
* @param zipFile The zip file
* @throws IOException
*/
public static void unpackZipPackageToInstallFolder(File zipFile) throws IOException {
File installFolder = getInstallFolder();
if(installFolder != null) {
FileUtils.deleteFolder(installFolder);
ZipUtils.unpackZip(zipFile, installFolder);
}
}
/**
* Check for and copy any pending plugins in the install folder.
* @return True if plugins were copied to the plugins folder and the install folder deleted
* @throws IOException
*/
public static boolean installPendingPlugins() throws IOException {
File installFolder = getInstallFolder();
if(installFolder != null && installFolder.exists() && installFolder.isDirectory()) {
File pluginsFolder = getPluginsFolder();
for(File file : installFolder.listFiles()) {
// Ignore the magic entry file
if(MAGIC_ENTRY.equalsIgnoreCase(file.getName())) {
continue;
}
// Delete old ones in target plugins folder
deleteMatchingPlugin(file, pluginsFolder);
// Copy new ones
if(file.isDirectory()) {
FileUtils.copyFolder(file, new File(pluginsFolder, file.getName()));
}
else {
FileUtils.copyFile(file, new File(pluginsFolder, file.getName()), false);
}
}
// Now delete the install folder
FileUtils.deleteFolder(installFolder);
// If we got this far and successfully deleted the install folder then return true
if(!installFolder.exists()) {
return true;
}
}
return false;
}
// Delete matching target plugin
private static void deleteMatchingPlugin(File newPlugin, File pluginsFolder) throws IOException {
for(File file : findMatchingPlugins(pluginsFolder, newPlugin)) {
if(file.isDirectory()) {
recursiveDeleteOnExit(file.toPath());
}
else {
file.deleteOnExit();
}
}
}
private static File[] findMatchingPlugins(File pluginsFolder, File newPlugin) {
String pluginName = getPluginName(newPlugin.getName());
return pluginsFolder.listFiles(new FileFilter() {
public boolean accept(File file) {
String targetPluginName = getPluginName(file.getName());
return targetPluginName.equals(pluginName) && !newPlugin.getName().equals(file.getName());
}
});
}
static String getPluginName(String string) {
int index = string.indexOf("_"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(0, index);
}
return string;
}
static String getPluginVersion(String string) {
int index = string.lastIndexOf(".jar"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(0, index);
}
index = string.lastIndexOf("_"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(index + 1);
}
return string;
}
static File getInstallFolder() {
Location instanceLoc = Platform.getInstanceLocation();
if(instanceLoc != null) {
return new File(instanceLoc.getURL().getPath(), INSTALL_FOLDER);
}
return null;
}
static File getPluginsFolder() throws IOException {
URL url = Platform.getBundle(ArchiPlugin.PLUGIN_ID).getEntry("/"); //$NON-NLS-1$
url = FileLocator.resolve(url);
return new File(url.getPath()).getParentFile();
}
static void recursiveDeleteOnExit(Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
file.toFile().deleteOnExit();
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
dir.toFile().deleteOnExit();
return FileVisitResult.CONTINUE;
}
});
}
}
| com.archimatetool.editor/src/com/archimatetool/editor/PluginInstaller.java | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.osgi.service.datalocation.Location;
import com.archimatetool.editor.utils.FileUtils;
import com.archimatetool.editor.utils.ZipUtils;
/**
* Installs Plug-ins
*
* @author Phillip Beauvoir
*/
public class PluginInstaller {
static final String INSTALL_FOLDER = ".install"; //$NON-NLS-1$
static final String MAGIC_ENTRY = "archi-plugin"; //$NON-NLS-1$
/**
* @param file
* @return True if the file is an Archi plugin Zip file
* @throws IOException
*/
public static boolean isPluginZipFile(File file) throws IOException {
return ZipUtils.isZipFile(file) && ZipUtils.hasZipEntry(file, MAGIC_ENTRY);
}
/**
* Unzip the zip file to the install folder
* @param zipFile The zip file
* @throws IOException
*/
public static void unpackZipPackageToInstallFolder(File zipFile) throws IOException {
File installFolder = getInstallFolder();
if(installFolder != null) {
FileUtils.deleteFolder(installFolder);
ZipUtils.unpackZip(zipFile, installFolder);
}
}
/**
* Check for and copy any pending plugins in the install folder.
* @return True if plugins were copied to the plugins folder and the install folder deleted
* @throws IOException
*/
public static boolean installPendingPlugins() throws IOException {
File installFolder = getInstallFolder();
if(installFolder != null && installFolder.exists() && installFolder.isDirectory()) {
File pluginsFolder = getPluginsFolder();
for(File file : installFolder.listFiles()) {
// Ignore the magic entry file
if(MAGIC_ENTRY.equalsIgnoreCase(file.getName())) {
continue;
}
// Delete old ones in target plugins folder
deleteMatchingPlugin(file, pluginsFolder);
// Copy new ones
if(file.isDirectory()) {
FileUtils.copyFolder(file, new File(pluginsFolder, file.getName()));
}
else {
FileUtils.copyFile(file, new File(pluginsFolder, file.getName()), false);
}
}
// Now delete the install folder
FileUtils.deleteFolder(installFolder);
// If we got this far and successfully deleted the install folder then return true
if(!installFolder.exists()) {
return true;
}
}
return false;
}
// Delete matching target plugin
private static void deleteMatchingPlugin(File newPlugin, File pluginsFolder) throws IOException {
String pluginName = getPluginName(newPlugin.getName());
for(File file : findMatchingPlugins(pluginsFolder, pluginName)) {
if(file.isDirectory()) {
FileUtils.deleteFolder(file);
}
else {
file.delete();
}
}
}
private static File[] findMatchingPlugins(File pluginsFolder, final String pluginName) {
return pluginsFolder.listFiles(new FileFilter() {
public boolean accept(File file) {
String targetPluginName = getPluginName(file.getName());
return targetPluginName.equals(pluginName);
}
});
}
static String getPluginName(String string) {
int index = string.indexOf("_"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(0, index);
}
return string;
}
static String getPluginVersion(String string) {
int index = string.lastIndexOf(".jar"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(0, index);
}
index = string.lastIndexOf("_"); //$NON-NLS-1$
if(index != -1) {
string = string.substring(index + 1);
}
return string;
}
static File getInstallFolder() {
Location instanceLoc = Platform.getInstanceLocation();
if(instanceLoc != null) {
return new File(instanceLoc.getURL().getPath(), INSTALL_FOLDER);
}
return null;
}
static File getPluginsFolder() throws IOException {
URL url = Platform.getBundle(ArchiPlugin.PLUGIN_ID).getEntry("/"); //$NON-NLS-1$
url = FileLocator.resolve(url);
return new File(url.getPath()).getParentFile();
}
}
| PluginInstaller deletes old plugins on exit
| com.archimatetool.editor/src/com/archimatetool/editor/PluginInstaller.java | PluginInstaller deletes old plugins on exit | <ide><path>om.archimatetool.editor/src/com/archimatetool/editor/PluginInstaller.java
<ide> import java.io.FileFilter;
<ide> import java.io.IOException;
<ide> import java.net.URL;
<add>import java.nio.file.FileVisitResult;
<add>import java.nio.file.Files;
<add>import java.nio.file.Path;
<add>import java.nio.file.SimpleFileVisitor;
<add>import java.nio.file.attribute.BasicFileAttributes;
<ide>
<ide> import org.eclipse.core.runtime.FileLocator;
<ide> import org.eclipse.core.runtime.Platform;
<ide>
<ide> // Delete matching target plugin
<ide> private static void deleteMatchingPlugin(File newPlugin, File pluginsFolder) throws IOException {
<del> String pluginName = getPluginName(newPlugin.getName());
<del>
<del> for(File file : findMatchingPlugins(pluginsFolder, pluginName)) {
<add> for(File file : findMatchingPlugins(pluginsFolder, newPlugin)) {
<ide> if(file.isDirectory()) {
<del> FileUtils.deleteFolder(file);
<add> recursiveDeleteOnExit(file.toPath());
<ide> }
<ide> else {
<del> file.delete();
<add> file.deleteOnExit();
<ide> }
<ide> }
<ide> }
<ide>
<del> private static File[] findMatchingPlugins(File pluginsFolder, final String pluginName) {
<add> private static File[] findMatchingPlugins(File pluginsFolder, File newPlugin) {
<add> String pluginName = getPluginName(newPlugin.getName());
<add>
<ide> return pluginsFolder.listFiles(new FileFilter() {
<ide> public boolean accept(File file) {
<ide> String targetPluginName = getPluginName(file.getName());
<del> return targetPluginName.equals(pluginName);
<add> return targetPluginName.equals(pluginName) && !newPlugin.getName().equals(file.getName());
<ide> }
<ide> });
<ide> }
<ide> url = FileLocator.resolve(url);
<ide> return new File(url.getPath()).getParentFile();
<ide> }
<add>
<add> static void recursiveDeleteOnExit(Path path) throws IOException {
<add> Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
<add>
<add> @Override
<add> public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
<add> file.toFile().deleteOnExit();
<add> return FileVisitResult.CONTINUE;
<add> }
<add>
<add> @Override
<add> public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
<add> dir.toFile().deleteOnExit();
<add> return FileVisitResult.CONTINUE;
<add> }
<add> });
<add> }
<ide> } |
|
Java | lgpl-2.1 | 3041d62625af5a57ae36ecc042f0d8cc2febcc3a | 0 | serrapos/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,victos/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,victos/opencms-core,it-tavis/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,serrapos/opencms-core,MenZil/opencms-core,MenZil/opencms-core,alkacon/opencms-core,MenZil/opencms-core,serrapos/opencms-core,victos/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,victos/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/db/CmsDriverManager.java,v $
* Date : $Date: 2004/04/05 05:33:02 $
* Version: $Revision: 1.349 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2002 - 2003 Alkacon Software (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.db;
import org.opencms.file.*;
import org.opencms.flex.CmsFlexRequestContextInfo;
import org.opencms.lock.CmsLock;
import org.opencms.lock.CmsLockException;
import org.opencms.lock.CmsLockManager;
import org.opencms.main.CmsEvent;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.I_CmsConstants;
import org.opencms.main.I_CmsEventListener;
import org.opencms.main.OpenCms;
import org.opencms.main.OpenCmsCore;
import org.opencms.report.CmsLogReport;
import org.opencms.report.I_CmsReport;
import org.opencms.security.CmsAccessControlEntry;
import org.opencms.security.CmsAccessControlList;
import org.opencms.security.CmsPermissionSet;
import org.opencms.security.CmsSecurityException;
import org.opencms.security.I_CmsPasswordValidation;
import org.opencms.security.I_CmsPrincipal;
import org.opencms.util.CmsUUID;
import org.opencms.validation.CmsHtmlLinkValidator;
import org.opencms.workflow.CmsTask;
import org.opencms.workflow.CmsTaskLog;
import org.opencms.workplace.CmsWorkplaceManager;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.commons.collections.map.LRUMap;
/**
* This is the driver manager.<p>
*
* @author Alexander Kandzior ([email protected])
* @author Thomas Weckert ([email protected])
* @author Carsten Weinholz ([email protected])
* @author Michael Emmerich ([email protected])
* @version $Revision: 1.349 $ $Date: 2004/04/05 05:33:02 $
* @since 5.1
*/
public class CmsDriverManager extends Object implements I_CmsEventListener {
/**
* Provides a method to build cache keys for groups and users that depend either on
* a name string or an id.<p>
*
* @author Alkexander Kandzior ([email protected])
*/
private class CacheId extends Object {
/**
* Name of the object
*/
public String m_name = null;
/**
* Id of the object
*/
public CmsUUID m_uuid = null;
/**
* Creates a new CacheId for a CmsGroup.<p>
*
* @param group the group to create a cache id from
*/
public CacheId(CmsGroup group) {
m_name = group.getName();
m_uuid = group.getId();
}
/**
* Creates a new CacheId for a CmsResource.<p>
*
* @param resource the resource to create a cache id from
*/
public CacheId(CmsResource resource) {
m_name = resource.getName();
m_uuid = resource.getResourceId();
}
/**
* Creates a new CacheId for a CmsUser.<p>
*
* @param user the user to create a cache id from
*/
public CacheId(CmsUser user) {
m_name = user.getName() + user.getType();
m_uuid = user.getId();
}
/**
* Creates a new CacheId for a CmsUUID.<p>
*
* @param uuid the uuid to create a cache id from
*/
public CacheId(CmsUUID uuid) {
m_uuid = uuid;
}
/**
* Creates a new CacheId for a String.<p>
*
* @param str the string to create a cache id from
*/
public CacheId(String str) {
m_name = str;
}
/**
* Creates a new CacheId for a String and CmsUUID.<p>
*
* @param name the string to create a cache id from
* @param uuid the uuid to create a cache id from
*/
public CacheId(String name, CmsUUID uuid) {
m_name = name;
m_uuid = uuid;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof CacheId)) {
return false;
}
CacheId other = (CacheId)o;
boolean result;
if (m_uuid != null) {
result = m_uuid.equals(other.m_uuid);
if (result) {
return true;
}
}
if (m_name != null) {
result = m_name.equals(other.m_name);
if (result) {
return true;
}
}
return false;
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
if (m_uuid == null) {
return 509;
} else {
return m_uuid.hashCode();
}
}
}
/**
* Key for all properties
*/
public static final String C_CACHE_ALL_PROPERTIES = "__CACHE_ALL_PROPERTIES__";
/**
* Key for null value
*/
public static final String C_CACHE_NULL_PROPERTY_VALUE = "__CACHE_NULL_PROPERTY_VALUE__";
/**
* Key for indicating no changes
*/
public static final int C_NOTHING_CHANGED = 0;
/**
* Key to indicate complete update
*/
public static final int C_UPDATE_ALL = 3;
/**
* Key to indicate update of resource record
*/
public static final int C_UPDATE_RESOURCE = 4;
/**
* Key to indicate update of resource state
*/
public static final int C_UPDATE_RESOURCE_STATE = 1;
/**
* Key to indicate update of struicture record
*/
public static final int C_UPDATE_STRUCTURE = 5;
/**
* Key to indicate update of structure state
*/
public static final int C_UPDATE_STRUCTURE_STATE = 2;
/**
* Separator for user cache
*/
private static final String C_USER_CACHE_SEP = "\u0000";
/**
* Cache for access control lists
*/
private Map m_accessControlListCache;
/**
* The backup driver
*/
private I_CmsBackupDriver m_backupDriver;
/**
* The configuration of the property-file.
*/
private ExtendedProperties m_configuration;
/**
* Constant to count the file-system changes if Folders are involved.
*/
private long m_fileSystemFolderChanges;
/**
* Cache for groups
*/
private Map m_groupCache;
/**
* The portnumber the workplace access is limited to.
*/
private int m_limitedWorkplacePort = -1;
/**
* The lock manager
*/
private CmsLockManager m_lockManager = OpenCms.getLockManager();
/**
* The class used for password validation
*/
private I_CmsPasswordValidation m_passwordValidationClass;
/**
* The class used for cache key generation
*/
private I_CmsCacheKey m_keyGenerator;
/**
* Cache for permission checks
*/
private Map m_permissionCache;
/**
* Cache for offline projects
*/
private Map m_projectCache;
/**
* The project driver
*/
private I_CmsProjectDriver m_projectDriver;
/**
* Cache for properties
*/
private Map m_propertyCache;
/**
* Comment for <code>m_refresh</code>
*/
private String m_refresh;
/**
* The Registry
*/
private CmsRegistry m_registry;
/**
* Cache for resources
*/
private Map m_resourceCache;
/**
* Cache for resource lists
*/
private Map m_resourceListCache;
/**
* Hashtable with resource-types.
*/
private I_CmsResourceType[] m_resourceTypes = null;
/**
* Cache for user data
*/
private Map m_userCache;
/** The user driver. */
private I_CmsUserDriver m_userDriver;
/**
* Cache for user groups
*/
private Map m_userGroupsCache;
/**
* The VFS driver
*/
private I_CmsVfsDriver m_vfsDriver;
/**
* The workflow driver
*/
private I_CmsWorkflowDriver m_workflowDriver;
/**
* The HTML link validator
*/
private CmsHtmlLinkValidator m_htmlLinkValidator;
/**
* Reads the required configurations from the opencms.properties file and creates
* the various drivers to access the cms resources.<p>
*
* The initialization process of the driver manager and its drivers is split into
* the following phases:
* <ul>
* <li>the database pool configuration is read</li>
* <li>a plain and empty driver manager instance is created</li>
* <li>an instance of each driver is created</li>
* <li>the driver manager is passed to each driver during initialization</li>
* <li>finally, the driver instances are passed to the driver manager during initialization</li>
* </ul>
*
* @param configuration the configurations from the propertyfile
* @param resourceTypes the initialized configured resource types
* @return CmsDriverManager the instanciated driver manager.
* @throws CmsException if the driver manager couldn't be instanciated.
*/
public static final CmsDriverManager newInstance(ExtendedProperties configuration, List resourceTypes) throws CmsException {
// initialize static hastables
CmsDbUtil.init();
List drivers = null;
String driverName = null;
I_CmsVfsDriver vfsDriver = null;
I_CmsUserDriver userDriver = null;
I_CmsProjectDriver projectDriver = null;
I_CmsWorkflowDriver workflowDriver = null;
I_CmsBackupDriver backupDriver = null;
CmsDriverManager driverManager = null;
try {
// create a driver manager instance
driverManager = new CmsDriverManager();
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 1 - initializing database");
}
} catch (Exception exc) {
String message = "Critical error while loading driver manager";
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isFatalEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).fatal(message, exc);
}
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 2 - initializing pools");
}
// read the pool names to initialize
String driverPoolNames[] = configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_DB + ".pools");
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
String names = "";
for (int p = 0; p < driverPoolNames.length; p++) {
names += driverPoolNames[p] + " ";
}
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Resource pools : " + names);
}
// initialize each pool
for (int p = 0; p < driverPoolNames.length; p++) {
driverManager.newPoolInstance(configuration, driverPoolNames[p]);
}
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 3 - initializing drivers");
}
// read the vfs driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_VFS));
driverName = configuration.getString((String)drivers.get(0) + ".vfs.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
vfsDriver = (I_CmsVfsDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
// read the user driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_USER));
driverName = configuration.getString((String)drivers.get(0) + ".user.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
userDriver = (I_CmsUserDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
// read the project driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_PROJECT));
driverName = configuration.getString((String)drivers.get(0) + ".project.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
projectDriver = (I_CmsProjectDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
// read the workflow driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_WORKFLOW));
driverName = configuration.getString((String)drivers.get(0) + ".workflow.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
workflowDriver = (I_CmsWorkflowDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
// read the backup driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_BACKUP));
driverName = configuration.getString((String)drivers.get(0) + ".backup.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
backupDriver = (I_CmsBackupDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
try {
// invoke the init method of the driver manager
driverManager.init(configuration, vfsDriver, userDriver, projectDriver, workflowDriver, backupDriver);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 4 ok - finished");
}
} catch (Exception exc) {
String message = "Critical error while loading driver manager";
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isFatalEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).fatal(message, exc);
}
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
// set the pool for the COS
// TODO: check if there is a better place for this
String cosPoolUrl = configuration.getString("db.cos.pool");
OpenCms.setRuntimeProperty("cosPoolUrl", cosPoolUrl);
CmsDbUtil.setDefaultPool(cosPoolUrl);
// register the driver manager for clearcache events
org.opencms.main.OpenCms.addCmsEventListener(driverManager, new int[] {
I_CmsEventListener.EVENT_CLEAR_CACHES,
I_CmsEventListener.EVENT_PUBLISH_PROJECT
});
// set the resource type list
driverManager.setResourceTypes(resourceTypes);
// return the configured driver manager
return driverManager;
}
/**
* Sets the internal list of configured resource types.<p>
*
* @param resourceTypes the list of configured resource types
* @throws CmsException if something goes wrong
*/
private void setResourceTypes(List resourceTypes) throws CmsException {
m_resourceTypes = new I_CmsResourceType[resourceTypes.size() * 2];
for (int i = 0; i < resourceTypes.size(); i++) {
// add the resource-type
try {
I_CmsResourceType resTypeClass = (I_CmsResourceType)resourceTypes.get(i);
int pos = resTypeClass.getResourceType();
if (pos > m_resourceTypes.length) {
I_CmsResourceType[] buffer = new I_CmsResourceType[pos * 2];
System.arraycopy(m_resourceTypes, 0, buffer, 0, m_resourceTypes.length);
m_resourceTypes = buffer;
}
m_resourceTypes[pos] = resTypeClass;
} catch (Exception e) {
OpenCms.getLog(this).error("Error initializing resource types", e);
throw new CmsException("[" + getClass().getName() + "] Error while getting ResourceType: " + resourceTypes.get(i) + " from registry ", CmsException.C_UNKNOWN_EXCEPTION);
}
}
}
/**
* Accept a task from the Cms.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task to accept.
*
* @throws CmsException if something goes wrong
*/
public void acceptTask(CmsRequestContext context, int taskId) throws CmsException {
CmsTask task = m_workflowDriver.readTask(taskId);
task.setPercentage(1);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Task was accepted from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Tests if the user can access the project.<p>
*
* All users are granted.
*
* @param context the current request context
* @param projectId the id of the project
* @return true, if the user has access, else returns false
* @throws CmsException if something goes wrong
*/
public boolean accessProject(CmsRequestContext context, int projectId) throws CmsException {
CmsProject testProject = readProject(projectId);
if (projectId == I_CmsConstants.C_PROJECT_ONLINE_ID) {
return true;
}
// is the project unlocked?
if (testProject.getFlags() != I_CmsConstants.C_PROJECT_STATE_UNLOCKED && testProject.getFlags() != I_CmsConstants.C_PROJECT_STATE_INVISIBLE) {
return (false);
}
// is the current-user admin, or the owner of the project?
if ((context.currentProject().getOwnerId().equals(context.currentUser().getId())) || isAdmin(context)) {
return (true);
}
// get all groups of the user
Vector groups = getGroupsOfUser(context, context.currentUser().getName());
// test, if the user is in the same groups like the project.
for (int i = 0; i < groups.size(); i++) {
CmsUUID groupId = ((CmsGroup)groups.elementAt(i)).getId();
if ((groupId.equals(testProject.getGroupId())) || (groupId.equals(testProject.getManagerGroupId()))) {
return (true);
}
}
return (false);
}
/**
* Adds a file extension to the list of known file extensions.<p>
*
* Users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param extension a file extension like 'html'
* @param resTypeName name of the resource type associated to the extension
* @throws CmsException if something goes wrong
*/
public void addFileExtension(CmsRequestContext context, String extension, String resTypeName) throws CmsException {
if (extension != null && resTypeName != null) {
if (isAdmin(context)) {
Hashtable suffixes = (Hashtable)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS);
if (suffixes == null) {
suffixes = new Hashtable();
suffixes.put(extension, resTypeName);
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS, suffixes);
} else {
suffixes.put(extension, resTypeName);
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS, suffixes);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] addFileExtension() " + extension, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
}
/**
* Adds a user to the Cms.<p>
*
* Only a adminstrator can add users to the cms.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param id the id of the user
* @param name the name for the user
* @param password the password for the user
* @param recoveryPassword the recoveryPassword for the user
* @param description the description for the user
* @param firstname the firstname of the user
* @param lastname the lastname of the user
* @param email the email of the user
* @param flags the flags for a user (e.g. I_CmsConstants.C_FLAG_ENABLED)
* @param additionalInfos a Hashtable with additional infos for the user, these
* Infos may be stored into the Usertables (depending on the implementation)
* @param defaultGroup the default groupname for the user
* @param address the address of the user
* @param section the section of the user
* @param type the type of the user
* @return the new user will be returned.
* @throws CmsException if operation was not succesfull
*/
public CmsUser addImportUser(CmsRequestContext context, String id, String name, String password, String recoveryPassword, String description, String firstname, String lastname, String email, int flags, Hashtable additionalInfos, String defaultGroup, String address, String section, int type) throws CmsException {
// Check the security
if (isAdmin(context)) {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
CmsGroup group = readGroup(defaultGroup);
CmsUser newUser = m_userDriver.importUser(new CmsUUID(id), name, password, recoveryPassword, description, firstname, lastname, email, 0, 0, flags, additionalInfos, group, address, section, type, null);
addUserToGroup(context, newUser.getName(), group.getName());
return newUser;
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] addImportUser() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Adds a user to the Cms.<p>
*
* Only a adminstrator can add users to the cms.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param name the new name for the user
* @param password the new password for the user
* @param group the default groupname for the user
* @param description the description for the user
* @param additionalInfos a Hashtable with additional infos for the user, these
* Infos may be stored into the Usertables (depending on the implementation)
* @return the new user will be returned
* @throws CmsException if operation was not succesfull
*/
public CmsUser addUser(CmsRequestContext context, String name, String password, String group, String description, Hashtable additionalInfos) throws CmsException {
// Check the security
if (isAdmin(context)) {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
// check the password
validatePassword(password);
if (name.length() > 0) {
CmsGroup defaultGroup = readGroup(group);
CmsUser newUser = m_userDriver.createUser(name, password, description, " ", " ", " ", 0, I_CmsConstants.C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
addUserToGroup(context, newUser.getName(), defaultGroup.getName());
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_INVALID_PASSWORD);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] addUser() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Adds a user to a group.<p>
*
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param username the name of the user that is to be added to the group
* @param groupname the name of the group
* @throws CmsException if operation was not succesfull
*/
public void addUserToGroup(CmsRequestContext context, String username, String groupname) throws CmsException {
if (!userInGroup(context, username, groupname)) {
// Check the security
if (isAdmin(context)) {
CmsUser user;
CmsGroup group;
try {
user = readUser(username);
} catch (CmsException e) {
if (e.getType() == CmsException.C_NO_USER) {
user = readWebUser(username);
} else {
throw e;
}
}
//check if the user exists
if (user != null) {
group = readGroup(groupname);
//check if group exists
if (group != null) {
//add this user to the group
m_userDriver.createUserInGroup(user.getId(), group.getId(), null);
// update the cache
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]" + groupname, CmsException.C_NO_GROUP);
}
} else {
throw new CmsException("[" + getClass().getName() + "]" + username, CmsException.C_NO_USER);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] addUserToGroup() " + username + " " + groupname, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
}
/**
* Adds a web user to the Cms.<p>
*
* A web user has no access to the workplace but is able to access personalized
* functions controlled by the OpenCms.
*
* @param name the new name for the user
* @param password the new password for the user
* @param group the default groupname for the user
* @param description the description for the user
* @param additionalInfos a Hashtable with additional infos for the user, these
* Infos may be stored into the Usertables (depending on the implementation)
* @return the new user will be returned.
* @throws CmsException if operation was not succesfull.
*/
public CmsUser addWebUser(String name, String password, String group, String description, Hashtable additionalInfos) throws CmsException {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
// check the password
validatePassword(password);
if ((name.length() > 0)) {
CmsGroup defaultGroup = readGroup(group);
CmsUser newUser = m_userDriver.createUser(name, password, description, " ", " ", " ", 0, I_CmsConstants.C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", I_CmsConstants.C_USER_TYPE_WEBUSER);
CmsUser user;
CmsGroup usergroup;
user = m_userDriver.readUser(newUser.getName(), I_CmsConstants.C_USER_TYPE_WEBUSER);
//check if the user exists
if (user != null) {
usergroup = readGroup(group);
//check if group exists
if (usergroup != null) {
//add this user to the group
m_userDriver.createUserInGroup(user.getId(), usergroup.getId(), null);
// update the cache
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]" + group, CmsException.C_NO_GROUP);
}
} else {
throw new CmsException("[" + getClass().getName() + "]" + name, CmsException.C_NO_USER);
}
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_INVALID_PASSWORD);
}
}
/**
* Adds a web user to the Cms.<p>
*
* A web user has no access to the workplace but is able to access personalized
* functions controlled by the OpenCms.<p>
*
* @param name the new name for the user
* @param password the new password for the user
* @param group the default groupname for the user
* @param additionalGroup an additional group for the user
* @param description the description for the user
* @param additionalInfos a Hashtable with additional infos for the user, these
* Infos may be stored into the Usertables (depending on the implementation)
* @return the new user will be returned.
* @throws CmsException if operation was not succesfull.
*/
public CmsUser addWebUser(String name, String password, String group, String additionalGroup, String description, Hashtable additionalInfos) throws CmsException {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
// check the password
validatePassword(password);
if ((name.length() > 0)) {
CmsGroup defaultGroup = readGroup(group);
CmsUser newUser = m_userDriver.createUser(name, password, description, " ", " ", " ", 0, I_CmsConstants.C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", I_CmsConstants.C_USER_TYPE_WEBUSER);
CmsUser user;
CmsGroup usergroup;
CmsGroup addGroup;
user = m_userDriver.readUser(newUser.getName(), I_CmsConstants.C_USER_TYPE_WEBUSER);
//check if the user exists
if (user != null) {
usergroup = readGroup(group);
//check if group exists
if (usergroup != null && isWebgroup(usergroup)) {
//add this user to the group
m_userDriver.createUserInGroup(user.getId(), usergroup.getId(), null);
// update the cache
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]" + group, CmsException.C_NO_GROUP);
}
// if an additional groupname is given and the group does not belong to
// Users, Administrators or Projectmanager add the user to this group
if (additionalGroup != null && !"".equals(additionalGroup)) {
addGroup = readGroup(additionalGroup);
if (addGroup != null && isWebgroup(addGroup)) {
//add this user to the group
m_userDriver.createUserInGroup(user.getId(), addGroup.getId(), null);
// update the cache
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]" + additionalGroup, CmsException.C_NO_GROUP);
}
}
} else {
throw new CmsException("[" + getClass().getName() + "]" + name, CmsException.C_NO_USER);
}
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_INVALID_PASSWORD);
}
}
/**
* Creates a backup of the published project.<p>
*
* @param context the current request context
* @param backupProject the project to be backuped
* @param tagId the version of the backup
* @param publishDate the date of publishing
* @throws CmsException if operation was not succesful
*/
public void backupProject(CmsRequestContext context, CmsProject backupProject, int tagId, long publishDate) throws CmsException {
m_backupDriver.writeBackupProject(backupProject, tagId, publishDate, context.currentUser());
}
/**
* Changes the lock of a resource.<p>
*
* @param context the current request context
* @param resourcename the name of the resource
* @throws CmsException if operation was not succesful
*/
public void changeLock(CmsRequestContext context, String resourcename) throws CmsException {
CmsResource resource = readFileHeader(context, resourcename);
CmsLock oldLock = getLock(context, resourcename);
CmsLock exclusiveLock = null;
if (oldLock.isNullLock()) {
throw new CmsLockException("Unable to steal lock on a unlocked resource", CmsLockException.C_RESOURCE_UNLOCKED);
}
// stealing a lock: checking permissions will throw an exception coz the
// resource is still locked for the other user. thus, the resource is unlocked
// before the permissions of the new user are checked. if the new user
// has insufficient permissions, the previous lock is restored.
// save the lock of the resource's exclusive locked sibling
exclusiveLock = m_lockManager.getExclusiveLockedSibling(this, context, resourcename);
// save the lock of the resource itself
oldLock = getLock(context, resourcename);
// remove the lock
m_lockManager.removeResource(this, context, resourcename, true);
try {
// check if the user has write access to the resource
m_permissionCache.clear();
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
} catch (CmsSecurityException e) {
// restore the lock of the exclusive locked sibling in case a lock gets stolen by
// a new user with insufficient permissions on the resource
m_lockManager.addResource(this, context, exclusiveLock.getResourceName(), exclusiveLock.getUserId(), exclusiveLock.getProjectId(), CmsLock.C_MODE_COMMON);
throw e;
}
if (resource.getState() != I_CmsConstants.C_STATE_UNCHANGED) {
// update the project flag of a modified resource as "modified inside the current project"
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), resource);
}
m_lockManager.addResource(this, context, resource.getRootPath(), context.currentUser().getId(), context.currentProject().getId(), CmsLock.C_MODE_COMMON);
clearResourceCache();
m_permissionCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Changes the project-id of a resource to the current project,
* for publishing the resource directly.<p>
*
* @param resourcename the name of the resource to change
* @param context the current request context
* @throws CmsException if something goes wrong
*/
public void changeLockedInProject(CmsRequestContext context, String resourcename) throws CmsException {
// include deleted resources, otherwise publishing of them will not work
List path = readPath(context, resourcename, true);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
// update the project flag of a modified resource as "modified inside the current project"
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), resource);
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Changes the user type of the user.<p>
* Only the administrator can change the type.
*
* @param context the current request context
* @param user the user to change
* @param userType the new usertype of the user
* @throws CmsException if something goes wrong
*/
public void changeUserType(CmsRequestContext context, CmsUser user, int userType) throws CmsException {
if (isAdmin(context)) {
// try to remove user from cache
clearUserCache(user);
m_userDriver.writeUserType(user.getId(), userType);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] changeUserType() " + user.getName(), CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Changes the user type of the user.<p>
* Only the administrator can change the type.
*
* @param context the current request context
* @param userId the id of the user to change
* @param userType the new usertype of the user
* @throws CmsException if something goes wrong
*/
public void changeUserType(CmsRequestContext context, CmsUUID userId, int userType) throws CmsException {
CmsUser theUser = m_userDriver.readUser(userId);
changeUserType(context, theUser, userType);
}
/**
* Changes the user type of the user.<p>
* Only the administrator can change the type.
*
* @param context the current request context
* @param username the name of the user to change
* @param userType the new usertype of the user
* @throws CmsException if something goes wrong
*/
public void changeUserType(CmsRequestContext context, String username, int userType) throws CmsException {
CmsUser theUser = null;
try {
// try to read the webuser
theUser = this.readWebUser(username);
} catch (CmsException e) {
// try to read the systemuser
if (e.getType() == CmsException.C_NO_USER) {
theUser = this.readUser(username);
} else {
throw e;
}
}
changeUserType(context, theUser, userType);
}
/**
* Performs a blocking permission check on a resource.<p>
* If the required permissions are not satisfied by the permissions the user has on the resource,
* an no access exception is thrown.
*
* @param context the current request context
* @param resource the resource on which permissions are required
* @param requiredPermissions the set of permissions required to access the resource
* @throws CmsException in case of any i/o error
* @throws CmsSecurityException if the required permissions are not satisfied
*/
public void checkPermissions(CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions) throws CmsException, CmsSecurityException {
if (!hasPermissions(context, resource, requiredPermissions, false)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] denied access to resource " + resource.getName() + ", required permissions are " + requiredPermissions.getPermissionString() + " (required one)", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Changes the state for this resource.<p>
* The user may change this, if he is admin of the resource.
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param filename the complete path to the resource
* @param state the new state of this resource
*
* @throws CmsException if the user has not the rights for this resource
*/
public void chstate(CmsRequestContext context, String filename, int state) throws CmsException {
CmsResource resource = null;
// read the resource to check the access
if (CmsResource.isFolder(filename)) {
resource = readFolder(context, filename);
} else {
resource = (CmsFile)readFileHeader(context, filename);
}
// check the access rights
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
// set the state of the resource
resource.setState(state);
// write-acces was granted - write the file.
if (CmsResource.isFolder(filename)) {
m_vfsDriver.writeFolder(context.currentProject(), (CmsFolder)resource, C_UPDATE_ALL, context.currentUser().getId());
// update the cache
//clearResourceCache(filename, context.currentProject(), context.currentUser());
clearResourceCache();
} else {
m_vfsDriver.writeFileHeader(context.currentProject(), (CmsFile)resource, C_UPDATE_ALL, context.currentUser().getId());
// update the cache
//clearResourceCache(filename, context.currentProject(), context.currentUser());
clearResourceCache();
}
}
/**
* Changes the resourcetype for this resource.<p>
*
* Only the resourcetype of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change this, if he is admin of the resource. <br>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param filename the complete m_path to the resource
* @param newType the name of the new resourcetype for this resource
*
* @throws CmsException if operation was not succesful
*/
public void chtype(CmsRequestContext context, String filename, int newType) throws CmsException {
I_CmsResourceType type = getResourceType(newType);
// read the resource to check the access
CmsResource resource = readFileHeader(context, filename);
resource.setType(type.getResourceType());
resource.setLoaderId(type.getLoaderId());
writeFileHeader(context, (CmsFile)resource);
}
/**
* Clears the access control list cache when access control entries are changed.<p>
*/
protected void clearAccessControlListCache() {
m_accessControlListCache.clear();
m_resourceCache.clear();
m_resourceListCache.clear();
m_permissionCache.clear();
}
/**
* Clears all internal DB-Caches.<p>
*/
// TODO: should become protected, use event instead
public void clearcache() {
m_userCache.clear();
m_groupCache.clear();
m_userGroupsCache.clear();
m_projectCache.clear();
m_resourceCache.clear();
m_resourceListCache.clear();
m_propertyCache.clear();
m_accessControlListCache.clear();
m_permissionCache.clear();
}
/**
* Clears all the depending caches when a resource was changed.<p>
*/
protected void clearResourceCache() {
m_resourceCache.clear();
m_resourceListCache.clear();
}
/**
* Clears all the depending caches when a resource was changed.<p>
*
* @param context the current request context
* @param resourcename The name of the changed resource
*/
protected void clearResourceCache(CmsRequestContext context, String resourcename) {
m_resourceCache.remove(getCacheKey(null, context.currentProject(), resourcename));
m_resourceCache.remove(getCacheKey("file", context.currentProject(), resourcename));
m_resourceCache.remove(getCacheKey("path", context.currentProject(), resourcename));
m_resourceCache.remove(getCacheKey("parent", context.currentProject(), resourcename));
m_resourceListCache.clear();
}
/**
* Clears the user cache for the given user.<p>
* @param user the user
*/
protected void clearUserCache(CmsUser user) {
removeUserFromCache(user);
m_resourceListCache.clear();
}
/**
* @see org.opencms.main.I_CmsEventListener#cmsEvent(org.opencms.main.CmsEvent)
*/
public void cmsEvent(CmsEvent event) {
if (org.opencms.main.OpenCms.getLog(this).isDebugEnabled()) {
org.opencms.main.OpenCms.getLog(this).debug("handling event: " + event.getType());
}
switch (event.getType()) {
case I_CmsEventListener.EVENT_PUBLISH_PROJECT:
case I_CmsEventListener.EVENT_CLEAR_CACHES:
this.clearcache();
break;
default:
break;
}
}
/**
* Copies the access control entries of a given resource to another resorce.<p>
*
* Already existing access control entries of this resource are removed.
* Access is granted, if:
* <ul>
* <li>the current user has control permission on the destination resource
* </ul>
*
* @param context the current request context
* @param source the resource which access control entries are copied
* @param dest the resource to which the access control entries are applied
* @throws CmsException if something goes wrong
*/
public void copyAccessControlEntries(CmsRequestContext context, CmsResource source, CmsResource dest) throws CmsException {
checkPermissions(context, dest, I_CmsConstants.C_CONTROL_ACCESS);
ListIterator acEntries = m_userDriver.readAccessControlEntries(context.currentProject(), source.getResourceId(), false).listIterator();
m_userDriver.removeAccessControlEntries(context.currentProject(), dest.getResourceId());
clearAccessControlListCache();
while (acEntries.hasNext()) {
writeAccessControlEntry(context, dest, (CmsAccessControlEntry)acEntries.next());
}
touchResource(context, dest, System.currentTimeMillis(), context.currentUser().getId());
}
/**
* Copies a file in the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the sourceresource</li>
* <li>the user can create the destinationresource</li>
* <li>the destinationresource doesn't exist</li>
* </ul>
*
* @param context the current request context
* @param source the complete m_path of the sourcefile
* @param destination the complete m_path to the destination
* @param lockCopy flag to lock the copied resource
* @param copyAsLink force the copy mode to link
* @param copyMode mode of the copy operation, described how to handle linked resourced during copy.
* Possible values are:
* <ul>
* <li>C_COPY_AS_NEW</li>
* <li>C_COPY_AS_SIBLING</li>
* <li>C_COPY_PRESERVE_SIBLING</li>
* </ul>
* @throws CmsException if operation was not succesful
*/
public void copyFile(CmsRequestContext context, String source, String destination, boolean lockCopy, boolean copyAsLink, int copyMode) throws CmsException {
String destinationFileName = null;
String destinationFolderName = null;
CmsResource newResource = null;
List properties = null;
if (CmsResource.isFolder(destination)) {
copyFolder(context, source, destination, lockCopy, false);
return;
}
// validate the destination path/filename
validFilename(destination.replace('/', 'a'));
// extract the destination folder and filename
destinationFolderName = destination.substring(0, destination.lastIndexOf("/") + 1);
destinationFileName = destination.substring(destination.lastIndexOf("/") + 1, destination.length());
// read the source file and destination parent folder
CmsFile sourceFile = readFile(context, source, false);
CmsFolder destinationFolder = readFolder(context, destinationFolderName);
// check the link mode to see if this resource has to be copied as a link.
// only check this if the override flag "copyAsLink" is not set.
if (!copyAsLink) {
// if we have the copy mode "copy as link, set the override flag to true
if (copyMode == I_CmsConstants.C_COPY_AS_SIBLING) {
copyAsLink = true;
}
// if the mode is "preservre links", we have to check the link counter
if (copyMode == I_CmsConstants.C_COPY_PRESERVE_SIBLING) {
if (sourceFile.getLinkCount() > 1) {
copyAsLink = true;
}
}
}
// checks, if the type is valid, i.e. the user can copy files of this type
// we can't utilize the access guard to do this, since it needs a resource to check
if (!isAdmin(context) && (sourceFile.getType() == CmsResourceTypeXMLTemplate.C_RESOURCE_TYPE_ID || sourceFile.getType() == CmsResourceTypeJsp.C_RESOURCE_TYPE_ID)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] copyFile() " + source, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
// check if the user has read access to the source file and write access to the destination folder
checkPermissions(context, sourceFile, I_CmsConstants.C_READ_ACCESS);
checkPermissions(context, destinationFolder, I_CmsConstants.C_WRITE_ACCESS);
// read the source properties
properties = readPropertyObjects(context, source, null, false);
if (copyAsLink) {
// create a copy of the source file in the destination parent folder
newResource = createSibling(context, destination, source, properties, false);
} else {
// create a new resource in the destination folder
// check the resource flags
int flags = sourceFile.getFlags();
if (sourceFile.isLabeled()) {
// reset "labeled" link flag for new resource
flags &= ~I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
}
// create the file
newResource = m_vfsDriver.createFile(context.currentUser(), context.currentProject(), destinationFileName, flags, destinationFolder, sourceFile.getContents(), getResourceType(sourceFile.getType()));
newResource.setFullResourceName(destination);
// copy the properties
m_vfsDriver.writePropertyObjects(context.currentProject(), newResource, properties);
m_propertyCache.clear();
// copy the access control entries
ListIterator aceList = m_userDriver.readAccessControlEntries(context.currentProject(), sourceFile.getResourceId(), false).listIterator();
while (aceList.hasNext()) {
CmsAccessControlEntry ace = (CmsAccessControlEntry)aceList.next();
m_userDriver.createAccessControlEntry(context.currentProject(), newResource.getResourceId(), ace.getPrincipal(), ace.getPermissions().getAllowedPermissions(), ace.getPermissions().getDeniedPermissions(), ace.getFlags());
}
m_vfsDriver.writeResourceState(context.currentProject(), newResource, C_UPDATE_ALL);
touch(context, destination, sourceFile.getDateLastModified(), sourceFile.getUserLastModified());
if (lockCopy) {
lockResource(context, destination);
}
}
clearAccessControlListCache();
clearResourceCache();
List modifiedResources = (List)new ArrayList();
modifiedResources.add(sourceFile);
modifiedResources.add(newResource);
modifiedResources.add(destinationFolder);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_COPIED, Collections.singletonMap("resources", modifiedResources)));
}
/**
* Copies a folder in the Cms. <p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the sourceresource</li>
* <li>the user can create the destinationresource</li>
* <li>the destinationresource doesn't exist</li>
* </ul>
*
* @param context the current request context
* @param source the complete m_path of the sourcefolder
* @param destination the complete m_path to the destination
* @param lockCopy flag to lock the copied folder
* @param preserveTimestamps true if the timestamps and users of the folder should be kept
* @throws CmsException if operation was not succesful.
*/
public void copyFolder(CmsRequestContext context, String source, String destination, boolean lockCopy, boolean preserveTimestamps) throws CmsException {
long dateLastModified = 0;
long dateCreated = 0;
CmsUUID userLastModified = null;
CmsUUID userCreated = null;
CmsResource newResource = null;
String destinationFoldername = null;
String destinationResourceName = null;
// checks, if the destinateion is valid, if not it throws a exception
validFilename(destination.replace('/', 'a'));
destinationFoldername = destination.substring(0, destination.substring(0, destination.length() - 1).lastIndexOf("/") + 1);
destinationResourceName = destination.substring(destinationFoldername.length());
if (CmsResource.isFolder(destinationResourceName)) {
destinationResourceName = destinationResourceName.substring(0, destinationResourceName.length() - 1);
}
CmsFolder destinationFolder = readFolder(context, destinationFoldername);
CmsFolder sourceFolder = readFolder(context, source);
// check if the user has write access to the destination folder (checking read access to the source is done implicitly by read folder)
checkPermissions(context, destinationFolder, I_CmsConstants.C_WRITE_ACCESS);
// set user and creation timestamps
if (preserveTimestamps) {
dateLastModified = sourceFolder.getDateLastModified();
dateCreated = sourceFolder.getDateCreated();
userLastModified = sourceFolder.getUserLastModified();
userCreated = sourceFolder.getUserCreated();
} else {
dateLastModified = System.currentTimeMillis();
dateCreated = System.currentTimeMillis();
userLastModified = context.currentUser().getId();
userCreated = context.currentUser().getId();
}
// create a copy of the folder
newResource = m_vfsDriver.createFolder(context.currentProject(), destinationFolder.getStructureId(), CmsUUID.getNullUUID(), destinationResourceName, sourceFolder.getFlags(), dateLastModified, userLastModified, dateCreated, userCreated);
newResource.setFullResourceName(destination);
clearResourceCache();
// copy the properties
List properties = readPropertyObjects(context, source, null, false);
m_vfsDriver.writePropertyObjects(context.currentProject(), newResource, properties);
m_propertyCache.clear();
if (preserveTimestamps) {
touch(context, destination, dateLastModified, userLastModified);
}
// copy the access control entries of this resource
ListIterator aceList = getAccessControlEntries(context, sourceFolder, false).listIterator();
while (aceList.hasNext()) {
CmsAccessControlEntry ace = (CmsAccessControlEntry)aceList.next();
m_userDriver.createAccessControlEntry(context.currentProject(), newResource.getResourceId(), ace.getPrincipal(), ace.getPermissions().getAllowedPermissions(), ace.getPermissions().getDeniedPermissions(), ace.getFlags());
}
if (lockCopy) {
lockResource(context, destination);
}
clearAccessControlListCache();
m_resourceListCache.clear();
List modifiedResources = (List)new ArrayList();
modifiedResources.add(sourceFolder);
modifiedResources.add(newResource);
modifiedResources.add(destinationFolder);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_COPIED, Collections.singletonMap("resources", modifiedResources)));
}
/**
* Copies a resource from the online project to a new, specified project.<p>
*
* Copying a resource will copy the file header or folder into the specified
* offline project and set its state to UNCHANGED.
* Access is granted, if:
* <ul>
* <li>the user is the owner of the project</li>
* </ul>
*
* @param context the current request context
* @param resource the name of the resource
* @throws CmsException if operation was not succesful
*/
// TODO: change checking access
public void copyResourceToProject(CmsRequestContext context, String resource) throws CmsException {
// is the current project the onlineproject?
// and is the current user the owner of the project?
// and is the current project state UNLOCKED?
if ((!context.currentProject().isOnlineProject()) && (isManagerOfProject(context)) && (context.currentProject().getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED)) {
// is offlineproject and is owner
// try to read the resource from the offline project, include deleted
CmsResource offlineRes = null;
try {
clearResourceCache();
// must include files marked as deleted for publishing deleted resources
//offlineRes = readFileHeaderInProject(context, context.currentProject().getId(), resource, true);
offlineRes = readFileHeader(context, resource, true);
if (!isInsideCurrentProject(context, offlineRes)) {
offlineRes = null;
}
} catch (CmsException exc) {
// if the resource does not exist in the offlineProject - it's ok
}
// create the projectresource only if the resource is not in the current project
if ((offlineRes == null) || (offlineRes.getProjectLastModified() != context.currentProject().getId())) {
// check if there are already any subfolders of this resource
if (CmsResource.isFolder(resource)) {
List projectResources = m_projectDriver.readProjectResources(context.currentProject());
for (int i = 0; i < projectResources.size(); i++) {
String resname = (String)projectResources.get(i);
if (resname.startsWith(resource)) {
// delete the existing project resource first
m_projectDriver.deleteProjectResource(context.currentProject().getId(), resname);
}
}
}
try {
m_projectDriver.createProjectResource(context.currentProject().getId(), resource, null);
} catch (CmsException exc) {
// if the subfolder exists already - all is ok
} finally {
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROJECT_MODIFIED, Collections.singletonMap("project", context.currentProject())));
}
}
} else {
// no changes on the onlineproject!
throw new CmsSecurityException("[" + this.getClass().getName() + "] " + context.currentProject().getName(), CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Moves a resource to the lost and found folder.<p>
*
* @param context the current request context
* @param resourcename the complete path of the sourcefile.
* @param copyResource true, if the resource should be copied to its destination inside the lost+found folder
* @return location of the moved resource
* @throws CmsException if the user has not the rights to move this resource,
* or if the file couldn't be moved.
*/
public String copyToLostAndFound(CmsRequestContext context, String resourcename, boolean copyResource) throws CmsException {
String siteRoot = context.getSiteRoot();
Stack storage = new Stack();
context.setSiteRoot("/");
String destination = I_CmsConstants.C_VFS_LOST_AND_FOUND + resourcename;
// create the require folders if nescessary
String des = destination;
// collect all folders...
try {
while (des.indexOf("/") == 0) {
des = des.substring(0, des.lastIndexOf("/"));
storage.push(des.concat("/"));
}
// ...now create them....
while (storage.size() != 0) {
des = (String)storage.pop();
try {
readFolder(context, des);
} catch (Exception e1) {
// the folder is not existing, so create it
createFolder(context, des, Collections.EMPTY_LIST);
}
}
// check if this resource name does already exist
// if so add a psotfix to the name
des = destination;
int postfix = 1;
boolean found = true;
while (found) {
try {
// try to read the file.....
found = true;
readFileHeader(context, des);
// ....it's there, so add a postfix and try again
String path = destination.substring(0, destination.lastIndexOf("/") + 1);
String filename = destination.substring(destination.lastIndexOf("/") + 1, destination.length());
des = path;
if (filename.lastIndexOf(".") > 0) {
des += filename.substring(0, filename.lastIndexOf("."));
} else {
des += filename;
}
des += "_" + postfix;
if (filename.lastIndexOf(".") > 0) {
des += filename.substring(filename.lastIndexOf("."), filename.length());
}
postfix++;
} catch (CmsException e3) {
// the file does not exist, so we can use this filename
found = false;
}
}
destination = des;
if (copyResource) {
// move the existing resource to the lost and foud folder
moveResource(context, resourcename, destination);
}
} catch (CmsException e2) {
throw e2;
} finally {
// set the site root to the old value again
context.setSiteRoot(siteRoot);
}
return destination;
}
/**
* Counts the locked resources in this project.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param context the current request context
* @param id the id of the project
* @return the amount of locked resources in this project.
* @throws CmsException if something goes wrong
*/
public int countLockedResources(CmsRequestContext context, int id) throws CmsException {
// read the project.
CmsProject project = readProject(id);
// check the security
if (isAdmin(context) || isManagerOfProject(context) || (project.getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED)) {
// count locks
return m_lockManager.countExclusiveLocksInProject(project);
} else if (!isAdmin(context) && !isManagerOfProject(context)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] countLockedResources()", CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] countLockedResources()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Counts the locked resources in a given folder.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param context the current request context
* @param foldername the folder to search in
* @return the amount of locked resources in this project
* @throws CmsException if something goes wrong
*/
public int countLockedResources(CmsRequestContext context, String foldername) throws CmsException {
// check the security
if (isAdmin(context) || isManagerOfProject(context) || (context.currentProject().getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED)) {
// count locks
return m_lockManager.countExclusiveLocksInFolder(foldername);
} else if (!isAdmin(context) && !isManagerOfProject(context)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] countLockedResources()", CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] countLockedResources()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Creates a project for the direct publish.<p>
*
* Only the users which are in the admin or projectleader-group of the current project are granted.
*
* @param context the current context (user/project)
* @param name The name of the project to read
* @param description The description for the new project
* @param groupname the group to be set
* @param managergroupname the managergroup to be set
* @param projecttype the type of the project
* @return the direct publish project
* @throws CmsException if something goes wrong
*/
/*
public CmsProject createDirectPublishProject(CmsRequestContext context, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException {
if (isAdmin(context) || isManagerOfProject(context)) {
if (I_CmsConstants.C_PROJECT_ONLINE.equals(name)) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// read the needed groups from the cms
CmsGroup group = readGroup(context, groupname);
CmsGroup managergroup = readGroup(context, managergroupname);
return m_projectDriver.createProject(context.currentUser(), group, managergroup, noTask, name, description, I_CmsConstants.C_PROJECT_STATE_UNLOCKED, projecttype, null);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createDirectPublishProject()", CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
}
}
*/
/**
* Creates a new file with the given content and resourcetype.<p>
*
* Files can only be created in an offline project, the state of the new file
* is set to NEW (2). <br>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the folder-resource is not locked by another user</li>
* <li>the file doesn't exist</li>
* </ul>
*
* @param context the current request context
* @param newFileName the name of the new file
* @param contents the contents of the new file
* @param type the name of the resourcetype of the new file
* @param propertyinfos a Hashtable of propertyinfos, that should be set for this folder.
* The keys for this Hashtable are the names for propertydefinitions, the values are
* the values for the propertyinfos.
* @return the created file.
* @throws CmsException if operation was not succesful.
*/
public CmsFile createFile(CmsRequestContext context, String newFileName, byte[] contents, String type, List propertyinfos) throws CmsException {
// extract folder information
String folderName = newFileName.substring(0, newFileName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR, newFileName.length()) + 1);
String resourceName = newFileName.substring(folderName.length(), newFileName.length());
// checks, if the filename is valid, if not it throws a exception
validFilename(resourceName);
// checks, if the type is valid, i.e. the user can create files of this type
// we can't utilize the access guard to do this, since it needs a resource to check
if (!isAdmin(context) && (CmsResourceTypeXMLTemplate.C_RESOURCE_TYPE_NAME.equals(type) || CmsResourceTypeJsp.C_RESOURCE_TYPE_NAME.equals(type))) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createFile() " + resourceName, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
CmsFolder parentFolder = readFolder(context, folderName);
// check if the user has write access to the destination folder
checkPermissions(context, parentFolder, I_CmsConstants.C_WRITE_ACCESS);
// create and return the file.
CmsFile newFile = m_vfsDriver.createFile(context.currentUser(), context.currentProject(), resourceName, 0, parentFolder, contents, getResourceType(type));
newFile.setFullResourceName(newFileName);
// write the metainfos
//writeProperties(context, newFileName, propertyinfos);
m_vfsDriver.writePropertyObjects(context.currentProject(), newFile, propertyinfos);
m_propertyCache.clear();
contents = null;
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_CREATED, Collections.singletonMap("resource", newFile)));
return newFile;
}
/**
* Creates a new folder.<p>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is not locked by another user</li>
* </ul>
*
* @param context the current request context
* @param newFolderName the name of the new folder (No pathinformation allowed).
* @param propertyinfos a Hashtable of propertyinfos, that should be set for this folder.
* The keys for this Hashtable are the names for propertydefinitions, the values are
* the values for the propertyinfos.
* @return the created folder.
* @throws CmsException for missing propertyinfos, for worng propertydefs
* or if the filename is not valid. The CmsException will also be thrown, if the
* user has not the rights for this resource.
*/
public CmsFolder createFolder(CmsRequestContext context, String newFolderName, List propertyinfos) throws CmsException {
// append I_CmsConstants.C_FOLDER_SEPARATOR if required
if (!newFolderName.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
newFolderName += I_CmsConstants.C_FOLDER_SEPARATOR;
}
// extract folder information
String folderName = newFolderName.substring(0, newFolderName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR, newFolderName.length() - 2) + 1);
String resourceName = newFolderName.substring(folderName.length(), newFolderName.length() - 1);
// checks, if the filename is valid, if not it throws a exception
validFilename(resourceName);
CmsFolder cmsFolder = readFolder(context, folderName);
// check if the user has write access to the destination folder
checkPermissions(context, cmsFolder, I_CmsConstants.C_WRITE_ACCESS);
// create the folder.
CmsFolder newFolder = m_vfsDriver.createFolder(context.currentProject(), cmsFolder.getStructureId(), CmsUUID.getNullUUID(), resourceName, 0, 0, context.currentUser().getId(), 0, context.currentUser().getId());
newFolder.setFullResourceName(newFolderName);
// write metainfos for the folder
m_vfsDriver.writePropertyObjects(context.currentProject(), newFolder, propertyinfos);
m_propertyCache.clear();
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_CREATED, Collections.singletonMap("resource", newFolder)));
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROJECT_MODIFIED, Collections.singletonMap("project", context.currentProject())));
// return the folder
return newFolder;
}
/**
* Creates a new sibling of the target resource.<p>
*
* @param context the context
* @param linkName the name of the link
* @param targetName the name of the target
* @param linkProperties the properties to attach via the the link
* @param lockResource true, if the new created link should be initially locked
* @return the new resource
* @throws CmsException if something goes wrong
*/
public CmsResource createSibling(CmsRequestContext context, String linkName, String targetName, List linkProperties, boolean lockResource) throws CmsException {
CmsResource targetResource = null;
CmsResource linkResource = null;
String parentFolderName = null;
CmsFolder parentFolder = null;
String resourceName = null;
parentFolderName = linkName.substring(0, linkName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR) + 1);
resourceName = linkName.substring(linkName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR) + 1, linkName.length());
// read the target resource
targetResource = this.readFileHeader(context, targetName);
if (targetResource.isFolder()) {
throw new CmsException("Setting links on folders is not supported");
}
// read the parent folder
parentFolder = this.readFolder(context, parentFolderName, false);
// for the parent folder is write access required
checkPermissions(context, parentFolder, I_CmsConstants.C_WRITE_ACCESS);
// construct a dummy that is written to the db
linkResource = new CmsResource(new CmsUUID(), targetResource.getResourceId(), parentFolder.getStructureId(), CmsUUID.getNullUUID(), resourceName, targetResource.getType(), targetResource.getFlags(), context.currentProject().getId(), org.opencms.main.I_CmsConstants.C_STATE_NEW, targetResource.getLoaderId(), System.currentTimeMillis(), context.currentUser().getId(), System.currentTimeMillis(), context.currentUser().getId(), 0, targetResource.getLinkCount() + 1);
// check if the resource has to be labeled now
if (labelResource(context, targetResource, linkName, 1)) {
int flags = linkResource.getFlags();
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
linkResource.setFlags(flags);
}
// setting the full resource name twice here looks crude but is essential!
linkResource.setFullResourceName(linkName);
linkResource = m_vfsDriver.createSibling(context.currentProject(), linkResource, context.currentUser().getId(), parentFolder.getStructureId(), resourceName);
linkResource.setFullResourceName(linkName);
// mark the new sibling as modified in the current project
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), linkResource);
if (linkProperties == null) {
// "empty" properties are represented by an empty property map
linkProperties = Collections.EMPTY_LIST;
}
// write its properties
CmsProperty.setAutoCreatePropertyDefinitions(linkProperties, true);
m_vfsDriver.writePropertyObjects(context.currentProject(), linkResource, linkProperties);
// if the source
clearResourceCache();
m_propertyCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", parentFolder)));
if (lockResource) {
// lock the resource
lockResource(context, linkName);
}
return linkResource;
}
/**
* Add a new group to the Cms.<p>
*
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param id the id of the new group
* @param name the name of the new group
* @param description the description for the new group
* @param flags the flags for the new group
* @param parent the name of the parent group (or null)
* @return new created group
* @throws CmsException if operation was not successfull.
*/
public CmsGroup createGroup(CmsRequestContext context, CmsUUID id, String name, String description, int flags, String parent) throws CmsException {
// Check the security
if (isAdmin(context)) {
name = name.trim();
validFilename(name);
// check the lenght of the groupname
if (name.length() > 1) {
return m_userDriver.createGroup(id, name, description, flags, parent, null);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createGroup() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Add a new group to the Cms.<p>
*
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param name the name of the new group
* @param description the description for the new group
* @param flags the flags for the new group
* @param parent the name of the parent group (or null)
* @return new created group
* @throws CmsException if operation was not successfull.
*/
public CmsGroup createGroup(CmsRequestContext context, String name, String description, int flags, String parent) throws CmsException {
return createGroup(context, new CmsUUID(), name, description, flags, parent);
}
/**
* Add a new group to the Cms.<p>
*
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param id the id of the new group
* @param name the name of the new group
* @param description the description for the new group
* @param flags the flags for the new group
* @param parent the name of the parent group (or null)
* @return new created group
* @throws CmsException if operation was not successfull
*/
public CmsGroup createGroup(CmsRequestContext context, String id, String name, String description, int flags, String parent) throws CmsException {
return createGroup(context, new CmsUUID(id), name, description, flags, parent);
}
/**
* Creates a new project for task handling.<p>
*
* @param context the current request context
* @param projectName name of the project
* @param roleName usergroup for the project
* @param timeout time when the Project must finished
* @param priority priority for the Project
* @return The new task project
*
* @throws CmsException if something goes wrong
*/
public CmsTask createProject(CmsRequestContext context, String projectName, String roleName, long timeout, int priority) throws CmsException {
CmsGroup role = null;
// read the role
if (roleName != null && !roleName.equals("")) {
role = readGroup(roleName);
}
// create the timestamp
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
return m_workflowDriver.createTask(0, 0, 1, // standart project type,
context.currentUser().getId(), context.currentUser().getId(), role.getId(), projectName, now, timestamp, priority);
}
/**
* Creates a project.<p>
*
* Only the users which are in the admin or projectmanager groups are granted.<p>
*
* @param context the current request context
* @param name the name of the project to create
* @param description the description of the project
* @param groupname the project user group to be set
* @param managergroupname the project manager group to be set
* @param projecttype type the type of the project
* @return the created project
* @throws CmsException if something goes wrong
*/
public CmsProject createProject(CmsRequestContext context, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException {
if (isAdmin(context) || isProjectManager(context)) {
if (I_CmsConstants.C_PROJECT_ONLINE.equals(name)) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// read the needed groups from the cms
CmsGroup group = readGroup(groupname);
CmsGroup managergroup = readGroup(managergroupname);
// create a new task for the project
CmsTask task = createProject(context, name, group.getName(), System.currentTimeMillis(), I_CmsConstants.C_TASK_PRIORITY_NORMAL);
return m_projectDriver.createProject(context.currentUser(), group, managergroup, task, name, description, I_CmsConstants.C_PROJECT_STATE_UNLOCKED, projecttype, null);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createProject()", CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
}
}
/**
* Creates the propertydefinition for the resource type.<p>
*
* Only the admin can do this.
*
* @param context the current request context
* @param name the name of the propertydefinition to overwrite
* @param resourcetype the name of the resource-type for the propertydefinition
* @return the created propertydefinition
* @throws CmsException if something goes wrong.
*/
public CmsPropertydefinition createPropertydefinition(CmsRequestContext context, String name, int resourcetype) throws CmsException {
CmsPropertydefinition propertyDefinition = null;
if (isAdmin(context)) {
name = name.trim();
validFilename(name);
try {
propertyDefinition = m_vfsDriver.readPropertyDefinition(name, context.currentProject().getId(), resourcetype);
} catch (CmsException e) {
propertyDefinition = m_vfsDriver.createPropertyDefinition(name, context.currentProject().getId(), resourcetype);
}
try {
m_vfsDriver.readPropertyDefinition(name, I_CmsConstants.C_PROJECT_ONLINE_ID, resourcetype);
} catch (CmsException e) {
m_vfsDriver.createPropertyDefinition(name, I_CmsConstants.C_PROJECT_ONLINE_ID, resourcetype);
}
try {
m_backupDriver.readBackupPropertyDefinition(name, resourcetype);
} catch (CmsException e) {
m_backupDriver.createBackupPropertyDefinition(name, resourcetype);
}
//propertyDefinition = m_vfsDriver.createPropertyDefinition(name, context.currentProject().getId(), resourcetype));
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createPropertydefinition() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
return propertyDefinition;
}
/**
* Creates a new task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param agentName username who will edit the task
* @param roleName usergroupname for the task
* @param taskname name of the task
* @param timeout time when the task must finished
* @param priority Id for the priority
* @return A new Task Object
* @throws CmsException if something goes wrong
*/
public CmsTask createTask(CmsRequestContext context, String agentName, String roleName, String taskname, long timeout, int priority) throws CmsException {
CmsGroup role = m_userDriver.readGroup(roleName);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
CmsUUID agentId = CmsUUID.getNullUUID();
validTaskname(taskname); // check for valid Filename
try {
agentId = readUser(agentName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER).getId();
} catch (Exception e) {
// ignore that this user doesn't exist and create a task for the role
}
return m_workflowDriver.createTask(context.currentProject().getTaskId(), context.currentProject().getTaskId(), 1, // standart Task Type
context.currentUser().getId(), agentId, role.getId(), taskname, now, timestamp, priority);
}
/**
* Creates a new task.<p>
*
* All users are granted.
*
* @param currentUser the current user
* @param projectid the current project id
* @param agentName user who will edit the task
* @param roleName usergroup for the task
* @param taskName name of the task
* @param taskType type of the task
* @param taskComment description of the task
* @param timeout time when the task must finished
* @param priority Id for the priority
* @return a new task object
* @throws CmsException if something goes wrong.
*/
public CmsTask createTask(CmsUser currentUser, int projectid, String agentName, String roleName, String taskName, String taskComment, int taskType, long timeout, int priority) throws CmsException {
CmsUser agent = readUser(agentName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
CmsGroup role = m_userDriver.readGroup(roleName);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
validTaskname(taskName); // check for valid Filename
CmsTask task = m_workflowDriver.createTask(projectid, projectid, taskType, currentUser.getId(), agent.getId(), role.getId(), taskName, now, timestamp, priority);
if (taskComment != null && !taskComment.equals("")) {
m_workflowDriver.writeTaskLog(task.getId(), currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), taskComment, I_CmsConstants.C_TASKLOG_USER);
}
return task;
}
/**
* Creates the project for the temporary files.<p>
*
* Only the users which are in the admin or projectleader-group are granted.
*
* @param context the current request context
* @return the new tempfile project
* @throws CmsException if something goes wrong
*/
public CmsProject createTempfileProject(CmsRequestContext context) throws CmsException {
if (isAdmin(context)) {
// read the needed groups from the cms
CmsGroup group = readGroup(OpenCms.getDefaultUsers().getGroupUsers());
CmsGroup managergroup = readGroup(OpenCms.getDefaultUsers().getGroupAdministrators());
// create a new task for the project
CmsTask task = createProject(context, CmsWorkplaceManager.C_TEMP_FILE_PROJECT_NAME, group.getName(), System.currentTimeMillis(), I_CmsConstants.C_TASK_PRIORITY_NORMAL);
CmsProject tempProject = m_projectDriver.createProject(context.currentUser(), group, managergroup, task, CmsWorkplaceManager.C_TEMP_FILE_PROJECT_NAME, CmsWorkplaceManager.C_TEMP_FILE_PROJECT_DESCRIPTION, I_CmsConstants.C_PROJECT_STATE_INVISIBLE, I_CmsConstants.C_PROJECT_STATE_INVISIBLE, null);
m_projectDriver.createProjectResource(tempProject.getId(), "/", null);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROJECT_MODIFIED, Collections.singletonMap("project", tempProject)));
return tempProject;
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createTempfileProject() ", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Creates a new sibling of the target resource.<p>
*
* @param context the context
* @param linkName the name of the link
* @param targetName the name of the target
* @param linkProperties the properties to attach via the the link
* @param lockResource true, if the new created link should be initially locked
* @return the new resource
* @throws CmsException if something goes wrong
*/
public CmsResource createVfsLink(CmsRequestContext context, String linkName, String targetName, List linkProperties, boolean lockResource) throws CmsException {
CmsResource targetResource = null;
CmsResource linkResource = null;
String parentFolderName = null;
CmsFolder parentFolder = null;
String resourceName = null;
parentFolderName = linkName.substring(0, linkName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR) + 1);
resourceName = linkName.substring(linkName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR) + 1, linkName.length());
// read the target resource
targetResource = this.readFileHeader(context, targetName);
if (targetResource.isFolder()) {
throw new CmsException("Setting links on folders is not supported");
}
// read the parent folder
parentFolder = this.readFolder(context, parentFolderName, false);
// for the parent folder is write access required
checkPermissions(context, parentFolder, I_CmsConstants.C_WRITE_ACCESS);
// construct a dummy that is written to the db
linkResource = new CmsResource(new CmsUUID(), targetResource.getResourceId(), parentFolder.getStructureId(), CmsUUID.getNullUUID(), resourceName, targetResource.getType(), targetResource.getFlags(), context.currentProject().getId(), org.opencms.main.I_CmsConstants.C_STATE_NEW, targetResource.getLoaderId(), System.currentTimeMillis(), context.currentUser().getId(), System.currentTimeMillis(), context.currentUser().getId(), 0, targetResource.getLinkCount() + 1);
// check if the resource has to be labeled now
if (labelResource(context, targetResource, linkName, 1)) {
int flags = linkResource.getFlags();
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
linkResource.setFlags(flags);
}
// setting the full resource name twice here looks crude but is essential!
linkResource.setFullResourceName(linkName);
linkResource = m_vfsDriver.createSibling(context.currentProject(), linkResource, context.currentUser().getId(), parentFolder.getStructureId(), resourceName);
linkResource.setFullResourceName(linkName);
// mark the new sibling as modified in the current project
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), linkResource);
if (linkProperties == null) {
// "empty" properties are represented by an empty property map
linkProperties = Collections.EMPTY_LIST;
}
// write its properties
m_vfsDriver.writePropertyObjects(context.currentProject(), linkResource, linkProperties);
// if the source
clearResourceCache();
m_propertyCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", parentFolder)));
if (lockResource) {
// lock the resource
lockResource(context, linkName);
}
return linkResource;
}
/**
* Marks all access control entries belonging to a resource as deleted.<p>
*
* Access is granted, if:
* <ul>
* <li>the current user has write permission on the resource
* </ul>
*
* @param context the current request context
* @param resource the resource
* @throws CmsException if something goes wrong
*/
private void deleteAllAccessControlEntries(CmsRequestContext context, CmsResource resource) throws CmsException {
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
m_userDriver.deleteAccessControlEntries(context.currentProject(), resource.getResourceId());
// not here
// touchResource(context, resource, System.currentTimeMillis());
clearAccessControlListCache();
}
/**
* Deletes all propertyinformation for a file or folder.<p>
*
* Only the user is granted, who has the right to write the resource.
*
* @param context the current request context
* @param resourceName the name of the resource of which the propertyinformations have to be deleted.
* @throws CmsException if operation was not succesful
*/
public void deleteAllProperties(CmsRequestContext context, String resourceName) throws CmsException {
CmsResource resource = null;
try {
// read the resource
resource = readFileHeader(context, resourceName);
// check the security
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
//delete all Properties
m_vfsDriver.deleteProperties(context.currentProject().getId(), resource);
} finally {
// clear the driver manager cache
m_propertyCache.clear();
// fire an event that all properties of a resource have been deleted
OpenCms.fireCmsEvent(new CmsEvent(
new CmsObject(),
I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED,
Collections.singletonMap("resource", resource)));
}
}
/**
* Deletes all backup versions of a single resource.<p>
*
* @param res the resource to delete all backups from
* @throws CmsException if operation was not succesful
*/
public void deleteBackup(CmsResource res) throws CmsException {
// we need a valid CmsBackupResource, so get all backup file headers of the
// requested resource
List backupFileHeaders=m_backupDriver.readBackupFileHeaders(res.getResourceId());
// check if we have some results
if (backupFileHeaders.size()>0) {
// get the first backup resource
CmsBackupResource backupResource=(CmsBackupResource)backupFileHeaders.get(0);
// create a timestamp slightly in the future
long timestamp=System.currentTimeMillis()+100000;
// get the maximum tag id and add ne to include the current publish process as well
int maxTag = m_backupDriver.readBackupProjectTag(timestamp)+1;
int resVersions = m_backupDriver.readBackupMaxVersion(res.getResourceId());
// delete the backups
m_backupDriver.deleteBackup(backupResource, maxTag, resVersions);
}
}
/**
* Deletes the versions from the backup tables that are older then the given timestamp and/or number of remaining versions.<p>
*
* The number of verions always wins, i.e. if the given timestamp would delete more versions than given in the
* versions parameter, the timestamp will be ignored.
* Deletion will delete file header, content and properties.
*
* @param context the current request context
* @param timestamp the max age of backup resources
* @param versions the number of remaining backup versions for each resource
* @param report the report for output logging
* @throws CmsException if operation was not succesful
*/
public void deleteBackups(CmsRequestContext context, long timestamp, int versions, I_CmsReport report) throws CmsException {
if (isAdmin(context)) {
// get all resources from the backup table
// do only get one version per resource
List allBackupFiles = m_backupDriver.readBackupFileHeaders();
int counter = 1;
int size = allBackupFiles.size();
// get the tagId of the oldest Backupproject which will be kept in the database
int maxTag = m_backupDriver.readBackupProjectTag(timestamp);
Iterator i = allBackupFiles.iterator();
while (i.hasNext()) {
// now check get a single backup resource
CmsBackupResource res = (CmsBackupResource)i.next();
// get the full resource path if not present
if (!res.hasFullResourceName()) {
res.setFullResourceName(readPath(context, res, true));
}
report.print("( " + counter + " / " + size + " ) ", I_CmsReport.C_FORMAT_NOTE);
report.print(report.key("report.history.checking"), I_CmsReport.C_FORMAT_NOTE);
report.print(res.getRootPath() + " ");
// now delete all versions of this resource that have more than the maximun number
// of allowed versions and which are older then the maximum backup date
int resVersions = m_backupDriver.readBackupMaxVersion(res.getResourceId());
int versionsToDelete = resVersions - versions;
// now we know which backup versions must be deleted, so remove them now
if (versionsToDelete > 0) {
report.print(report.key("report.history.deleting") + report.key("report.dots"));
m_backupDriver.deleteBackup(res, maxTag, versionsToDelete);
} else {
report.print(report.key("report.history.nothing") + report.key("report.dots"));
}
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
counter++;
//TODO: delete the old backup projects as well
m_projectDriver.deletePublishHistory(context.currentProject().getId(), maxTag);
}
}
}
/**
* Deletes a file in the Cms.<p>
*
* A file can only be deleteed in an offline project.
* A file is deleted by setting its state to DELETED (3).
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callinUser</li>
* </ul>
*
* @param context the current request context
* @param filename the complete m_path of the file
* @param deleteOption flag to delete siblings as well
*
* @throws CmsException if operation was not succesful.
*/
public void deleteFile(CmsRequestContext context, String filename, int deleteOption) throws CmsException {
List resources = (List)new ArrayList();
CmsResource currentResource = null;
CmsLock currentLock = null;
CmsResource resource = null;
Iterator i = null;
boolean existsOnline = false;
// TODO set the flag deleteOption in all calling methods correct
// read the resource to delete/remove
resource = readFileHeader(context, filename, false);
// upgrade a potential inherited, non-shared lock into an exclusive lock
currentLock = getLock(context, filename);
if (currentLock.getType() == CmsLock.C_TYPE_INHERITED) {
lockResource(context, filename);
}
// add the resource itself to the list of all resources that get deleted/removed
resources.add(resource);
// if selected, add all links pointing to this resource to the list of files that get deleted/removed
if (deleteOption == I_CmsConstants.C_DELETE_OPTION_DELETE_SIBLINGS) {
resources.addAll(readSiblings(context, filename, false, false));
}
// ensure that each link pointing to the resource is unlocked or locked by the current user
i = resources.iterator();
while (i.hasNext()) {
currentResource = (CmsResource)i.next();
currentLock = getLock(context, currentResource);
if (!currentLock.equals(CmsLock.getNullLock()) && !currentLock.getUserId().equals(context.currentUser().getId())) {
// the resource is locked by a user different from the current user
int exceptionType = currentLock.getUserId().equals(context.currentUser().getId()) ? CmsLockException.C_RESOURCE_LOCKED_BY_CURRENT_USER : CmsLockException.C_RESOURCE_LOCKED_BY_OTHER_USER;
throw new CmsLockException("VFS link " + currentResource.getRootPath() + " pointing to " + filename + " is locked by another user!", exceptionType);
}
}
// delete/remove all collected resources
i = resources.iterator();
while (i.hasNext()) {
existsOnline = false;
currentResource = (CmsResource)i.next();
// try to delete/remove the resource only if the user has write access to the resource
if (hasPermissions(context, currentResource, I_CmsConstants.C_WRITE_ACCESS, false)) {
try {
// try to read the corresponding online resource to decide if the resource should be either removed or deleted
readFileHeaderInProject(I_CmsConstants.C_PROJECT_ONLINE_ID, currentResource.getRootPath(), false);
existsOnline = true;
} catch (CmsException exc) {
existsOnline = false;
}
m_lockManager.removeResource(this, context, currentResource.getRootPath(), true);
if (!existsOnline) {
// remove the properties
deleteAllProperties(context, currentResource.getRootPath());
// remove the access control entries
m_userDriver.removeAccessControlEntries(context.currentProject(), currentResource.getResourceId());
// the resource doesn't exist online => remove the file
if (currentResource.isLabeled() && !labelResource(context, currentResource, null, 2)) {
// update the resource flags to "unlabel" the other siblings
int flags = currentResource.getFlags();
flags &= ~I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
currentResource.setFlags(flags);
}
m_vfsDriver.removeFile(context.currentProject(), currentResource, true);
} else {
// delete the access control entries
deleteAllAccessControlEntries(context, currentResource);
// the resource exists online => mark the file as deleted
//m_vfsDriver.deleteFile(context.currentProject(), currentResource);
currentResource.setState(I_CmsConstants.C_STATE_DELETED);
m_vfsDriver.writeResourceState(context.currentProject(), currentResource, C_UPDATE_STRUCTURE_STATE);
// add the project id as a property, this is later used for publishing
CmsProperty property = new CmsProperty();
property.setKey(I_CmsConstants.C_PROPERTY_INTERNAL);
property.setStructureValue("" + context.currentProject().getId());
m_vfsDriver.writePropertyObject(context.currentProject(), currentResource, property);
// TODO: still necessary after we have the property?
// update the project ID
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), currentResource);
}
}
}
// flush all caches
clearAccessControlListCache();
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_DELETED, Collections.singletonMap("resources", resources)));
}
/**
* Deletes a folder in the Cms.<p>
*
* Only folders in an offline Project can be deleted. A folder is deleted by
* setting its state to DELETED (3).
* In its current implmentation, this method can ONLY delete empty folders.
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read and write this resource and all subresources</li>
* <li>the resource is not locked</li>
* </ul>
*
* @param context the current request context
* @param foldername the complete m_path of the folder
*
* @throws CmsException if operation was not succesful
*/
public void deleteFolder(CmsRequestContext context, String foldername) throws CmsException {
CmsResource onlineFolder;
// TODO: "/" is currently used inconsistent !!!
if (!CmsResource.isFolder(foldername)) {
foldername = foldername.concat("/");
}
// read the folder, that should be deleted
CmsFolder cmsFolder = readFolder(context, foldername);
try {
onlineFolder = readFolderInProject(I_CmsConstants.C_PROJECT_ONLINE_ID, foldername);
} catch (CmsException exc) {
// the file dosent exist
onlineFolder = null;
}
// check if the user has write access to the folder
checkPermissions(context, cmsFolder, I_CmsConstants.C_WRITE_ACCESS);
m_lockManager.removeResource(this, context, foldername, true);
// write-acces was granted - delete the folder and metainfos.
if (onlineFolder == null) {
// the onlinefile dosent exist => remove the file realy!
deleteAllProperties(context, foldername);
m_vfsDriver.removeFolder(context.currentProject(), cmsFolder);
// remove the access control entries
m_userDriver.removeAccessControlEntries(context.currentProject(), cmsFolder.getResourceId());
} else {
// m_vfsDriver.deleteFolder(context.currentProject(), cmsFolder);
// add the project id as a property, this is later used for publishing
CmsProperty property = new CmsProperty();
property.setKey(I_CmsConstants.C_PROPERTY_INTERNAL);
property.setStructureValue("" + context.currentProject().getId());
m_vfsDriver.writePropertyObject(context.currentProject(), cmsFolder, property);
cmsFolder.setState(I_CmsConstants.C_STATE_DELETED);
m_vfsDriver.writeResourceState(context.currentProject(), cmsFolder, C_UPDATE_STRUCTURE_STATE);
// delete the access control entries
deleteAllAccessControlEntries(context, cmsFolder);
// update the project ID
// TODO: still nescessary?
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), cmsFolder);
}
// update cache
clearAccessControlListCache();
clearResourceCache();
List resources = (List) new ArrayList();
resources.add(cmsFolder);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_DELETED, Collections.singletonMap("resources", resources)));
}
/**
* Delete a group from the Cms.<p>
*
* Only groups that contain no subgroups can be deleted.
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param delgroup the name of the group that is to be deleted
* @throws CmsException if operation was not succesfull
*/
public void deleteGroup(CmsRequestContext context, String delgroup) throws CmsException {
// Check the security
if (isAdmin(context)) {
Vector childs = null;
Vector users = null;
// get all child groups of the group
childs = getChild(context, delgroup);
// get all users in this group
users = getUsersOfGroup(context, delgroup);
// delete group only if it has no childs and there are no users in this group.
if ((childs == null) && ((users == null) || (users.size() == 0))) {
m_userDriver.deleteGroup(delgroup);
m_groupCache.remove(new CacheId(delgroup));
} else {
throw new CmsException(delgroup, CmsException.C_GROUP_NOT_EMPTY);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteGroup() " + delgroup, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Deletes a project.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param context the current request context
* @param projectId the id of the project to be published
*
* @throws CmsException if something goes wrong
*/
public void deleteProject(CmsRequestContext context, int projectId) throws CmsException {
Vector deletedFolders = new Vector();
// read the project that should be deleted.
CmsProject deleteProject = readProject(projectId);
if ((isAdmin(context) || isManagerOfProject(context)) && (projectId != I_CmsConstants.C_PROJECT_ONLINE_ID)) {
// List allFiles = m_vfsDriver.readFiles(deleteProject.getId(), false, true);
// List allFolders = m_vfsDriver.readFolders(deleteProject, false, true);
List allFiles = readChangedResourcesInsideProject(context, projectId, 1);
List allFolders = readChangedResourcesInsideProject(context, projectId, CmsResourceTypeFolder.C_RESOURCE_TYPE_ID);
// first delete files or undo changes in files
for (int i = 0; i < allFiles.size(); i++) {
CmsFile currentFile = (CmsFile)allFiles.get(i);
String currentResourceName = readPath(context, currentFile, true);
if (currentFile.getState() == I_CmsConstants.C_STATE_NEW) {
CmsLock lock = getLock(context, currentFile);
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// delete the properties
m_vfsDriver.deleteProperties(projectId, currentFile);
// delete the file
m_vfsDriver.removeFile(context.currentProject(), currentFile, true);
// remove the access control entries
m_userDriver.removeAccessControlEntries(context.currentProject(), currentFile.getResourceId());
} else if (currentFile.getState() == I_CmsConstants.C_STATE_CHANGED) {
CmsLock lock = getLock(context, currentFile);
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// undo all changes in the file
undoChanges(context, currentResourceName);
} else if (currentFile.getState() == I_CmsConstants.C_STATE_DELETED) {
// first undelete the file
undeleteResource(context, currentResourceName);
CmsLock lock = getLock(context, currentFile);
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// then undo all changes in the file
undoChanges(context, currentResourceName);
}
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", currentFile)));
}
// now delete folders or undo changes in folders
for (int i = 0; i < allFolders.size(); i++) {
CmsFolder currentFolder = (CmsFolder)allFolders.get(i);
String currentResourceName = readPath(context, currentFolder, true);
CmsLock lock = getLock(context, currentFolder);
if (currentFolder.getState() == I_CmsConstants.C_STATE_NEW) {
// delete the properties
m_vfsDriver.deleteProperties(projectId, currentFolder);
// add the folder to the vector of folders that has to be deleted
deletedFolders.addElement(currentFolder);
} else if (currentFolder.getState() == I_CmsConstants.C_STATE_CHANGED) {
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// undo all changes in the folder
undoChanges(context, currentResourceName);
} else if (currentFolder.getState() == I_CmsConstants.C_STATE_DELETED) {
// undelete the folder
undeleteResource(context, currentResourceName);
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// then undo all changes in the folder
undoChanges(context, currentResourceName);
}
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", currentFolder)));
}
// now delete the folders in the vector
for (int i = deletedFolders.size() - 1; i > -1; i--) {
CmsFolder delFolder = ((CmsFolder)deletedFolders.elementAt(i));
m_vfsDriver.removeFolder(context.currentProject(), delFolder);
// remove the access control entries
m_userDriver.removeAccessControlEntries(context.currentProject(), delFolder.getResourceId());
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", delFolder)));
}
// unlock all resources in the project
m_lockManager.removeResourcesInProject(deleteProject.getId());
clearAccessControlListCache();
clearResourceCache();
// set project to online project if current project is the one which will be deleted
if (projectId == context.currentProject().getId()) {
context.setCurrentProject(readProject(I_CmsConstants.C_PROJECT_ONLINE_ID));
}
// delete the project
m_projectDriver.deleteProject(deleteProject);
m_projectCache.remove(new Integer(projectId));
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROJECT_MODIFIED, Collections.singletonMap("project", deleteProject)));
} else if (projectId == I_CmsConstants.C_PROJECT_ONLINE_ID) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteProject() " + deleteProject.getName(), CmsSecurityException.C_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteProject() " + deleteProject.getName(), CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
}
}
/**
* Delete the propertydefinition for the resource type.<p>
*
* Only the admin can do this.
*
* @param context the current request context
* @param name the name of the propertydefinition to read
* @param resourcetype the name of the resource type for which the propertydefinition is valid
*
* @throws CmsException if something goes wrong
*/
public void deletePropertydefinition(CmsRequestContext context, String name, int resourcetype) throws CmsException {
CmsPropertydefinition propertyDefinition = null;
// check the security
if (isAdmin(context)) {
try {
// first read and then delete the metadefinition.
propertyDefinition = readPropertydefinition(context, name, resourcetype);
m_vfsDriver.deletePropertyDefinition(propertyDefinition);
} finally {
// fire an event that a property of a resource has been deleted
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROPERTY_DEFINITION_MODIFIED, Collections.singletonMap("propertyDefinition", propertyDefinition)));
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deletePropertydefinition() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Deletes an entry in the published resource table.<p>
*
* @param context the current request context
* @param resourceName The name of the resource to be deleted in the static export
* @param linkType the type of resource deleted (0= non-paramter, 1=parameter)
* @param linkParameter the parameters ofthe resource
* @throws CmsException if something goes wrong
*/
public void deleteStaticExportPublishedResource(CmsRequestContext context, String resourceName, int linkType, String linkParameter) throws CmsException {
m_projectDriver.deleteStaticExportPublishedResource(context.currentProject(), resourceName, linkType, linkParameter);
}
/**
* Deletes all entries in the published resource table.<p>
*
* @param context the current request context
* @param linkType the type of resource deleted (0= non-paramter, 1=parameter)
* @throws CmsException if something goes wrong
*/
public void deleteAllStaticExportPublishedResources(CmsRequestContext context, int linkType) throws CmsException {
m_projectDriver.deleteAllStaticExportPublishedResources(context.currentProject(), linkType);
}
/**
* Deletes a user from the Cms.<p>
*
* Only a adminstrator can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param userId the Id of the user to be deleted
*
* @throws CmsException if operation was not succesfull
*/
public void deleteUser(CmsRequestContext context, CmsUUID userId) throws CmsException {
CmsUser user = readUser(userId);
deleteUser(context, user.getName());
}
/**
* Deletes a user from the Cms.<p>
*
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param username the name of the user to be deleted
*
* @throws CmsException if operation was not succesfull
*/
public void deleteUser(CmsRequestContext context, String username) throws CmsException {
// Test is this user is existing
CmsUser user = readUser(username);
// Check the security
// Avoid to delete admin or guest-user
if (isAdmin(context) && !(username.equals(OpenCms.getDefaultUsers().getUserAdmin()) || username.equals(OpenCms.getDefaultUsers().getUserGuest()))) {
m_userDriver.deleteUser(username);
// delete user from cache
clearUserCache(user);
} else if (username.equals(OpenCms.getDefaultUsers().getUserAdmin()) || username.equals(OpenCms.getDefaultUsers().getUserGuest())) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteUser() " + username, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteUser() " + username, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Deletes a web user from the Cms.<p>
*
* @param userId the Id of the user to be deleted
*
* @throws CmsException if operation was not succesfull
*/
public void deleteWebUser(CmsUUID userId) throws CmsException {
CmsUser user = readUser(userId);
m_userDriver.deleteUser(user.getName());
// delete user from cache
clearUserCache(user);
}
/**
* Destroys this driver manager.<p>
*
* @throws Throwable if something goes wrong
*/
public void destroy() throws Throwable {
finalize();
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Shutting down : " + this.getClass().getName() + " ... ok!");
}
}
/**
* Method to encrypt the passwords.<p>
*
* @param value the value to encrypt
* @return the encrypted value
*/
public String digest(String value) {
return m_userDriver.encryptPassword(value);
}
/**
* Ends a task from the Cms.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskid the ID of the task to end
*
* @throws CmsException if something goes wrong
*/
public void endTask(CmsRequestContext context, int taskid) throws CmsException {
m_workflowDriver.endTask(taskid);
if (context.currentUser() == null) {
m_workflowDriver.writeSystemTaskLog(taskid, "Task finished.");
} else {
m_workflowDriver.writeSystemTaskLog(taskid, "Task finished by " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
}
/**
* Tests if a resource with the given resourceId does already exist in the Database.<p>
*
* @param context the current request context
* @param resourceId the resource id to test for
* @return true if a resource with the given id was found, false otherweise
* @throws CmsException if something goes wrong
*/
public boolean existsResourceId(CmsRequestContext context, CmsUUID resourceId) throws CmsException {
return m_vfsDriver.validateResourceIdExists(context.currentProject().getId(), resourceId);
}
/**
* Extracts resources from a given resource list which are inside a given folder tree.<p>
*
* @param context the current request context
* @param storage ste of CmsUUID of all folders instide the folder tree
* @param resources list of CmsResources
* @return filtered list of CsmResources which are inside the folder tree
* @throws CmsException if operation was not succesful
*/
private List extractResourcesInTree(CmsRequestContext context, Set storage, List resources) throws CmsException {
List result = (List)new ArrayList();
Iterator i = resources.iterator();
// now select only those resources which are in the folder tree below the given folder
while (i.hasNext()) {
CmsResource res = (CmsResource)i.next();
// ckeck if the parent id of the resource is within the folder tree
if (storage.contains(res.getParentStructureId())) {
//this resource is inside the folder tree.
// now check if it is not marked as deleted
if (res.getState() != I_CmsConstants.C_STATE_DELETED) {
// check the read access
if (hasPermissions(context, res, I_CmsConstants.C_READ_ACCESS, false)) {
// this is a valid resouce, add it to the result list
res.setFullResourceName(readPath(context, res, false));
result.add(res);
updateContextDates(context, res);
}
}
}
}
return result;
}
/**
* Releases any allocated resources during garbage collection.<p>
*
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable {
try {
clearcache();
m_projectDriver.destroy();
m_userDriver.destroy();
m_vfsDriver.destroy();
m_workflowDriver.destroy();
m_backupDriver.destroy();
m_userCache = null;
m_groupCache = null;
m_userGroupsCache = null;
m_projectCache = null;
m_propertyCache = null;
m_resourceCache = null;
m_resourceListCache = null;
m_accessControlListCache = null;
m_projectDriver = null;
m_userDriver = null;
m_vfsDriver = null;
m_workflowDriver = null;
m_backupDriver = null;
m_htmlLinkValidator = null;
} catch (Throwable t) {
// ignore
}
super.finalize();
}
/**
* Forwards a task to a new user.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskid the Id of the task to forward
* @param newRoleName the new group name for the task
* @param newUserName the new user who gets the task. if its "" the a new agent will automatic selected
* @throws CmsException if something goes wrong
*/
public void forwardTask(CmsRequestContext context, int taskid, String newRoleName, String newUserName) throws CmsException {
CmsGroup newRole = m_userDriver.readGroup(newRoleName);
CmsUser newUser = null;
if (newUserName.equals("")) {
newUser = readUser(m_workflowDriver.readAgent(newRole.getId()));
} else {
newUser = readUser(newUserName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
}
m_workflowDriver.forwardTask(taskid, newRole.getId(), newUser.getId());
m_workflowDriver.writeSystemTaskLog(taskid, "Task fowarded from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + " to " + newUser.getFirstname() + " " + newUser.getLastname() + ".");
}
/**
* Reads all relevant access control entries for a given resource.<p>
*
* The access control entries of a resource are readable by everyone.
*
* @param context the current request context
* @param resource the resource
* @param getInherited true in order to include access control entries inherited by parent folders
* @return a vector of access control entries defining all permissions for the given resource
* @throws CmsException if something goes wrong
*/
public Vector getAccessControlEntries(CmsRequestContext context, CmsResource resource, boolean getInherited) throws CmsException {
CmsResource res = resource;
CmsUUID resourceId = res.getResourceId();
//CmsAccessControlList acList = new CmsAccessControlList();
// add the aces of the resource itself
Vector acEntries = m_userDriver.readAccessControlEntries(context.currentProject(), resourceId, false);
// add the aces of each predecessor
CmsUUID structureId;
while (getInherited && !(structureId = res.getParentStructureId()).isNullUUID()) {
res = m_vfsDriver.readFolder(context.currentProject().getId(), structureId);
acEntries.addAll(m_userDriver.readAccessControlEntries(context.currentProject(), res.getResourceId(), getInherited));
}
return acEntries;
}
/**
* Returns the access control list of a given resource.<p>
*
* Note: the current project must be the project the resource belongs to !
* The access control list of a resource is readable by everyone.
*
* @param context the current request context
* @param resource the resource
* @return the access control list of the resource
* @throws CmsException if something goes wrong
*/
public CmsAccessControlList getAccessControlList(CmsRequestContext context, CmsResource resource) throws CmsException {
return getAccessControlList(context, resource, false);
}
/**
* Returns the access control list of a given resource.<p>
*
* If inheritedOnly is set, non-inherited entries of the resource are skipped.
*
* @param context the current request context
* @param resource the resource
* @param inheritedOnly skip non-inherited entries if set
* @return the access control list of the resource
* @throws CmsException if something goes wrong
*/
public CmsAccessControlList getAccessControlList(CmsRequestContext context, CmsResource resource, boolean inheritedOnly) throws CmsException {
CmsResource res = resource;
CmsAccessControlList acList = (CmsAccessControlList)m_accessControlListCache.get(getCacheKey(inheritedOnly + "_", context.currentProject(), resource.getStructureId().toString()));
ListIterator acEntries = null;
CmsUUID resourceId = null;
// return the cached acl if already available
if (acList != null) {
return acList;
}
// otherwise, get the acl of the parent or a new one
if (!(resourceId = res.getParentStructureId()).isNullUUID()) {
res = m_vfsDriver.readFolder(context.currentProject().getId(), resourceId);
acList = (CmsAccessControlList)getAccessControlList(context, res, true).clone();
} else {
acList = new CmsAccessControlList();
}
// add the access control entries belonging to this resource
acEntries = m_userDriver.readAccessControlEntries(context.currentProject(), resource.getResourceId(), inheritedOnly).listIterator();
while (acEntries.hasNext()) {
CmsAccessControlEntry acEntry = (CmsAccessControlEntry)acEntries.next();
// if the overwrite flag is set, reset the allowed permissions to the permissions of this entry
if ((acEntry.getFlags() & I_CmsConstants.C_ACCESSFLAGS_OVERWRITE) > 0) {
acList.setAllowedPermissions(acEntry);
} else {
acList.add(acEntry);
}
}
m_accessControlListCache.put(getCacheKey(inheritedOnly + "_", context.currentProject(), resource.getStructureId().toString()), acList);
return acList;
}
/**
* Returns all projects, which are owned by the user or which are accessible for the group of the user.<p>
*
* All users are granted.
*
* @param context the current request context
* @return a vector of projects
* @throws CmsException if something goes wrong
*/
public Vector getAllAccessibleProjects(CmsRequestContext context) throws CmsException {
// get all groups of the user
Vector groups = getGroupsOfUser(context, context.currentUser().getName());
// get all projects which are owned by the user.
Vector projects = m_projectDriver.readProjectsForUser(context.currentUser());
// get all projects, that the user can access with his groups.
for (int i = 0; i < groups.size(); i++) {
Vector projectsByGroup;
// is this the admin-group?
if (((CmsGroup)groups.elementAt(i)).getName().equals(OpenCms.getDefaultUsers().getGroupAdministrators())) {
// yes - all unlocked projects are accessible for him
projectsByGroup = m_projectDriver.readProjects(I_CmsConstants.C_PROJECT_STATE_UNLOCKED);
} else {
// no - get all projects, which can be accessed by the current group
projectsByGroup = m_projectDriver.readProjectsForGroup((CmsGroup)groups.elementAt(i));
}
// merge the projects to the vector
for (int j = 0; j < projectsByGroup.size(); j++) {
// add only projects, which are new
if (!projects.contains(projectsByGroup.elementAt(j))) {
projects.addElement(projectsByGroup.elementAt(j));
}
}
}
// return the vector of projects
return (projects);
}
/**
* Returns a Vector with all projects from history.<p>
*
* @return Vector with all projects from history.
* @throws CmsException if operation was not succesful.
*/
public Vector getAllBackupProjects() throws CmsException {
Vector projects = new Vector();
projects = m_backupDriver.readBackupProjects();
return projects;
}
/**
* Returns all projects, which are owned by the user or which are manageable for the group of the user.<p>
*
* All users are granted.
*
* @param context the current request context
* @return a Vector of projects
* @throws CmsException if operation was not succesful
*/
public Vector getAllManageableProjects(CmsRequestContext context) throws CmsException {
// get all groups of the user
Vector groups = getGroupsOfUser(context, context.currentUser().getName());
// get all projects which are owned by the user.
Vector projects = m_projectDriver.readProjectsForUser(context.currentUser());
// get all projects, that the user can manage with his groups.
for (int i = 0; i < groups.size(); i++) {
// get all projects, which can be managed by the current group
Vector projectsByGroup;
// is this the admin-group?
if (((CmsGroup)groups.elementAt(i)).getName().equals(OpenCms.getDefaultUsers().getGroupAdministrators())) {
// yes - all unlocked projects are accessible for him
projectsByGroup = m_projectDriver.readProjects(I_CmsConstants.C_PROJECT_STATE_UNLOCKED);
} else {
// no - get all projects, which can be accessed by the current group
projectsByGroup = m_projectDriver.readProjectsForManagerGroup((CmsGroup)groups.elementAt(i));
}
// merge the projects to the vector
for (int j = 0; j < projectsByGroup.size(); j++) {
// add only projects, which are new
if (!projects.contains(projectsByGroup.elementAt(j))) {
projects.addElement(projectsByGroup.elementAt(j));
}
}
}
// remove the online-project, it is not manageable!
projects.removeElement(onlineProject());
// return the vector of projects
return projects;
}
/**
* Returns an array with all all initialized resource types.<p>
*
* @return array with all initialized resource types
*/
public I_CmsResourceType[] getAllResourceTypes() {
// return the resource-types.
return m_resourceTypes;
}
/**
* Gets the backup driver.<p>
*
* @return CmsBackupDriver
*/
public final I_CmsBackupDriver getBackupDriver() {
return m_backupDriver;
}
/**
* Get the next version id for the published backup resources.<p>
*
* @return the new version id
*/
public int getBackupTagId() {
return m_backupDriver.readNextBackupTagId();
}
/**
* Return a cache key build from the provided information.<p>
*
* @param prefix a prefix for the key
* @param project the project for which to genertate the key
* @param resource the resource for which to genertate the key
* @return String a cache key build from the provided information
*/
private String getCacheKey(String prefix, CmsProject project, String resource) {
StringBuffer buffer = new StringBuffer(32);
if (prefix != null) {
buffer.append(prefix);
buffer.append("_");
}
if (project != null) {
if (project.isOnlineProject()) {
buffer.append("on");
} else {
buffer.append("of");
}
buffer.append("_");
}
buffer.append(resource);
return buffer.toString();
}
/**
* Return a cache key build from the provided information.<p>
*
* @param prefix a prefix for the key
* @param projectId the project for which to genertate the key
* @param resource the resource for which to genertate the key
* @return String a cache key build from the provided information
*/
private String getCacheKey(String prefix, int projectId, String resource) {
StringBuffer buffer = new StringBuffer(32);
if (prefix != null) {
buffer.append(prefix);
buffer.append("_");
}
if (projectId >= I_CmsConstants.C_PROJECT_ONLINE_ID) {
if (projectId == I_CmsConstants.C_PROJECT_ONLINE_ID) {
buffer.append("on");
} else {
buffer.append("of");
}
buffer.append("_");
}
buffer.append(resource);
return buffer.toString();
}
/**
* Returns all child groups of a group.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param groupname the name of the group
* @return groups a Vector of all child groups or null
* @throws CmsException if operation was not succesful.
*/
public Vector getChild(CmsRequestContext context, String groupname) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readChildGroups(groupname);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getChild()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns all child groups of a group.<p>
* This method also returns all sub-child groups of the current group.
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param groupname the name of the group
* @return a Vector of all child groups or null
* @throws CmsException if operation was not succesful
*/
public Vector getChilds(CmsRequestContext context, String groupname) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
Vector childs = new Vector();
Vector allChilds = new Vector();
Vector subchilds = new Vector();
CmsGroup group = null;
// get all child groups if the user group
childs = m_userDriver.readChildGroups(groupname);
if (childs != null) {
allChilds = childs;
// now get all subchilds for each group
Enumeration enu = childs.elements();
while (enu.hasMoreElements()) {
group = (CmsGroup)enu.nextElement();
subchilds = getChilds(context, group.getName());
//add the subchilds to the already existing groups
Enumeration enusub = subchilds.elements();
while (enusub.hasMoreElements()) {
group = (CmsGroup)enusub.nextElement();
allChilds.addElement(group);
}
}
}
return allChilds;
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getChilds()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Method to access the configurations of the properties-file.<p>
*
* All users are granted.
*
* @return the Configurations of the properties-file
*/
public ExtendedProperties getConfigurations() {
return m_configuration;
}
/**
* Returns the list of groups to which the user directly belongs to<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param context the current request context
* @param username The name of the user.
* @return Vector of groups
* @throws CmsException Throws CmsException if operation was not succesful
*/
public Vector getDirectGroupsOfUser(CmsRequestContext context, String username) throws CmsException {
CmsUser user = readUser(username);
return m_userDriver.readGroupsOfUser(user.getId(), context.getRemoteAddress());
}
/**
* Returns a Vector with all resource-names that have set the given property to the given value.<p>
*
* All users are granted.
*
* @param context the current request context
* @param propertyDefinition the name of the propertydefinition to check
* @param propertyValue the value of the property for the resource
* @return vector with all names of resources
* @throws CmsException if operation was not succesful
*/
public Vector getFilesWithProperty(CmsRequestContext context, String propertyDefinition, String propertyValue) throws CmsException {
List result = setFullResourceNames(context, m_vfsDriver.readResourceNames(context.currentProject().getId(), propertyDefinition, propertyValue));
return new Vector(result);
}
/**
* This method can be called, to determine if the file-system was changed
* in the past. A module can compare its previosly stored number with this
* returned number. If they differ, a change was made.<p>
*
* All users are granted.
*
* @return the number of file-system-changes.
*/
public long getFileSystemFolderChanges() {
return m_fileSystemFolderChanges;
}
/**
* Creates Set containing all CmsUUIDs of the subfolders of a given folder.<p>
*
* This HashSet can be used to test if a resource is inside a subtree of the given folder.
* No permission check is performed on the set of folders, if required this has to be done
* in the method that calls this method.<p>
*
* @param context the current request context
* @param folder the folder to get the subresources from
* @return Set of CmsUUIDs
* @throws CmsException if operation was not succesful
*/
private Set getFolderIds(CmsRequestContext context, String folder) throws CmsException {
CmsFolder parentFolder = readFolder(context, folder);
return (Set)new HashSet(m_vfsDriver.readFolderTree(context.currentProject(), parentFolder));
}
/**
* Returns all groups.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @return users a Vector of all existing groups
* @throws CmsException if operation was not succesful
*/
public Vector getGroups(CmsRequestContext context) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readGroups();
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getGroups()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns the groups of a Cms user.<p>
*
* @param context the current request context
* @param username the name of the user
* @return a vector of Cms groups filtered by the specified IP address
* @throws CmsException if operation was not succesful
*/
public Vector getGroupsOfUser(CmsRequestContext context, String username) throws CmsException {
return getGroupsOfUser(context, username, context.getRemoteAddress());
}
/**
* Returns the groups of a Cms user filtered by the specified IP address.<p>
*
* @param context the current request context
* @param username the name of the user
* @param remoteAddress the IP address to filter the groups in the result vector
* @return a vector of Cms groups
* @throws CmsException if operation was not succesful
*/
public Vector getGroupsOfUser(CmsRequestContext context, String username, String remoteAddress) throws CmsException {
CmsUser user = readUser(username);
String cacheKey = m_keyGenerator.getCacheKeyForUserGroups(remoteAddress, context, user);
Vector allGroups = (Vector)m_userGroupsCache.get(cacheKey);
if ((allGroups == null) || (allGroups.size() == 0)) {
CmsGroup subGroup;
CmsGroup group;
// get all groups of the user
Vector groups = m_userDriver.readGroupsOfUser(user.getId(), remoteAddress);
allGroups = new Vector();
// now get all childs of the groups
Enumeration enu = groups.elements();
while (enu.hasMoreElements()) {
group = (CmsGroup)enu.nextElement();
subGroup = getParent(group.getName());
while ((subGroup != null) && (!allGroups.contains(subGroup))) {
allGroups.addElement(subGroup);
// read next sub group
subGroup = getParent(subGroup.getName());
}
if (!allGroups.contains(group)) {
allGroups.add(group);
}
}
m_userGroupsCache.put(cacheKey, allGroups);
}
return allGroups;
}
/**
* Returns all groups with a name like the specified pattern.<p>
*
* All users are granted, except the anonymous user.<p>
*
* @param context the current request context
* @param namePattern pattern for the group name
* @return a Vector of all groups with a name like the given pattern
* @throws CmsException if something goes wrong
*/
public Vector getGroupsLike(CmsRequestContext context, String namePattern) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readGroupsLike(namePattern);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getGroupsLike()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Checks if a user is a direct member of a group having a name like the specified pattern.<p>
*
* All users are granted.<p>
*
* @param context the current request context
* @param username the name of the user.
* @param groupNamePattern pattern for the group name
* @return <code>true</code> if the given user is a direct member of a group having a name like the specified pattern
* @throws CmsException if something goes wrong
*/
public boolean hasDirectGroupsOfUserLike(CmsRequestContext context, String username, String groupNamePattern) throws CmsException {
CmsUser user = readUser(username);
return m_userDriver.hasGroupsOfUserLike(user.getId(), context.getRemoteAddress(), groupNamePattern);
}
/**
* This is the port the workplace access is limited to. With the opencms.properties
* the access to the workplace can be limited to a user defined port. With this
* feature a firewall can block all outside requests to this port with the result
* the workplace is only available in the local net segment.<p>
*
* @return the portnumber or -1 if no port is set
*/
public int getLimitedWorkplacePort() {
return m_limitedWorkplacePort;
}
/**
* Returns the lock for a resource.<p>
*
* @param context the current request context
* @param resource the resource
* @return the lock
* @throws CmsException if something goes wrong
*/
public CmsLock getLock(CmsRequestContext context, CmsResource resource) throws CmsException {
if (!resource.hasFullResourceName()) {
try {
// cw: it must be possible to check if there is a lock set on a resource even if the resource is deleted
readPath(context, resource, true);
} catch (CmsException e) {
return CmsLock.getNullLock();
}
}
return getLock(context, resource.getRootPath());
}
/**
* Returns the lock for a resource name.<p>
*
* @param context the current request context
* @param resourcename name of the resource
* @return the lock
* @throws CmsException if something goes wrong
*/
public CmsLock getLock(CmsRequestContext context, String resourcename) throws CmsException {
return m_lockManager.getLock(this, context, resourcename);
}
/**
* Returns the parent group of a group.<p>
*
* @param groupname the name of the group
* @return group the parent group or null
* @throws CmsException if operation was not succesful
*/
public CmsGroup getParent(String groupname) throws CmsException {
CmsGroup group = readGroup(groupname);
if (group.getParentId().isNullUUID()) {
return null;
}
// try to read from cache
CmsGroup parent = (CmsGroup)m_groupCache.get(new CacheId(group.getParentId()));
if (parent == null) {
parent = m_userDriver.readGroup(group.getParentId());
m_groupCache.put(new CacheId(parent), parent);
}
return parent;
}
/**
* Returns the parent resource of a resouce.<p>
*
* All users are granted.
*
* @param context the current request context
* @param resourcename the name of the resource to find the parent for
* @return the parent resource read from the VFS
* @throws CmsException if parent resource could not be read
*/
public CmsResource getParentResource(CmsRequestContext context, String resourcename) throws CmsException {
// check if this is the root resource
if (!resourcename.equals(I_CmsConstants.C_ROOT)) {
return readFileHeader(context, CmsResource.getParentFolder(resourcename));
} else {
// just return the root
return readFileHeader(context, I_CmsConstants.C_ROOT);
}
}
/**
* Returns the current permissions of an user on the given resource.<p>
*
* Permissions are readable by everyone.
*
* @param context the current request context
* @param resource the resource
* @param user the user
* @return bitset with allowed permissions
* @throws CmsException if something goes wrong
*/
public CmsPermissionSet getPermissions(CmsRequestContext context, CmsResource resource, CmsUser user) throws CmsException {
CmsAccessControlList acList = getAccessControlList(context, resource);
return acList.getPermissions(user, getGroupsOfUser(context, user.getName()));
}
/**
* Gets the project driver.<p>
*
* @return CmsProjectDriver
*/
public final I_CmsProjectDriver getProjectDriver() {
return m_projectDriver;
}
/**
* Returns the current OpenCms registry.<p>
*
* @param cms the current OpenCms context object
* @return the current OpenCms registry
*/
public CmsRegistry getRegistry(CmsObject cms) {
return m_registry.clone(cms);
}
/**
* Returns a Vector with the subresources for a folder.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read and view this resource</li>
* </ul>
*
* @param context the current request context
* @param folder the name of the folder to get the subresources from
* @return a Vector with resources.
*
* @throws CmsException if operation was not successful
*/
public Vector getResourcesInFolder(CmsRequestContext context, String folder) throws CmsException {
CmsFolder folderRes = null;
Vector resources = new Vector();
Vector retValue = new Vector();
try {
folderRes = readFolder(context, folder);
if (folderRes.getState() == I_CmsConstants.C_STATE_DELETED) {
folderRes = null;
}
} catch (CmsException exc) {
// ignore the exception - folder was not found in this project
}
if (folderRes == null) {
// the folder is not existent
throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_NOT_FOUND);
} else {
// try to read from cache
String cacheKey = getCacheKey(context.currentUser().getName() + "_resources", context.currentProject(), folderRes.getRootPath());
retValue = (Vector)m_resourceListCache.get(cacheKey);
if (retValue == null || retValue.size() == 0) {
//resources = m_vfsDriver.getResourcesInFolder(context.currentProject().getId(), folderRes);
List subFolders = m_vfsDriver.readChildResources(context.currentProject(), folderRes, true);
List subFiles = m_vfsDriver.readChildResources(context.currentProject(), folderRes, false);
resources.addAll(subFolders);
resources.addAll(subFiles);
setFullResourceNames(context, resources);
retValue = new Vector(resources.size());
// make sure that we have access to all these
Iterator i = resources.iterator();
while (i.hasNext()) {
CmsResource res = (CmsResource)i.next();
if (hasPermissions(context, res, I_CmsConstants.C_VIEW_ACCESS, false)) {
if (res.isFolder() && !CmsResource.isFolder(res.getName())) {
res.setFullResourceName(folderRes.getRootPath() + res.getName().concat("/"));
} else {
res.setFullResourceName(folderRes.getRootPath() + res.getName());
}
retValue.addElement(res);
updateContextDates(context, res);
}
}
m_resourceListCache.put(cacheKey, retValue);
}
}
return (retValue == null) ? null : (Vector)retValue.clone();
}
/**
* Returns a list with all sub resources of a given folder that have benn modified in a given time range.<p>
*
* All users are granted.
*
* @param context the current request context
* @param folder the folder to get the subresources from
* @param starttime the begin of the time range
* @param endtime the end of the time range
* @return list with all resources
*
* @throws CmsException if operation was not succesful
*/
public List getResourcesInTimeRange(CmsRequestContext context, String folder, long starttime, long endtime) throws CmsException {
List extractedResources = null;
String cacheKey = null;
cacheKey = getCacheKey(context.currentUser().getName() + "_SubtreeResourcesInTimeRange", context.currentProject(), folder + "_" + starttime + "_" + endtime);
if ((extractedResources = (List)m_resourceListCache.get(cacheKey)) == null) {
// get the folder tree
Set storage = getFolderIds(context, folder);
// now get all resources which contain the selected property
List resources = m_vfsDriver.readResources(context.currentProject().getId(), starttime, endtime);
// filter the resources inside the tree
extractedResources = extractResourcesInTree(context, storage, resources);
// cache the calculated result list
m_resourceListCache.put(cacheKey, extractedResources);
resources = null;
storage = null;
}
return extractedResources;
}
/**
* Returns a list with all sub resources of a given folder that have set the given property.<p>
*
* All users are granted.
*
* @param context the current request context
* @param folder the folder to get the subresources from
* @param propertyDefinition the name of the propertydefinition to check
* @return list with all resources
*
* @throws CmsException if operation was not succesful
*/
public List getResourcesWithProperty(CmsRequestContext context, String folder, String propertyDefinition) throws CmsException {
List extractedResources = null;
String cacheKey = null;
cacheKey = getCacheKey(context.currentUser().getName() + "_SubtreeResourcesWithProperty", context.currentProject(), folder + "_" + propertyDefinition);
if ((extractedResources = (List)m_resourceListCache.get(cacheKey)) == null) {
// get the folder tree
Set storage = getFolderIds(context, folder);
// now get all resources which contain the selected property
List resources = m_vfsDriver.readResources(context.currentProject().getId(), propertyDefinition);
// filter the resources inside the tree
extractedResources = extractResourcesInTree(context, storage, resources);
// cache the calculated result list
m_resourceListCache.put(cacheKey, extractedResources);
}
return extractedResources;
}
/**
* Returns a vector with all resources of the given type that have set the given property to the given value.<p>
*
* All users are granted.
*
* @param context the current request context
* @param propertyDefinition the name of the propertydefinition to check
* @return Vector with all resources
* @throws CmsException if operation was not succesful
*/
public Vector getResourcesWithPropertyDefinition(CmsRequestContext context, String propertyDefinition) throws CmsException {
List result = setFullResourceNames(context, m_vfsDriver.readResources(context.currentProject().getId(), propertyDefinition));
return new Vector(result);
}
/**
* Returns a vector with all resources of the given type that have set the given property to the given value.<p>
*
* All users are granted.
*
* @param context the current request context
* @param propertyDefinition the name of the propertydefinition to check
* @param propertyValue the value of the property for the resource
* @param resourceType the resource type of the resource
* @return vector with all resources.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public Vector getResourcesWithPropertyDefintion(CmsRequestContext context, String propertyDefinition, String propertyValue, int resourceType) throws CmsException {
return m_vfsDriver.readResources(context.currentProject().getId(), propertyDefinition, propertyValue, resourceType);
}
/**
* Returns the initialized resource type instance for the given id.<p>
*
* @param resourceType the id of the resourceType to get
* @return the initialized resource type instance for the given id
* @throws CmsException if something goes wrong
*/
public I_CmsResourceType getResourceType(int resourceType) throws CmsException {
try {
return getAllResourceTypes()[resourceType];
} catch (Exception e) {
throw new CmsException("[" + this.getClass().getName() + "] Unknown resource type id requested: " + resourceType, CmsException.C_NOT_FOUND);
}
}
/**
* Returns the initialized resource type instance for the given resource type name.<p>
*
* @param resourceType the name of the resourceType to get
* @return the initialized resource type instance for the given id
* @throws CmsException if something goes wrong
*/
public I_CmsResourceType getResourceType(String resourceType) throws CmsException {
try {
I_CmsResourceType[] types = getAllResourceTypes();
for (int i = 0; i < types.length; i++) {
I_CmsResourceType t = types[i];
if ((t != null) && (t.getResourceTypeName().equals(resourceType))) {
return t;
}
}
throw new Exception("Resource type not found");
} catch (Exception e) {
throw new CmsException("[" + this.getClass().getName() + "] Unknown resource type name requested: " + resourceType, CmsException.C_NOT_FOUND);
}
}
/**
* Gets the sub files of a folder.<p>
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @return a List of all sub files
* @throws CmsException if something goes wrong
*/
public List getSubFiles(CmsRequestContext context, String parentFolderName) throws CmsException {
return getSubFiles(context, parentFolderName, false);
}
/**
* Gets the sub files of a folder.<p>
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @param includeDeleted true if deleted files should be included in the result
* @return a List of all sub files
* @throws CmsException if something goes wrong
*/
public List getSubFiles(CmsRequestContext context, String parentFolderName, boolean includeDeleted) throws CmsException {
return getSubResources(context, parentFolderName, includeDeleted, false);
}
/**
* Gets the sub folders of a folder.<p>
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @return a List of all sub folders
* @throws CmsException if something goes wrong
*/
public List getSubFolders(CmsRequestContext context, String parentFolderName) throws CmsException {
return getSubFolders(context, parentFolderName, false);
}
/**
* Gets the sub folder of a folder.<p>
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @param includeDeleted true if deleted files should be included in the result
* @return a List of all sub folders
* @throws CmsException if something goes wrong
*/
public List getSubFolders(CmsRequestContext context, String parentFolderName, boolean includeDeleted) throws CmsException {
return getSubResources(context, parentFolderName, includeDeleted, true);
}
/**
* Gets all sub folders or sub files in a folder.<p>
* Note: the list contains all resources that are readable or visible.
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @param includeDeleted true if deleted files should be included in the result
* @param getSubFolders true if the sub folders of the parent folder are requested, false if the sub files are requested
* @return a list of all sub folders or sub files
* @throws CmsException if something goes wrong
*/
protected List getSubResources(CmsRequestContext context, String parentFolderName, boolean includeDeleted, boolean getSubFolders) throws CmsException {
List subResources = null;
CmsFolder parentFolder = null;
CmsResource currentResource = null;
String cacheKey = null;
// try to get the sub resources from the cache
if (getSubFolders) {
cacheKey = getCacheKey(context.currentUser().getName() + "_folders", context.currentProject(), parentFolderName);
} else {
cacheKey = getCacheKey(context.currentUser().getName() + "_files_" + includeDeleted, context.currentProject(), parentFolderName);
}
subResources = (List)m_resourceListCache.get(cacheKey);
try {
// validate the parent folder name
if (! CmsResource.isFolder(parentFolderName)) {
parentFolderName += "/";
}
// read the parent folder
parentFolder = readFolder(context, parentFolderName, includeDeleted);
checkPermissions(context, parentFolder, I_CmsConstants.C_READ_ACCESS);
} catch (CmsException e) {
return new ArrayList(0);
}
if ((parentFolder.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted)) {
// the parent folder was found, but it is deleted -> sub resources are not available
return new ArrayList(0);
}
if (subResources != null && subResources.size() > 0) {
// the parent folder is not deleted, and the sub resources were cached, no further operations required
// we must return a copy (see below)
return new ArrayList(subResources);
}
// get the sub resources from the VFS driver and check the required permissions
subResources = m_vfsDriver.readChildResources(context.currentProject(), parentFolder, getSubFolders);
for (int i = 0; i < subResources.size(); i++) {
currentResource = (CmsResource)subResources.get(i);
if (!includeDeleted && currentResource.getState() == I_CmsConstants.C_STATE_DELETED) {
subResources.remove(i--);
} else if (!hasPermissions(context, currentResource, I_CmsConstants.C_READ_OR_VIEW_ACCESS, false)) {
subResources.remove(i--);
} else {
if (currentResource.isFolder() && !CmsResource.isFolder(currentResource.getName())) {
currentResource.setFullResourceName(parentFolderName + currentResource.getName().concat("/"));
} else {
currentResource.setFullResourceName(parentFolderName + currentResource.getName());
}
updateContextDates(context, currentResource);
}
}
// cache the sub resources
m_resourceListCache.put(cacheKey, subResources);
// currently we must return a copy to prevent the cached copy from being modified externally
return new ArrayList(subResources);
}
/**
* Get a parameter value for a task.<p>
*
* All users are granted.
*
* @param taskId the Id of the task
* @param parName name of the parameter
* @return task parameter value
* @throws CmsException if something goes wrong
*/
public String getTaskPar(int taskId, String parName) throws CmsException {
return m_workflowDriver.readTaskParameter(taskId, parName);
}
/**
* Get the template task id for a given taskname.<p>
*
* @param taskName name of the task
* @return id from the task template
* @throws CmsException if something goes wrong
*/
public int getTaskType(String taskName) throws CmsException {
return m_workflowDriver.readTaskType(taskName);
}
/**
* Gets a user cache key.<p>
*
* @param id the user uuid
* @return the user cache key
*/
private String getUserCacheKey(CmsUUID id) {
return id.toString();
}
/**
* Gets a user cache key.<p>
*
* @param username the name of the user
* @param type the user type
* @return the user cache key
*/
private String getUserCacheKey(String username, int type) {
return username + C_USER_CACHE_SEP + CmsUser.isSystemUser(type);
}
/**
* Gets the user driver.<p>
*
* @return I_CmsUserDriver
*/
public final I_CmsUserDriver getUserDriver() {
return m_userDriver;
}
/**
* Gets a user from cache.<p>
*
* @param id the user uuid
* @return CmsUser from cache
*/
private CmsUser getUserFromCache(CmsUUID id) {
return (CmsUser)m_userCache.get(getUserCacheKey(id));
}
/**
* Gets a user from cache.<p>
*
* @param username the username
* @param type the user tpye
* @return CmsUser from cache
*/
private CmsUser getUserFromCache(String username, int type) {
return (CmsUser)m_userCache.get(getUserCacheKey(username, type));
}
/**
* Returns all users.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @return a Vector of all existing users
* @throws CmsException if operation was not succesful.
*/
public Vector getUsers(CmsRequestContext context) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsers(I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsers()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns all users from a given type.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param type the type of the users
* @return a Vector of all existing users
* @throws CmsException if operation was not succesful
*/
public Vector getUsers(CmsRequestContext context, int type) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsers(type);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsers()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns all users from a given type that start with a specified string.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param type the type of the users
* @param namestart the filter for the username
* @return a Vector of all existing users
* @throws CmsException if operation was not succesful
*/
public Vector getUsers(CmsRequestContext context, int type, String namestart) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsers(type, namestart);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsers()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Gets all users with a certain Lastname.<p>
*
* @param context the current request context
* @param Lastname the start of the users lastname
* @param UserType webuser or systemuser
* @param UserStatus enabled, disabled
* @param wasLoggedIn was the user ever locked in?
* @param nMax max number of results
* @return vector of users
* @throws CmsException if operation was not successful
*/
public Vector getUsersByLastname(CmsRequestContext context, String Lastname, int UserType, int UserStatus, int wasLoggedIn, int nMax) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsers(Lastname, UserType, UserStatus, wasLoggedIn, nMax);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsersByLastname()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns a list of users in a group.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param groupname the name of the group to list users from
* @return vector of users
* @throws CmsException if operation was not succesful
*/
public Vector getUsersOfGroup(CmsRequestContext context, String groupname) throws CmsException {
// check the security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsersOfGroup(groupname, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsersOfGroup()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Gets the VfsDriver.<p>
*
* @return CmsVfsDriver
*/
public final I_CmsVfsDriver getVfsDriver() {
return m_vfsDriver;
}
/**
* Returns a Vector with all resources of the given type that have set the given property to the given value.<p>
*
* All users that have read and view access are granted.
*
* @param context the current request context
* @param propertyDefinition the name of the propertydefinition to check.
* @param propertyValue the value of the property for the resource.
* @param resourceType the resource type of the resource
* @return Vector with all resources
* @throws CmsException if operation was not succesful
*/
public Vector getVisibleResourcesWithProperty(CmsRequestContext context, String propertyDefinition, String propertyValue, int resourceType) throws CmsException {
Vector visibleResources = new Vector();
Vector allResources = new Vector();
allResources = m_vfsDriver.readResources(context.currentProject().getId(), propertyDefinition, propertyValue, resourceType);
// check if the user has view access
Enumeration e = allResources.elements();
String lastcheck = "#"; // just a char that is not valid in a filename
while (e.hasMoreElements()) {
CmsResource res = (CmsResource)e.nextElement();
if (!context.removeSiteRoot(readPath(context, res, false)).equals(lastcheck)) {
if (hasPermissions(context, res, I_CmsConstants.C_VIEW_ACCESS, false)) {
visibleResources.addElement(res);
lastcheck = context.removeSiteRoot(readPath(context, res, false));
}
}
}
return visibleResources;
}
/**
* Gets the workflow driver.<p>
*
* @return I_CmsWorkflowDriver
*/
public final I_CmsWorkflowDriver getWorkflowDriver() {
return m_workflowDriver;
}
/**
* Performs a non-blocking permission check on a resource.<p>
*
* @param context the current request context
* @param resource the resource on which permissions are required
* @param requiredPermissions the set of permissions required to access the resource
* @param strongCheck if set to true, all required permission have to be granted, otherwise only one
* @return true if the user has sufficient permissions on the resource
* @throws CmsException if something goes wrong
*/
public boolean hasPermissions(CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, boolean strongCheck) throws CmsException {
String cacheKey = m_keyGenerator.getCacheKeyForUserPermissions(new Boolean(strongCheck).toString(), context, resource, requiredPermissions);
Boolean cacheResult = (Boolean)m_permissionCache.get(cacheKey);
if (cacheResult != null) {
return cacheResult.booleanValue();
}
CmsLock lock = getLock(context, resource);
CmsPermissionSet permissions = null;
int denied = 0;
// if this is the onlineproject, write is rejected
if (context.currentProject().isOnlineProject()) {
denied |= I_CmsConstants.C_PERMISSION_WRITE;
}
// check if the current user is admin
boolean isAdmin = isAdmin(context);
// if the resource type is jsp or xml template
// write is only allowed for administrators
if (!isAdmin && ((resource.getType() == CmsResourceTypeXMLTemplate.C_RESOURCE_TYPE_ID) || (resource.getType() == CmsResourceTypeJsp.C_RESOURCE_TYPE_ID))) {
denied |= I_CmsConstants.C_PERMISSION_WRITE;
}
if (!lock.isNullLock()) {
// if the resource is locked by another user, write is rejected
// read must still be possible, since the explorer file list needs some properties
if (!context.currentUser().getId().equals(lock.getUserId())) {
denied |= I_CmsConstants.C_PERMISSION_WRITE;
}
}
if (isAdmin) {
// if the current user is administrator, anything is allowed
permissions = new CmsPermissionSet(~0);
} else {
// otherwise, get the permissions from the access control list
CmsAccessControlList acl = getAccessControlList(context, resource);
permissions = acl.getPermissions(context.currentUser(), getGroupsOfUser(context, context.currentUser().getName()));
}
permissions.denyPermissions(denied);
boolean result;
if (strongCheck) {
result = (requiredPermissions.getPermissions() & (permissions.getPermissions())) == requiredPermissions.getPermissions();
} else {
result = (requiredPermissions.getPermissions() & (permissions.getPermissions())) > 0;
}
m_permissionCache.put(cacheKey, new Boolean(result));
if (!result && OpenCms.getLog(this).isDebugEnabled()) {
OpenCms.getLog(this).debug(
"Access to resource " + resource.getRootPath() + " "
+ "not permitted for user " + context.currentUser().getName() + ", "
+ "required permissions " + requiredPermissions.getPermissionString() + " "
+ "not satisfied by " + permissions.getPermissionString() + " "
+ ((strongCheck) ? "(required all)" : "(required one)"));
}
return result;
}
/**
* Writes a vector of access control entries as new access control entries of a given resource.<p>
*
* Already existing access control entries of this resource are removed before.
* Access is granted, if:
* <ul>
* <li>the current user has control permission on the resource
* </ul>
*
* @param context the current request context
* @param resource the resource
* @param acEntries vector of access control entries applied to the resource
* @throws CmsException if something goes wrong
*/
public void importAccessControlEntries(CmsRequestContext context, CmsResource resource, Vector acEntries) throws CmsException {
checkPermissions(context, resource, I_CmsConstants.C_CONTROL_ACCESS);
m_userDriver.removeAccessControlEntries(context.currentProject(), resource.getResourceId());
Iterator i = acEntries.iterator();
while (i.hasNext()) {
m_userDriver.writeAccessControlEntry(context.currentProject(), (CmsAccessControlEntry)i.next());
}
clearAccessControlListCache();
//touchResource(context, resource, System.currentTimeMillis());
}
/**
* Imports a import-resource (folder or zipfile) to the cms.<p>
*
* Only Administrators can do this.
*
* @param cms the cms-object to use for the export
* @param context the current request context
* @param importFile the name (absolute Path) of the import resource (zip or folder)
* @param importPath the name (absolute Path) of folder in which should be imported
* @throws CmsException if something goes wrong
*/
public void importFolder(CmsObject cms, CmsRequestContext context, String importFile, String importPath) throws CmsException {
if (isAdmin(context)) {
new CmsImportFolder(importFile, importPath, cms);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] importFolder()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Imports a resource.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is not locked by another user</li>
* </ul>
*
* @param context the current request ocntext
* @param newResourceName the name of the new resource (No pathinformation allowed)
* @param resource the resource to be imported
* @param propertyinfos a Hashtable of propertyinfos, that should be set for this folder
* The keys for this Hashtable are the names for propertydefinitions, the values are
* the values for the propertyinfos
* @param filecontent the content of the resource if it is of type file
* @return CmsResource The created resource
* @throws CmsException will be thrown for missing propertyinfos, for worng propertydefs
* or if the filename is not valid. The CmsException will also be thrown, if the
* user has not the rights for this resource.
*/
public CmsResource importResource(CmsRequestContext context, String newResourceName, CmsResource resource, byte[] filecontent, List propertyinfos) throws CmsException {
// extract folder information
String folderName = null;
String resourceName = null;
if (resource.isFolder()) {
// append I_CmsConstants.C_FOLDER_SEPARATOR if required
if (!newResourceName.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
newResourceName += I_CmsConstants.C_FOLDER_SEPARATOR;
}
// extract folder information
folderName = newResourceName.substring(0, newResourceName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR, newResourceName.length() - 2) + 1);
resourceName = newResourceName.substring(folderName.length(), newResourceName.length() - 1);
} else {
folderName = newResourceName.substring(0, newResourceName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR, newResourceName.length()) + 1);
resourceName = newResourceName.substring(folderName.length(), newResourceName.length());
// check if a link to the imported resource lies in a marked site
if (labelResource(context, resource, newResourceName, 2)) {
int flags = resource.getFlags();
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
resource.setFlags(flags);
}
}
// checks, if the filename is valid, if not it throws a exception
validFilename(resourceName);
CmsFolder parentFolder = readFolder(context, folderName);
// check if the user has write access to the destination folder
checkPermissions(context, parentFolder, I_CmsConstants.C_WRITE_ACCESS);
// create a new CmsResourceObject
if (filecontent == null) {
filecontent = new byte[0];
}
// set the parent id
resource.setParentId(parentFolder.getStructureId());
// create the folder
CmsResource newResource = m_vfsDriver.importResource(context.currentProject(), parentFolder.getStructureId(), resource, filecontent, context.currentUser().getId(), resource.isFolder());
newResource.setFullResourceName(newResourceName);
filecontent = null;
clearResourceCache();
// write metainfos for the folder
m_vfsDriver.writePropertyObjects(context.currentProject(), newResource, propertyinfos);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_LIST_MODIFIED, Collections.singletonMap("resource", parentFolder)));
// return the folder
return newResource;
}
/**
* Initializes the driver and sets up all required modules and connections.<p>
*
* @param config the OpenCms configuration
* @param vfsDriver the vfsdriver
* @param userDriver the userdriver
* @param projectDriver the projectdriver
* @param workflowDriver the workflowdriver
* @param backupDriver the backupdriver
* @throws CmsException if something goes wrong
* @throws Exception if something goes wrong
*/
public void init(ExtendedProperties config, I_CmsVfsDriver vfsDriver, I_CmsUserDriver userDriver, I_CmsProjectDriver projectDriver, I_CmsWorkflowDriver workflowDriver, I_CmsBackupDriver backupDriver) throws CmsException, Exception {
// store the limited workplace port
m_limitedWorkplacePort = config.getInteger("workplace.limited.port", -1);
// initialize the access-module.
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 4 - connecting to the database");
}
// store the access objects
m_vfsDriver = vfsDriver;
m_userDriver = userDriver;
m_projectDriver = projectDriver;
m_workflowDriver = workflowDriver;
m_backupDriver = backupDriver;
m_configuration = config;
// initialize the key generator
m_keyGenerator = (I_CmsCacheKey)Class.forName(config.getString(I_CmsConstants.C_CONFIGURATION_CACHE + ".keygenerator")).newInstance();
// initalize the caches
LRUMap hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".user", 50));
m_userCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_userCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".group", 50));
m_groupCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_groupCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".usergroups", 50));
m_userGroupsCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_userGroupsCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".project", 50));
m_projectCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_projectCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".resource", 2500));
m_resourceCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_resourceCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".resourcelist", 100));
m_resourceListCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_resourceListCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".property", 5000));
m_propertyCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_propertyCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".accesscontrollists", 1000));
m_accessControlListCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_accessControlListCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".permissions", 1000));
m_permissionCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_permissionCache", hashMap);
}
m_refresh = config.getString(I_CmsConstants.C_CONFIGURATION_CACHE + ".refresh", "");
// initialize the registry
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Initializing registry: starting");
}
try {
m_registry = new CmsRegistry(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(config.getString(I_CmsConstants.C_CONFIGURATION_REGISTRY)));
} catch (CmsException ex) {
throw ex;
} catch (Exception ex) {
// init of registry failed - throw exception
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error(OpenCmsCore.C_MSG_CRITICAL_ERROR + "4", ex);
}
throw new CmsException("Init of registry failed", CmsException.C_REGISTRY_ERROR, ex);
}
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Initializing registry: finished");
}
getProjectDriver().fillDefaults();
// initialize the HTML link validator
m_htmlLinkValidator = new CmsHtmlLinkValidator(this);
}
/**
* Determines, if the users current group is the admin-group.<p>
*
* All users are granted.
*
* @param context the current request context
* @return true, if the users current group is the admin-group, else it returns false
* @throws CmsException if operation was not succesful
*/
public boolean isAdmin(CmsRequestContext context) throws CmsException {
return userInGroup(context, context.currentUser().getName(), OpenCms.getDefaultUsers().getGroupAdministrators());
}
/**
* Proves if a specified resource is inside the current project.<p>
*
* @param context the current request context
* @param resource the specified resource
* @return true, if the resource name of the specified resource matches any of the current project's resources
*/
public boolean isInsideCurrentProject(CmsRequestContext context, CmsResource resource) {
List projectResources = null;
try {
projectResources = readProjectResources(context.currentProject());
} catch (CmsException e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("[CmsDriverManager.isInsideProject()] error reading project resources " + e.getMessage());
}
return false;
}
return CmsProject.isInsideProject(projectResources, resource);
}
/**
*
* Proves if a resource is locked.<p>
*
* @see org.opencms.lock.CmsLockManager#isLocked(org.opencms.db.CmsDriverManager, org.opencms.file.CmsRequestContext, java.lang.String)
*
* @param context the current request context
* @param resourcename the full resource name including the site root
* @return true, if and only if the resource is currently locked
* @throws CmsException if something goes wrong
*/
public boolean isLocked(CmsRequestContext context, String resourcename) throws CmsException {
return m_lockManager.isLocked(this, context, resourcename);
}
/**
* Determines, if the users may manage a project.<p>
* Only the manager of a project may publish it.
*
* All users are granted.
*
* @param context the current request context
* @return true, if the user manage this project
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public boolean isManagerOfProject(CmsRequestContext context) throws CmsException {
// is the user owner of the project?
if (context.currentUser().getId().equals(context.currentProject().getOwnerId())) {
// YES
return true;
}
if (isAdmin(context)) {
return true;
}
// get all groups of the user
Vector groups = getGroupsOfUser(context, context.currentUser().getName());
for (int i = 0; i < groups.size(); i++) {
// is this a managergroup for this project?
if (((CmsGroup)groups.elementAt(i)).getId().equals(context.currentProject().getManagerGroupId())) {
// this group is manager of the project
return true;
}
}
// this user is not manager of this project
return false;
}
/**
* Determines if the user is a member of the "Projectmanagers" group.<p>
*
* All users are granted.
*
* @param context the current request context
* @return true, if the users current group is the projectleader-group, else it returns false
* @throws CmsException if operation was not succesful
*/
public boolean isProjectManager(CmsRequestContext context) throws CmsException {
return userInGroup(context, context.currentUser().getName(), OpenCms.getDefaultUsers().getGroupProjectmanagers());
}
/**
* Checks if a project is the tempfile project.<p>
* @param project the project to test
* @return true if the project is the tempfile project
*/
public boolean isTempfileProject(CmsProject project) {
return project.getName().equals("tempFileProject");
}
/**
* Determines if the user is a member of the default users group.<p>
*
* All users are granted.
*
* @param context the current request context
* @return true, if the users current group is the projectleader-group, else it returns false
* @throws CmsException if operation was not succesful
*/
public boolean isUser(CmsRequestContext context) throws CmsException {
return userInGroup(context, context.currentUser().getName(), OpenCms.getDefaultUsers().getGroupUsers());
}
/**
* Checks if this is a valid group for webusers.<p>
*
* @param group the group to be checked
* @return true if the group does not belong to users, administrators or projectmanagers
* @throws CmsException if operation was not succesful
*/
protected boolean isWebgroup(CmsGroup group) throws CmsException {
try {
CmsUUID user = m_userDriver.readGroup(OpenCms.getDefaultUsers().getGroupUsers()).getId();
CmsUUID admin = m_userDriver.readGroup(OpenCms.getDefaultUsers().getGroupAdministrators()).getId();
CmsUUID manager = m_userDriver.readGroup(OpenCms.getDefaultUsers().getGroupProjectmanagers()).getId();
if ((group.getId().equals(user)) || (group.getId().equals(admin)) || (group.getId().equals(manager))) {
return false;
} else {
CmsUUID parentId = group.getParentId();
// check if the group belongs to Users, Administrators or Projectmanager
if (!parentId.isNullUUID()) {
// check is the parentgroup is a webgroup
return isWebgroup(m_userDriver.readGroup(parentId));
}
}
} catch (CmsException e) {
throw e;
}
return true;
}
/**
* Checks if one of the resources VFS links (except the resource itself) resides in a "labeled" site folder.<p>
*
* This method is used when creating a new sibling (use the newResource parameter & action = 1) or deleting/importing a resource (call with action = 2).<p>
*
* @param context the current request context
* @param resource the resource
* @param newResource absolute path for a resource sibling which will be created
* @param action the action which has to be performed (1 = create VFS link, 2 all other actions)
* @return true if the flag should be set for the resource, otherwise false
* @throws CmsException if something goes wrong
*/
public boolean labelResource(CmsRequestContext context, CmsResource resource, String newResource, int action) throws CmsException {
// get the list of labeled site folders from the runtime property
List labeledSites = OpenCms.getWorkplaceManager().getLabelSiteFolders();
if (action == 1) {
// CASE 1: a new resource is created, check the sites
if (!resource.isLabeled()) {
// source isn't labeled yet, so check!
boolean linkInside = false;
boolean sourceInside = false;
Iterator i = labeledSites.iterator();
while (i.hasNext()) {
String curSite = (String)i.next();
if (newResource.startsWith(curSite)) {
// the link lies in a labeled site
linkInside = true;
}
if (resource.getRootPath().startsWith(curSite)) {
// the source lies in a labeled site
sourceInside = true;
}
}
// return true when either source or link is in labeled site, otherwise false
return (linkInside != sourceInside);
}
// resource is already labeled
return false;
} else {
// CASE 2: the resource will be deleted or created (import)
// check if at least one of the other siblings resides inside a "labeled site"
// and if at least one of the other siblings resides outside a "labeled site"
boolean isInside = false;
boolean isOutside = false;
// check if one of the other vfs links lies in a labeled site folder
List vfsLinkList = m_vfsDriver.readSiblings(context.currentProject(), resource, false);
setFullResourceNames(context, vfsLinkList);
Iterator i = vfsLinkList.iterator();
while (i.hasNext() && (!isInside || !isOutside)) {
CmsResource currentResource = (CmsResource)i.next();
if (currentResource.equals(resource)) {
// dont't check the resource itself!
continue;
}
String curPath = currentResource.getRootPath();
boolean curInside = false;
for (int k = 0; k < labeledSites.size(); k++) {
if (curPath.startsWith((String)labeledSites.get(k))) {
// the link is in the labeled site
isInside = true;
curInside = true;
break;
}
}
if (!curInside) {
// the current link was not found in labeled site, so it is outside
isOutside = true;
}
}
// now check the new resource name if present
if (newResource != null) {
boolean curInside = false;
for (int k = 0; k < labeledSites.size(); k++) {
if (newResource.startsWith((String)labeledSites.get(k))) {
// the new resource is in the labeled site
isInside = true;
curInside = true;
break;
}
}
if (!curInside) {
// the new resource was not found in labeled site, so it is outside
isOutside = true;
}
}
return (isInside && isOutside);
}
}
/**
* Returns the user, who had locked the resource.<p>
*
* A user can lock a resource, so he is the only one who can write this
* resource. This methods checks, if a resource was locked.
*
* @param context the current request context
* @param resource the resource
*
* @return the user, who had locked the resource.
*
* @throws CmsException will be thrown, if the user has not the rights for this resource
*/
public CmsUser lockedBy(CmsRequestContext context, CmsResource resource) throws CmsException {
return lockedBy(context, resource.getRootPath());
}
/**
* Returns the user, who had locked the resource.<p>
*
* A user can lock a resource, so he is the only one who can write this
* resource. This methods checks, if a resource was locked.
*
* @param context the current request context
* @param resourcename the complete name of the resource
*
* @return the user, who had locked the resource.
*
* @throws CmsException will be thrown, if the user has not the rights for this resource.
*/
public CmsUser lockedBy(CmsRequestContext context, String resourcename) throws CmsException {
return readUser(m_lockManager.getLock(this, context, resourcename).getUserId());
}
/**
* Locks a resource exclusively.<p>
*
* @param context the current request context
* @param resourcename the resource name that gets locked
* @throws CmsException if something goes wrong
*/
public void lockResource(CmsRequestContext context, String resourcename) throws CmsException {
lockResource(context, resourcename, CmsLock.C_MODE_COMMON);
}
/**
* Locks a resource exclusively.<p>
*
* @param context the current request context
* @param resourcename the resource name that gets locked
* @param mode flag indicating the mode (temporary or common) of a lock
* @throws CmsException if something goes wrong
*/
public void lockResource(CmsRequestContext context, String resourcename, int mode) throws CmsException {
CmsResource resource = readFileHeader(context, resourcename);
// check if the user has write access to the resource
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
if (resource.getState() != I_CmsConstants.C_STATE_UNCHANGED) {
// update the project flag of a modified resource as "modified inside the current project"
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), resource);
}
// add the resource to the lock dispatcher
m_lockManager.addResource(this, context, resource.getRootPath(), context.currentUser().getId(), context.currentProject().getId(), mode);
// update the resource cache
clearResourceCache();
// cw/060104 we must also clear the permission cache
m_permissionCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Attempts to authenticate a user into OpenCms with the given password.<p>
*
* For security reasons, all error / exceptions that occur here are "blocked" and
* a simple security exception is thrown.<p>
*
* @param username the name of the user to be logged in
* @param password the password of the user
* @param remoteAddress the ip address of the request
* @param userType the user type to log in (System user or Web user)
* @return the logged in users name
*
* @throws CmsSecurityException if login was not succesful
*/
public CmsUser loginUser(String username, String password, String remoteAddress, int userType) throws CmsSecurityException {
CmsUser newUser;
try {
// read the user from the driver to avoid the cache
newUser = m_userDriver.readUser(username, password, remoteAddress, userType);
} catch (Throwable t) {
// any error here: throw a security exception
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED, t);
}
// check if the "enabled" flag is set for the user
if (newUser.getFlags() != I_CmsConstants.C_FLAG_ENABLED) {
// user is disabled, throw a securiy exception
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED);
}
// set the last login time to the current time
newUser.setLastlogin(System.currentTimeMillis());
try {
// write the changed user object back to the user driver
m_userDriver.writeUser(newUser);
} catch (Throwable t) {
// any error here: throw a security exception
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED, t);
}
// update cache
putUserInCache(newUser);
// invalidate all user depdent caches
m_accessControlListCache.clear();
m_groupCache.clear();
m_userGroupsCache.clear();
m_resourceListCache.clear();
m_permissionCache.clear();
// return the user object read from the driver
return newUser;
}
/**
* Lookup and read the user or group with the given UUID.<p>
*
* @param principalId the UUID of the principal to lookup
* @return the principal (group or user) if found, otherwise null
*/
public I_CmsPrincipal lookupPrincipal(CmsUUID principalId) {
try {
CmsGroup group = m_userDriver.readGroup(principalId);
if (group != null) {
return (I_CmsPrincipal)group;
}
} catch (Exception e) {
// ignore this exception
}
try {
CmsUser user = readUser(principalId);
if (user != null) {
return (I_CmsPrincipal)user;
}
} catch (Exception e) {
// ignore this exception
}
return null;
}
/**
* Lookup and read the user or group with the given name.<p>
*
* @param principalName the name of the principal to lookup
* @return the principal (group or user) if found, otherwise null
*/
public I_CmsPrincipal lookupPrincipal(String principalName) {
try {
CmsGroup group = m_userDriver.readGroup(principalName);
if (group != null) {
return (I_CmsPrincipal)group;
}
} catch (Exception e) {
// ignore this exception
}
try {
CmsUser user = readUser(principalName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
if (user != null) {
return (I_CmsPrincipal)user;
}
} catch (Exception e) {
// ignore this exception
}
return null;
}
/**
* Moves the file.<p>
*
* This operation includes a copy and a delete operation. These operations
* are done with their security-checks.
*
* @param context the current request context
* @param sourceName the complete name of the sourcefile
* @param destinationName The complete m_path of the destinationfile
*
* @throws CmsException will be thrown, if the file couldn't be moved.
* The CmsException will also be thrown, if the user has not the rights
* for this resource.
*/
public void moveResource(CmsRequestContext context, String sourceName, String destinationName) throws CmsException {
// read the source file
CmsResource source = readFileHeader(context, sourceName);
if (source.isFile()) {
// file is copied as link
copyFile(context, sourceName, destinationName, true, true, I_CmsConstants.C_COPY_AS_SIBLING);
deleteFile(context, sourceName, I_CmsConstants.C_DELETE_OPTION_PRESERVE_SIBLINGS);
} else {
// folder is copied as link
copyFolder(context, sourceName, destinationName, true, true);
deleteFolder(context, sourceName);
}
// read the moved file
CmsResource destination = readFileHeader(context, destinationName);
// since the resource was copied as link, we have to update the date/user lastmodified
// its sufficient to use source instead of dest, since there is only one resource
destination.setDateLastModified(System.currentTimeMillis());
destination.setUserLastModified(context.currentUser().getId());
m_vfsDriver.writeResourceState(context.currentProject(), destination, C_UPDATE_STRUCTURE);
// lock the new resource
lockResource(context, destinationName);
/*
List modifiedResources = (List) new ArrayList();
modifiedResources.add(source);
modifiedResources.add(destination);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCES_MODIFIED, Collections.singletonMap("resources", modifiedResources)));
*/
}
/**
* Gets a new driver instance.<p>
*
* @param configuration the configurations
* @param driverName the driver name
* @param successiveDrivers the list of successive drivers
* @return the driver object
* @throws CmsException if something goes wrong
*/
public Object newDriverInstance(ExtendedProperties configuration, String driverName, List successiveDrivers) throws CmsException {
Class initParamClasses[] = {ExtendedProperties.class, List.class, CmsDriverManager.class };
Object initParams[] = {configuration, successiveDrivers, this };
Class driverClass = null;
Object driver = null;
try {
// try to get the class
driverClass = Class.forName(driverName);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : starting " + driverName);
}
// try to create a instance
driver = driverClass.newInstance();
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : initializing " + driverName);
}
// invoke the init-method of this access class
driver.getClass().getMethod("init", initParamClasses).invoke(driver, initParams);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : ok, finished");
}
} catch (Exception exc) {
String message = "Critical error while initializing " + driverName;
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("[CmsDriverManager] " + message);
}
exc.printStackTrace(System.err);
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
return driver;
}
/**
* Method to create a new instance of a driver.<p>
*
* @param configuration the configurations from the propertyfile
* @param driverName the class name of the driver
* @param driverPoolUrl the pool url for the driver
* @return an initialized instance of the driver
* @throws CmsException if something goes wrong
*/
public Object newDriverInstance(ExtendedProperties configuration, String driverName, String driverPoolUrl) throws CmsException {
Class initParamClasses[] = {ExtendedProperties.class, String.class, CmsDriverManager.class };
Object initParams[] = {configuration, driverPoolUrl, this };
Class driverClass = null;
Object driver = null;
try {
// try to get the class
driverClass = Class.forName(driverName);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : starting " + driverName);
}
// try to create a instance
driver = driverClass.newInstance();
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : initializing " + driverName);
}
// invoke the init-method of this access class
driver.getClass().getMethod("init", initParamClasses).invoke(driver, initParams);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : finished, assigned pool " + driverPoolUrl);
}
} catch (Exception exc) {
String message = "Critical error while initializing " + driverName;
if (OpenCms.getLog(this).isFatalEnabled()) {
OpenCms.getLog(this).fatal(message, exc);
}
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
return driver;
}
/**
* Method to create a new instance of a pool.<p>
*
* @param configurations the configurations from the propertyfile
* @param poolName the configuration name of the pool
* @return the pool url
* @throws CmsException if something goes wrong
*/
public String newPoolInstance(ExtendedProperties configurations, String poolName) throws CmsException {
String poolUrl = null;
try {
poolUrl = CmsDbPool.createDriverManagerConnectionPool(configurations, poolName);
} catch (Exception exc) {
String message = "Critical error while initializing resource pool " + poolName;
if (OpenCms.getLog(this).isFatalEnabled()) {
OpenCms.getLog(this).fatal(message, exc);
}
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
return poolUrl;
}
/**
* Returns the online project object.<p>
*
* @return the online project object
* @throws CmsException if something goes wrong
*
* @deprecated use readProject(I_CmsConstants.C_PROJECT_ONLINE_ID) instead
*/
public CmsProject onlineProject() throws CmsException {
return readProject(I_CmsConstants.C_PROJECT_ONLINE_ID);
}
/**
* Publishes a project.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param cms the current CmsObject
* @param context the current request context
* @param report a report object to provide the loggin messages
* @param publishList a Cms publish list
* @throws Exception if something goes wrong
* @see #getPublishList(CmsRequestContext, CmsResource, boolean, I_CmsReport)
*/
public synchronized void publishProject(CmsObject cms, CmsRequestContext context, CmsPublishList publishList, I_CmsReport report) throws Exception {
Vector changedResources = new Vector();
Vector changedModuleMasters = new Vector();
int publishProjectId = context.currentProject().getId();
boolean backupEnabled = OpenCms.getSystemInfo().isVersionHistoryEnabled();
int tagId = 0;
CmsResource directPublishResource = null;
// boolean flag whether the current user has permissions to publish the current project/direct published resource
boolean hasPublishPermissions = false;
// to publish a project/resource...
// the current user either has to be a member of the administrators group
hasPublishPermissions |= isAdmin(context);
// or he has to be a member of the project managers group
hasPublishPermissions |= isManagerOfProject(context);
if (publishList.isDirectPublish()) {
directPublishResource = readFileHeader(context, publishList.getDirectPublishResourceName(), true);
// or he has the explicit permission to direct publish a resource
hasPublishPermissions |= hasPermissions(context, directPublishResource, I_CmsConstants.C_DIRECT_PUBLISH, false);
}
// and the current project must be different from the online project
hasPublishPermissions &= (publishProjectId != I_CmsConstants.C_PROJECT_ONLINE_ID);
// and the project flags have to be set to zero
hasPublishPermissions &= (context.currentProject().getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED);
if (hasPublishPermissions) {
try {
if (backupEnabled) {
tagId = getBackupTagId();
} else {
tagId = 0;
}
int maxVersions = OpenCms.getSystemInfo().getVersionHistoryMaxCount();
// if we direct publish a file, check if all parent folders are already published
if (publishList.isDirectPublish()) {
CmsUUID parentID = publishList.getDirectPublishParentStructureId();
try {
getVfsDriver().readFolder(I_CmsConstants.C_PROJECT_ONLINE_ID, parentID);
} catch (CmsException e) {
report.println("Parent folder not published for resource " + publishList.getDirectPublishResourceName(), I_CmsReport.C_FORMAT_ERROR);
return;
}
}
m_projectDriver.publishProject(context, report, readProject(I_CmsConstants.C_PROJECT_ONLINE_ID), publishList, OpenCms.getSystemInfo().isVersionHistoryEnabled(), tagId, maxVersions);
// don't publish COS module data if a file/folder gets published directly
if (!publishList.isDirectPublish()) {
// now publish the module masters
Vector publishModules = new Vector();
cms.getRegistry().getModulePublishables(publishModules, null);
long publishDate = System.currentTimeMillis();
if (backupEnabled) {
try {
publishDate = m_backupDriver.readBackupProject(tagId).getPublishingDate();
} catch (CmsException e) {
// nothing to do
}
if (publishDate == 0) {
publishDate = System.currentTimeMillis();
}
}
for (int i = 0; i < publishModules.size(); i++) {
// call the publishProject method of the class with parameters:
// cms, m_enableHistory, project_id, version_id, publishDate, subId,
// the vector changedResources and the vector changedModuleMasters
try {
// The changed masters are added to the vector changedModuleMasters, so after the last module
// was published the vector contains the changed masters of all published modules
Class.forName((String) publishModules.elementAt(i)).getMethod("publishProject", new Class[] {CmsObject.class, Boolean.class, Integer.class, Integer.class, Long.class, Vector.class, Vector.class}).invoke(null, new Object[] {cms, new Boolean(OpenCms.getSystemInfo().isVersionHistoryEnabled()), new Integer(publishProjectId), new Integer(tagId), new Long(publishDate), changedResources, changedModuleMasters});
} catch (ClassNotFoundException ec) {
report.println(report.key("report.publish_class_for_module_does_not_exist_1") + (String) publishModules.elementAt(i) + report.key("report.publish_class_for_module_does_not_exist_2"), I_CmsReport.C_FORMAT_WARNING);
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error calling publish class of module " + (String) publishModules.elementAt(i), ec);
}
} catch (Exception ex) {
report.println(ex);
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error while publishing data of module " + (String) publishModules.elementAt(i), ex);
}
}
}
Iterator i = changedModuleMasters.iterator();
while (i.hasNext()) {
CmsPublishedResource currentCosResource = (CmsPublishedResource) i.next();
m_projectDriver.writePublishHistory(context.currentProject(), publishList.getPublishHistoryId(), tagId, currentCosResource.getContentDefinitionName(), currentCosResource.getMasterId(), currentCosResource.getType(), currentCosResource.getState());
}
}
} catch (CmsException e) {
throw e;
} finally {
this.clearResourceCache();
// the project was stored in the backuptables for history
//new projectmechanism: the project can be still used after publishing
// it will be deleted if the project_flag = C_PROJECT_STATE_TEMP
if (context.currentProject().getType() == I_CmsConstants.C_PROJECT_TYPE_TEMPORARY) {
m_projectDriver.deleteProject(context.currentProject());
try {
m_projectCache.remove(new Integer(publishProjectId));
} catch (Exception e) {
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn("Could not remove project " + publishProjectId + " from cache");
}
}
if (publishProjectId == context.currentProject().getId()) {
cms.getRequestContext().setCurrentProject(cms.readProject(I_CmsConstants.C_PROJECT_ONLINE_ID));
}
}
// finally set the refresh signal to another server if necessary
if (m_refresh.length() > 0) {
try {
URL url = new URL(m_refresh);
URLConnection con = url.openConnection();
con.connect();
InputStream in = con.getInputStream();
in.close();
//System.err.println(in.toString());
} catch (Exception ex) {
throw new CmsException(0, ex);
}
}
}
} else if (publishProjectId == I_CmsConstants.C_PROJECT_ONLINE_ID) {
throw new CmsSecurityException("[" + getClass().getName() + "] could not publish project " + publishProjectId, CmsSecurityException.C_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT);
} else if (!isAdmin(context) && !isManagerOfProject(context)) {
throw new CmsSecurityException("[" + getClass().getName() + "] could not publish project " + publishProjectId, CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] could not publish project " + publishProjectId, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Stores a user in the user cache.<p>
*
* @param user the user to be stored in the cache
*/
private void putUserInCache(CmsUser user) {
m_userCache.put(getUserCacheKey(user.getName(), user.getType()), user);
m_userCache.put(getUserCacheKey(user.getId()), user);
}
/**
* Reads an access control entry from the cms.<p>
*
* The access control entries of a resource are readable by everyone.
*
* @param context the current request context
* @param resource the resource
* @param principal the id of a group or a user any other entity
* @return an access control entry that defines the permissions of the entity for the given resource
* @throws CmsException if something goes wrong
*/
public CmsAccessControlEntry readAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsUUID principal) throws CmsException {
return m_userDriver.readAccessControlEntry(context.currentProject(), resource.getResourceId(), principal);
}
/**
* Reads the agent of a task from the OpenCms.<p>
*
* @param task the task to read the agent from
* @return the owner of a task
* @throws CmsException if something goes wrong
*/
public CmsUser readAgent(CmsTask task) throws CmsException {
return readUser(task.getAgentUser());
}
/**
* Reads all file headers of a file in the OpenCms.<p>
*
* This method returns a vector with the histroy of all file headers, i.e.
* the file headers of a file, independent of the project they were attached to.<br>
* The reading excludes the filecontent.
* Access is granted, if:
* <ul>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @return vector of file headers read from the Cms
* @throws CmsException if operation was not succesful
*/
public List readAllBackupFileHeaders(CmsRequestContext context, String filename) throws CmsException {
CmsResource cmsFile = readFileHeader(context, filename);
// check if the user has read access
checkPermissions(context, cmsFile, I_CmsConstants.C_READ_ACCESS);
// access to all subfolders was granted - return the file-history (newest version first)
List backupFileHeaders = m_backupDriver.readBackupFileHeaders(cmsFile.getResourceId());
if (backupFileHeaders != null && backupFileHeaders.size() > 1) {
// change the order of the list
Collections.reverse(backupFileHeaders);
}
setFullResourceNames(context, backupFileHeaders);
return backupFileHeaders;
}
/**
* Select all projectResources from an given project.<p>
*
* @param context the current request context
* @param projectId the project in which the resource is used
* @return vector of all resources in the project
* @throws CmsException if operation was not succesful
*/
public Vector readAllProjectResources(CmsRequestContext context, int projectId) throws CmsException {
CmsProject project = m_projectDriver.readProject(projectId);
List result = setFullResourceNames(context, m_projectDriver.readProjectResources(project));
return new Vector(result);
}
/**
* Reads all property definitions of a given resourcetype.<p>
*
* @param context the current request context
* @param resourceType the resource type to read all property defnitions from
* @return vector of property defintions
* @throws CmsException if operation was not succesful
*/
private Vector readAllPropertydefinitions(CmsRequestContext context, I_CmsResourceType resourceType) throws CmsException {
Vector returnValue = m_vfsDriver.readPropertyDefinitions(context.currentProject().getId(), resourceType);
Collections.sort(returnValue);
return returnValue;
}
/**
* Reads all propertydefinitions for the given resource type.<p>
*
* All users are granted.
*
* @param context the current request context
* @param resourceType te resource type to read the propertydefinitions for
* @return propertydefinitions a Vector with propertydefefinitions for the resource type. The Vector is maybe empty.
* @throws CmsException if something goes wrong
*/
public Vector readAllPropertydefinitions(CmsRequestContext context, int resourceType) throws CmsException {
I_CmsResourceType resType = getResourceType(resourceType);
return readAllPropertydefinitions(context, resType);
}
/**
* Reads all propertydefinitions for the given resource type.<p>
*
* All users are granted.
*
* @param context the current request context
* @param resourcetype the name of the resource type to read the propertydefinitions for
* @return propertydefinitions a Vector with propertydefefinitions for the resource type. The Vector is maybe empty.
* @throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(CmsRequestContext context, String resourcetype) throws CmsException {
I_CmsResourceType resType = getResourceType(resourcetype);
return readAllPropertydefinitions(context, resType);
}
/**
* Reads all sub-resources (including deleted resources) of a specified folder
* by traversing the sub-tree in a depth first search.<p>
*
* The specified folder is not included in the result list.
*
* @param context the current request context
* @param resourcename the resource name
* @param resourceType <0 if files and folders should be read, 0 if only folders should be read, >0 if only files should be read
* @return a list with all sub-resources
* @throws CmsException if something goes wrong
*/
public List readAllSubResourcesInDfs(CmsRequestContext context, String resourcename, int resourceType) throws CmsException {
List result = (List)new ArrayList();
Vector unvisited = new Vector();
CmsFolder currentFolder = null;
Enumeration unvisitedFolders = null;
boolean isFirst = true;
currentFolder = readFolder(context, resourcename, true);
unvisited.add(currentFolder);
while (unvisited.size() > 0) {
// visit all unvisited folders
unvisitedFolders = unvisited.elements();
while (unvisitedFolders.hasMoreElements()) {
currentFolder = (CmsFolder)unvisitedFolders.nextElement();
// remove the current folder from the list of unvisited folders
unvisited.remove(currentFolder);
if (!isFirst && resourceType <= CmsResourceTypeFolder.C_RESOURCE_TYPE_ID) {
// add the current folder to the result list
result.add(currentFolder);
}
if (resourceType != CmsResourceTypeFolder.C_RESOURCE_TYPE_ID) {
// add all sub-files in the current folder to the result list
result.addAll(getSubFiles(context, currentFolder.getRootPath(), true));
}
// add all sub-folders in the current folder to the list of unvisited folders
// to visit them in the next iteration
unvisited.addAll(getSubFolders(context, currentFolder.getRootPath(), true));
if (isFirst) {
isFirst = false;
}
}
}
// TODO the calculated resource list should be cached
return result;
}
/**
* Reads a file from the history of the Cms.<p>
*
* The reading includes the filecontent. <
* A file is read from the backup resources.
*
* @param context the current request context
* @param tagId the id of the tag of the file
* @param filename the name of the file to be read
* @return the file read from the Cms.
* @throws CmsException if operation was not succesful
*/
public CmsBackupResource readBackupFile(CmsRequestContext context, int tagId, String filename) throws CmsException {
CmsBackupResource backupResource = null;
try {
List path = readPath(context, filename, false);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
backupResource = m_backupDriver.readBackupFile(tagId, resource.getResourceId());
backupResource.setFullResourceName(filename);
} catch (CmsException exc) {
throw exc;
}
updateContextDates(context, backupResource);
return backupResource;
}
/**
* Reads a file header from the history of the Cms.<p>
*
* The reading excludes the filecontent.
* A file header is read from the backup resources.
*
* @param context the current request context
* @param tagId the id of the tag revisiton of the file
* @param filename the name of the file to be read
* @return the file read from the Cms.
* @throws CmsException if operation was not succesful
*/
public CmsBackupResource readBackupFileHeader(CmsRequestContext context, int tagId, String filename) throws CmsException {
CmsResource cmsFile = readFileHeader(context, filename);
CmsBackupResource resource = null;
try {
resource = m_backupDriver.readBackupFileHeader(tagId, cmsFile.getResourceId());
resource.setFullResourceName(filename);
} catch (CmsException exc) {
throw exc;
}
updateContextDates(context, resource);
return resource;
}
/**
* Reads the backupinformation of a project from the Cms.<p>
*
* @param tagId the tagId of the project
* @return the backup project
* @throws CmsException if something goes wrong
*/
public CmsBackupProject readBackupProject(int tagId) throws CmsException {
return m_backupDriver.readBackupProject(tagId);
}
/**
* Reads all resources that are inside and changed in a specified project.<p>
*
* @param context the current request context
* @param projectId the ID of the project
* @param resourceType <0 if files and folders should be read, 0 if only folders should be read, >0 if only files should be read
* @return a List with all resources inside the specified project
* @throws CmsException if somethong goes wrong
*/
public List readChangedResourcesInsideProject(CmsRequestContext context, int projectId, int resourceType) throws CmsException {
List projectResources = readProjectResources(readProject(projectId));
List result = (List)new ArrayList();
String currentProjectResource = null;
List resources = (List)new ArrayList();
CmsResource currentResource = null;
CmsLock currentLock = null;
for (int i = 0; i < projectResources.size(); i++) {
// read all resources that are inside the project by visiting each project resource
currentProjectResource = (String)projectResources.get(i);
try {
currentResource = readFileHeader(context, currentProjectResource, true);
if (currentResource.isFolder()) {
resources.addAll(readAllSubResourcesInDfs(context, currentProjectResource, resourceType));
} else {
resources.add(currentResource);
}
} catch (CmsException e) {
// the project resource probably doesnt exist (anymore)...
if (e.getType() != CmsException.C_NOT_FOUND) {
throw e;
}
}
}
for (int j = 0; j < resources.size(); j++) {
currentResource = (CmsResource)resources.get(j);
currentLock = getLock(context, currentResource.getRootPath());
if (currentResource.getState() != I_CmsConstants.C_STATE_UNCHANGED) {
if ((currentLock.isNullLock() && currentResource.getProjectLastModified() == projectId) || (currentLock.getUserId().equals(context.currentUser().getId()) && currentLock.getProjectId() == projectId)) {
// add only resources that are
// - inside the project,
// - changed in the project,
// - either unlocked, or locked for the current user in the project
result.add(currentResource);
}
}
}
resources.clear();
resources = null;
// TODO the calculated resource lists should be cached
return result;
}
/**
* Gets the Crontable.<p>
*
* All users are garnted.
*
* @return the crontable
* @throws CmsException if something goes wrong
*/
public String readCronTable() throws CmsException {
String retValue = (String)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_CRONTABLE);
if (retValue == null) {
return "";
} else {
return retValue;
}
}
/**
* Reads a file from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @return the file read from the VFS
* @throws CmsException if operation was not succesful
*/
public CmsFile readFile(CmsRequestContext context, String filename) throws CmsException {
return readFile(context, filename, false);
}
/**
* Reads a file from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @param includeDeleted flag to include deleted resources
* @return the file read from the VFS
* @throws CmsException if operation was not succesful
*/
public CmsFile readFile(CmsRequestContext context, String filename, boolean includeDeleted) throws CmsException {
CmsFile file = null;
try {
List path = readPath(context, filename, false);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
file = m_vfsDriver.readFile(context.currentProject().getId(), includeDeleted, resource.getStructureId());
if (file.isFolder() && (filename.charAt(filename.length() - 1) != '/')) {
filename += "/";
}
file.setFullResourceName(filename);
} catch (CmsException exc) {
// the resource was not readable
throw exc;
}
// check if the user has read access to the file
checkPermissions(context, file, I_CmsConstants.C_READ_ACCESS);
// update date info in context
updateContextDates(context, file);
// access to all subfolders was granted - return the file.
return file;
}
/**
* Gets the known file extensions (=suffixes).<p>
*
* All users are granted access.<p>
*
* @return Hashtable with file extensions as Strings
* @throws CmsException if operation was not succesful
*/
public Hashtable readFileExtensions() throws CmsException {
Hashtable res = (Hashtable)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS);
return ((res != null) ? res : new Hashtable());
}
/**
* Reads a file header from the Cms.<p>
*
* The reading excludes the filecontent.
* A file header can be read from an offline project or the online project.
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @return the file read from the Cms
* @throws CmsException if operation was not succesful
*/
public CmsResource readFileHeader(CmsRequestContext context, String filename) throws CmsException {
return readFileHeader(context, filename, false);
}
/**
* Reads a file header of another project of the Cms.<p>
*
* The reading excludes the filecontent.
* A file header can be read from an offline project or the online project.
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param projectId the id of the project to read the file from
* @param filename the name of the file to be read
* @param includeDeleted flag to include the deleted resources
* @return the file read from the Cms
* @throws CmsException if operation was not succesful
*/
public CmsResource readFileHeaderInProject(int projectId, String filename, boolean includeDeleted) throws CmsException {
if (filename == null) {
return null;
}
if (CmsResource.isFolder(filename)) {
return readFolderInProject(projectId, filename);
}
List path = readPathInProject(projectId, filename, includeDeleted);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
List projectResources = readProjectResources(readProject(projectId));
// set full resource name
resource.setFullResourceName(filename);
if (CmsProject.isInsideProject(projectResources, resource)) {
return resource;
}
throw new CmsResourceNotFoundException("File " + filename + " is not inside project with ID " + projectId);
}
/**
* Reads a file from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
* @param context the context (user/project) of this request
* @param projectId the id of the project to read the file from
* @param structureId the structure id of the file
* @param includeDeleted already deleted resources are found, too
* @return the file read from the VFS
* @throws CmsException if operation was not succesful
*/
public CmsFile readFileInProject(CmsRequestContext context, int projectId, CmsUUID structureId, boolean includeDeleted) throws CmsException {
CmsFile cmsFile = null;
try {
cmsFile = m_vfsDriver.readFile(projectId, includeDeleted, structureId);
cmsFile.setFullResourceName(readPathInProject(projectId, cmsFile, includeDeleted));
} catch (CmsException exc) {
// the resource was not readable
throw exc;
}
// check if the user has read access to the file
checkPermissions(context, cmsFile, I_CmsConstants.C_READ_ACCESS);
// access to all subfolders was granted - return the file.
return cmsFile;
}
/**
* Reads all files from the Cms, that are of the given type.<p>
*
* @param context the context (user/project) of this request
* @param projectId A project id for reading online or offline resources
* @param resourcetype the type of the files
* @return a Vector of files
* @throws CmsException if operation was not succesful
*/
public Vector readFilesByType(CmsRequestContext context, int projectId, int resourcetype) throws CmsException {
Vector resources = new Vector();
resources = m_vfsDriver.readFiles(projectId, resourcetype);
Vector retValue = new Vector(resources.size());
// check if the user has view access
Enumeration e = resources.elements();
while (e.hasMoreElements()) {
CmsFile res = (CmsFile)e.nextElement();
if (hasPermissions(context, res, I_CmsConstants.C_VIEW_ACCESS, false)) {
res.setFullResourceName(readPath(context, res, true));
retValue.addElement(res);
updateContextDates(context, res);
}
}
return retValue;
}
/**
* Reads a folder from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param folderId the id of the folder to be read
* @param includeDeleted include the folder it it is marked as deleted
* @return folder the read folder.
* @throws CmsException if the folder couldn't be read. The CmsException will also be thrown, if the user has not the rights for this resource.
*/
public CmsFolder readFolder(CmsRequestContext context, CmsUUID folderId, boolean includeDeleted) throws CmsException {
CmsFolder folder = null;
try {
folder = m_vfsDriver.readFolder(context.currentProject().getId(), folderId);
folder.setFullResourceName(readPath(context, folder, includeDeleted));
} catch (CmsException exc) {
throw exc;
}
// check if the user has write access to the folder
checkPermissions(context, folder, I_CmsConstants.C_READ_ACCESS);
// update date info in context
updateContextDates(context, folder);
// access was granted - return the folder.
if ((folder.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted)) {
throw new CmsException("[" + getClass().getName() + "]" + context.removeSiteRoot(readPath(context, folder, includeDeleted)), CmsException.C_RESOURCE_DELETED);
} else {
return folder;
}
}
/**
* Reads a folder from the Cms.<p>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param foldername the complete m_path of the folder to be read
* @return folder the read folder
* @throws CmsException if the folder couldn't be read. The CmsException will also be thrown, if the user has not the rights for this resource.
*/
public CmsFolder readFolder(CmsRequestContext context, String foldername) throws CmsException {
return readFolder(context, foldername, false);
}
/**
* Reads a file header from the Cms.<p>
*
* The reading excludes the filecontent.
* A file header can be read from an offline project or the online project.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @param includeDeleted flag to include the deleted resources
* @return the file read from the Cms
* @throws CmsException if operation was not succesful
*/
public CmsResource readFileHeader(CmsRequestContext context, String filename, boolean includeDeleted) throws CmsException {
List path = readPath(context, filename, includeDeleted);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
// check if the user has read access to the file
checkPermissions(context, resource, I_CmsConstants.C_READ_OR_VIEW_ACCESS);
// set full resource name
if (resource.isFolder()) {
if ((resource.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted)) {
// resource was deleted
throw new CmsException("[" + this.getClass().getName() + "]" + context.removeSiteRoot(readPath(context, resource, includeDeleted)), CmsException.C_RESOURCE_DELETED);
}
// resource.setFullResourceName(filename + I_CmsConstants.C_FOLDER_SEPARATOR);
resource = new CmsFolder(resource);
resource.setFullResourceName(filename);
} else {
resource.setFullResourceName(filename);
}
// update date info in context
updateContextDates(context, resource);
// access was granted - return the file-header.
return resource;
}
/**
* Reads a folder from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param foldername the complete m_path of the folder to be read
* @param includeDeleted include the folder it it is marked as deleted
* @return folder the read folder
* @throws CmsException if the folder couldn't be read. The CmsException will also be thrown, if the user has not the rights for this resource.
*/
public CmsFolder readFolder(CmsRequestContext context, String foldername, boolean includeDeleted) throws CmsException {
return (CmsFolder)readFileHeader(context, foldername, includeDeleted);
}
/**
* Reads a folder from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param projectId the project to read the folder from
* @param foldername the complete m_path of the folder to be read
* @return folder the read folder.
* @throws CmsException if the folder couldn't be read. The CmsException will also be thrown, if the user has not the rights for this resource
*/
protected CmsFolder readFolderInProject(int projectId, String foldername) throws CmsException {
if (foldername == null) {
return null;
}
if (!CmsResource.isFolder(foldername)) {
foldername += "/";
}
List path = readPathInProject(projectId, foldername, false);
CmsFolder folder = (CmsFolder)path.get(path.size() - 1);
List projectResources = readProjectResources(readProject(projectId));
// now set the full resource name
folder.setFullResourceName(foldername);
if (CmsProject.isInsideProject(projectResources, folder)) {
return folder;
}
throw new CmsResourceNotFoundException("Folder " + foldername + " is not inside project with ID " + projectId);
}
/**
* Reads all given tasks from a user for a project.<p>
*
* @param projectId the id of the Project in which the tasks are defined
* @param ownerName owner of the task
* @param taskType task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW.
* @param orderBy chooses, how to order the tasks
* @param sort sorting of the tasks
* @return vector of tasks
* @throws CmsException if something goes wrong
*/
public Vector readGivenTasks(int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException {
CmsProject project = null;
CmsUser owner = null;
if (ownerName != null) {
owner = readUser(ownerName);
}
if (projectId != I_CmsConstants.C_UNKNOWN_ID) {
project = readProject(projectId);
}
return m_workflowDriver.readTasks(project, null, owner, null, taskType, orderBy, sort);
}
/**
* Reads the group of a project from the OpenCms.<p>
*
* @param project the project to read from
* @return the group of a resource
*/
public CmsGroup readGroup(CmsProject project) {
// try to read group form cache
CmsGroup group = (CmsGroup)m_groupCache.get(new CacheId(project.getGroupId()));
if (group == null) {
try {
group = m_userDriver.readGroup(project.getGroupId());
} catch (CmsException exc) {
if (exc.getType() == CmsException.C_NO_GROUP) {
// the group does not exist any more - return a dummy-group
return new CmsGroup(CmsUUID.getNullUUID(), CmsUUID.getNullUUID(), project.getGroupId() + "", "deleted group", 0);
}
}
m_groupCache.put(new CacheId(group), group);
}
return group;
}
/**
* Reads the group (role) of a task from the OpenCms.<p>
*
* @param task the task to read from
* @return the group of a resource
* @throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(CmsTask task) throws CmsException {
return m_userDriver.readGroup(task.getRole());
}
/**
* Returns a group object.<p>
*
* @param groupname the name of the group that is to be read
* @return the requested group
* @throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(String groupname) throws CmsException {
CmsGroup group = null;
// try to read group form cache
group = (CmsGroup)m_groupCache.get(new CacheId(groupname));
if (group == null) {
group = m_userDriver.readGroup(groupname);
m_groupCache.put(new CacheId(group), group);
}
return group;
}
/**
* Returns a group object.<p>
*
* All users are granted.
*
* @param groupId the id of the group that is to be read
* @return the requested group
* @throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(CmsUUID groupId) throws CmsException {
return m_userDriver.readGroup(groupId);
}
/**
* Gets the Linkchecktable.<p>
*
* All users are garnted
*
* @return the linkchecktable.
* @throws CmsException if operation was not succesful
*/
public Hashtable readLinkCheckTable() throws CmsException {
Hashtable retValue = (Hashtable)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_LINKCHECKTABLE);
if (retValue == null) {
return new Hashtable();
} else {
return retValue;
}
}
/**
* Reads the manager group of a project from the OpenCms.<p>
*
* All users are granted.
*
* @param project the project to read from
* @return the group of a resource
*/
public CmsGroup readManagerGroup(CmsProject project) {
CmsGroup group = null;
// try to read group form cache
group = (CmsGroup)m_groupCache.get(new CacheId(project.getManagerGroupId()));
if (group == null) {
try {
group = m_userDriver.readGroup(project.getManagerGroupId());
} catch (CmsException exc) {
if (exc.getType() == CmsException.C_NO_GROUP) {
// the group does not exist any more - return a dummy-group
return new CmsGroup(CmsUUID.getNullUUID(), CmsUUID.getNullUUID(), project.getManagerGroupId() + "", "deleted group", 0);
}
}
m_groupCache.put(new CacheId(group), group);
}
return group;
}
/**
* Reads the original agent of a task from the OpenCms.<p>
*
* @param task the task to read the original agent from
* @return the owner of a task
* @throws CmsException if something goes wrong
*/
public CmsUser readOriginalAgent(CmsTask task) throws CmsException {
return readUser(task.getOriginalUser());
}
/**
* Reads the owner of a project from the OpenCms.<p>
*
* @param project the project to get the owner from
* @return the owner of a resource
* @throws CmsException if something goes wrong
*/
public CmsUser readOwner(CmsProject project) throws CmsException {
return readUser(project.getOwnerId());
}
/**
* Reads the owner (initiator) of a task from the OpenCms.<p>
*
* @param task the task to read the owner from
* @return the owner of a task
* @throws CmsException if something goes wrong
*/
public CmsUser readOwner(CmsTask task) throws CmsException {
return readUser(task.getInitiatorUser());
}
/**
* Reads the owner of a tasklog from the OpenCms.<p>
*
* @param log the tasklog
* @return the owner of a resource
* @throws CmsException if something goes wrong
*/
public CmsUser readOwner(CmsTaskLog log) throws CmsException {
return readUser(log.getUser());
}
/**
* Reads the package path of the system.<p>
* This path is used for db-export and db-import and all module packages.
*
* @return the package path
* @throws CmsException if operation was not successful
*/
public String readPackagePath() throws CmsException {
return (String)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_PACKAGEPATH);
}
/**
* Builds the path for a given CmsResource including the site root, e.g. <code>/default/vfs/some_folder/index.html</code>.<p>
*
* This is done by climbing up the path to the root folder by using the resource parent-ID's.
* Use this method with caution! Results are cached but reading path's increases runtime costs.
*
* @param context the context (user/project) of the request
* @param resource the resource
* @param includeDeleted include resources that are marked as deleted
* @return String the path of the resource
* @throws CmsException if something goes wrong
*/
public String readPath(CmsRequestContext context, CmsResource resource, boolean includeDeleted) throws CmsException {
return readPathInProject(context.currentProject().getId(), resource, includeDeleted);
}
/**
* Builds a list of resources for a given path.<p>
*
* Use this method if you want to select a resource given by it's full filename and path.
* This is done by climbing down the path from the root folder using the parent-ID's and
* resource names. Use this method with caution! Results are cached but reading path's
* inevitably increases runtime costs.
*
* @param context the context (user/project) of the request
* @param path the requested path
* @param includeDeleted include resources that are marked as deleted
* @return List of CmsResource's
* @throws CmsException if something goes wrong
*/
public List readPath(CmsRequestContext context, String path, boolean includeDeleted) throws CmsException {
return readPathInProject(context.currentProject().getId(), path, includeDeleted);
}
/**
* Builds the path for a given CmsResource including the site root, e.g. <code>/default/vfs/some_folder/index.html</code>.<p>
*
* This is done by climbing up the path to the root folder by using the resource parent-ID's.
* Use this method with caution! Results are cached but reading path's increases runtime costs.<p>
*
* @param projectId the project to lookup the resource
* @param resource the resource
* @param includeDeleted include resources that are marked as deleted
* @return String the path of the resource
* @throws CmsException if something goes wrong
*/
public String readPathInProject(int projectId, CmsResource resource, boolean includeDeleted) throws CmsException {
if (resource.hasFullResourceName()) {
// we did already what we want to do- no further operations required here!
return resource.getRootPath();
}
// the current resource
CmsResource currentResource = resource;
// the path of an already cached parent-ID
String cachedPath = null;
// the current path
String path = "";
// the current parent-ID
CmsUUID currentParentId = null;
// the initial parent-ID is used as a cache key
CmsUUID parentId = currentResource.getParentStructureId();
// key to get a cached parent resource
String resourceCacheKey = null;
// key to get a cached path
String pathCacheKey = null;
// the path + resourceName is the full resource name
String resourceName = currentResource.getName();
// add an optional / to the path if the resource is a folder
boolean isFolder = currentResource.getType() == CmsResourceTypeFolder.C_RESOURCE_TYPE_ID;
while (!(currentParentId = currentResource.getParentStructureId()).equals(CmsUUID.getNullUUID())) {
// see if we can find an already cached path for the current parent-ID
pathCacheKey = getCacheKey("path", projectId, currentParentId.toString());
if ((cachedPath = (String)m_resourceCache.get(pathCacheKey)) != null) {
path = cachedPath + path;
break;
}
// see if we can find a cached parent-resource for the current parent-ID
resourceCacheKey = getCacheKey("parent", projectId, currentParentId.toString());
if ((currentResource = (CmsResource)m_resourceCache.get(resourceCacheKey)) == null) {
currentResource = m_vfsDriver.readFileHeader(projectId, currentParentId, includeDeleted);
m_resourceCache.put(resourceCacheKey, currentResource);
}
if (!currentResource.getParentStructureId().equals(CmsUUID.getNullUUID())) {
// add a folder different from the root folder
path = currentResource.getName() + I_CmsConstants.C_FOLDER_SEPARATOR + path;
} else {
// add the root folder
path = currentResource.getName() + path;
}
}
// cache the calculated path
pathCacheKey = getCacheKey("path", projectId, parentId.toString());
m_resourceCache.put(pathCacheKey, path);
// build the full path of the resource
resourceName = path + resourceName;
if (isFolder && !resourceName.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
resourceName += I_CmsConstants.C_FOLDER_SEPARATOR;
}
// set the calculated path in the calling resource
resource.setFullResourceName(resourceName);
return resourceName;
}
/**
* Builds a list of resources for a given path.<p>
*
* Use this method if you want to select a resource given by it's full filename and path.
* This is done by climbing down the path from the root folder using the parent-ID's and
* resource names. Use this method with caution! Results are cached but reading path's
* inevitably increases runtime costs.<p>
*
* @param projectId the project to lookup the resource
* @param path the requested path
* @param includeDeleted include resources that are marked as deleted
* @return List of CmsResource's
* @throws CmsException if something goes wrong
*/
public List readPathInProject(int projectId, String path, boolean includeDeleted) throws CmsException {
// splits the path into folder and filename tokens
StringTokenizer tokens = null;
// # of folders in the path
int folderCount = 0;
// true if the path doesn't end with a folder
boolean lastResourceIsFile = false;
// holds the CmsResource instances in the path
List pathList = null;
// the current path token
String currentResourceName = null;
// the current path
String currentPath = null;
// the current resource
CmsResource currentResource = null;
// this is a comment. i love comments!
int i = 0, count = 0;
// key to cache the resources
String cacheKey = null;
// the parent resource of the current resource
CmsResource lastParent = null;
tokens = new StringTokenizer(path, I_CmsConstants.C_FOLDER_SEPARATOR);
// the root folder is no token in the path but a resource which has to be added to the path
count = tokens.countTokens() + 1;
pathList = (List)new ArrayList(count);
folderCount = count;
if (!path.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
folderCount--;
lastResourceIsFile = true;
}
// read the root folder, coz it's ID is required to read any sub-resources
currentResourceName = I_CmsConstants.C_ROOT;
currentPath = I_CmsConstants.C_ROOT;
cacheKey = getCacheKey(null, projectId, currentPath);
if ((currentResource = (CmsResource)m_resourceCache.get(cacheKey)) == null) {
currentResource = m_vfsDriver.readFolder(projectId, CmsUUID.getNullUUID(), currentResourceName);
currentResource.setFullResourceName(currentPath);
m_resourceCache.put(cacheKey, currentResource);
}
pathList.add(0, currentResource);
lastParent = currentResource;
if (count == 1) {
// the root folder was requested- no further operations required
return pathList;
}
currentResourceName = tokens.nextToken();
// read the folder resources in the path /a/b/c/
for (i = 1; i < folderCount; i++) {
currentPath += currentResourceName + I_CmsConstants.C_FOLDER_SEPARATOR;
// read the folder
cacheKey = getCacheKey(null, projectId, currentPath);
if ((currentResource = (CmsResource)m_resourceCache.get(cacheKey)) == null) {
currentResource = m_vfsDriver.readFolder(projectId, lastParent.getStructureId(), currentResourceName);
currentResource.setFullResourceName(currentPath);
m_resourceCache.put(cacheKey, currentResource);
}
pathList.add(i, currentResource);
lastParent = currentResource;
if (i < folderCount - 1) {
currentResourceName = tokens.nextToken();
}
}
// read the (optional) last file resource in the path /x.html
if (lastResourceIsFile) {
if (tokens.hasMoreTokens()) {
// this will only be false if a resource in the
// top level root folder (e.g. "/index.html") was requested
currentResourceName = tokens.nextToken();
}
currentPath += currentResourceName;
// read the file
cacheKey = getCacheKey(null, projectId, currentPath);
if ((currentResource = (CmsResource)m_resourceCache.get(cacheKey)) == null) {
currentResource = m_vfsDriver.readFileHeader(projectId, lastParent.getStructureId(), currentResourceName, includeDeleted);
currentResource.setFullResourceName(currentPath);
m_resourceCache.put(cacheKey, currentResource);
}
pathList.add(i, currentResource);
}
return pathList;
}
/**
* Reads a project from the Cms.<p>
*
* @param task the task to read the project of
* @return the project read from the cms
* @throws CmsException if something goes wrong
*/
public CmsProject readProject(CmsTask task) throws CmsException {
// read the parent of the task, until it has no parents.
while (task.getParent() != 0) {
task = readTask(task.getParent());
}
return m_projectDriver.readProject(task);
}
/**
* Reads a project from the Cms.<p>
*
* @param id the id of the project
* @return the project read from the cms
* @throws CmsException if something goes wrong.
*/
public CmsProject readProject(int id) throws CmsException {
CmsProject project = null;
project = (CmsProject)m_projectCache.get(new Integer(id));
if (project == null) {
project = m_projectDriver.readProject(id);
m_projectCache.put(new Integer(id), project);
}
return project;
}
/**
* Reads a project from the Cms.<p>
*
* @param name the name of the project
* @return the project read from the cms
* @throws CmsException if something goes wrong.
*/
public CmsProject readProject(String name) throws CmsException {
CmsProject project = null;
project = (CmsProject)m_projectCache.get(name);
if (project == null) {
project = m_projectDriver.readProject(name);
m_projectCache.put(name, project);
}
return project;
}
/**
* Reads log entries for a project.<p>
*
* @param projectId the id of the projec for tasklog to read
* @return a Vector of new TaskLog objects
* @throws CmsException if something goes wrong.
*/
public Vector readProjectLogs(int projectId) throws CmsException {
return m_projectDriver.readProjectLogs(projectId);
}
/**
* Returns the list of all resource names that define the "view" of the given project.<p>
*
* @param project the project to get the project resources for
* @return the list of all resource names that define the "view" of the given project
* @throws CmsException if something goes wrong
*/
public List readProjectResources(CmsProject project) throws CmsException {
return m_projectDriver.readProjectResources(project);
}
/**
* Reads all either new, changed, deleted or locked resources that are changed
* and inside a specified project.<p>
*
* @param context the current request context
* @param projectId the project ID
* @param filter specifies which resources inside the project should be read, {all|new|changed|deleted|locked}
* @return a Vector with the selected resources
* @throws CmsException if something goes wrong
*/
public Vector readProjectView(CmsRequestContext context, int projectId, String filter) throws CmsException {
Vector retValue = new Vector();
List resources = null;
CmsResource currentResource = null;
CmsLock currentLock = null;
// first get the correct status mode
int state=-1;
if (filter.equals("new")) {
state=I_CmsConstants.C_STATE_NEW;
} else if (filter.equals("changed")) {
state=I_CmsConstants.C_STATE_CHANGED;
} else if (filter.equals("deleted")) {
state=I_CmsConstants.C_STATE_DELETED;
} else if (filter.equals("all")) {
state=I_CmsConstants.C_STATE_UNCHANGED;
} else {
// this method was called with an unknown filter key
// filter all changed/new/deleted resources
state=I_CmsConstants.C_STATE_UNCHANGED;
}
// depending on the selected filter, we must use different methods to get the required
// resources
// if the "lock" filter was selected, we must handle the DB access different since
// lock information aren ot sotred in the DB anymore
if (filter.equals("locked")) {
resources=m_vfsDriver.readResources(projectId, state, I_CmsConstants.C_READMODE_IGNORESTATE);
} else {
if ((state == I_CmsConstants.C_STATE_NEW) || (state == I_CmsConstants.C_STATE_CHANGED)
|| (state == I_CmsConstants.C_STATE_DELETED)) {
resources=m_vfsDriver.readResources(projectId, state, I_CmsConstants.C_READMODE_MATCHSTATE);
// get all resources form the database which match to the selected state
} else if (state == I_CmsConstants.C_STATE_UNCHANGED) {
// get all resources form the database which are not unchanged
resources=m_vfsDriver.readResources(projectId, state, I_CmsConstants.C_READMODE_UNMATCHSTATE);
}
}
Iterator i = resources.iterator();
while (i.hasNext()) {
currentResource = (CmsResource)i.next();
if (hasPermissions(context, currentResource, I_CmsConstants.C_READ_ACCESS, false)) {
if (filter.equals("locked")) {
currentLock = getLock(context, currentResource);
if (!currentLock.isNullLock()) {
retValue.addElement(currentResource);
}
} else {
retValue.addElement(currentResource);
}
}
}
resources.clear();
resources = null;
return retValue;
}
/**
* Reads a definition for the given resource type.<p>
*
* All users are granted.
*
* @param context the current request context
* @param name the name of the propertydefinition to read
* @param resourcetype the name of the resource type for which the propertydefinition is valid.
* @return the propertydefinition that corresponds to the overgiven arguments - or null if there is no valid propertydefinition.
* @throws CmsException if something goes wrong
*/
public CmsPropertydefinition readPropertydefinition(CmsRequestContext context, String name, int resourcetype) throws CmsException {
return m_vfsDriver.readPropertyDefinition(name, context.currentProject().getId(), resourcetype);
}
/**
* Reads all project resources that belong to a given view. <p>
*
* A view can be "new", "changed" and "deleted" and contains those resources in the project whose
* state is equal to the selevted view.
*
* @param context the current request context
* @param projectId the preoject to read from
* @param filter the view filter, can be "new", "changed" or "deleted"
* @return vector of CmsResources
* @throws CmsException if something goes wrong
*/
public Vector readPublishProjectView(CmsRequestContext context, int projectId, String filter) throws CmsException {
Vector retValue = new Vector();
List resources = m_projectDriver.readProjectView(projectId, filter);
boolean onlyLocked = false;
// check if only locked resources should be displayed
if ("locked".equalsIgnoreCase(filter)) {
onlyLocked = true;
}
// check the security
Iterator i = resources.iterator();
while (i.hasNext()) {
CmsResource currentResource = (CmsResource)i.next();
if (hasPermissions(context, currentResource, I_CmsConstants.C_READ_ACCESS, false)) {
if (onlyLocked) {
// check if resource is locked
CmsLock lock = getLock(context, currentResource);
if (!lock.isNullLock()) {
retValue.addElement(currentResource);
}
} else {
// add all resources with correct permissions
retValue.addElement(currentResource);
}
}
}
return retValue;
}
/**
* Reads all siblings that point to the resource record of a specified resource name.<p>
*
* @param context the request context
* @param resourcename the name of the specified resource
* @param readAllSiblings true if the specified resource should be included in the result; false, if the specified resource should be excluded from the result
* @param includeDeleted true if deleted siblings should be included in the result List
* @return a List of CmsResources
* @throws CmsException if something goes wrong
*/
public List readSiblings(CmsRequestContext context, String resourcename, boolean readAllSiblings, boolean includeDeleted) throws CmsException {
if (resourcename == null || "".equals(resourcename)) {
return Collections.EMPTY_LIST;
}
CmsResource resource = readFileHeader(context, resourcename, includeDeleted);
List siblings = m_vfsDriver.readSiblings(context.currentProject(), resource, includeDeleted);
int n = siblings.size();
for (int i = 0; i < n; i++) {
CmsResource currentResource = (CmsResource)siblings.get(i);
if (!readAllSiblings && currentResource.getStructureId().equals(resource.getStructureId())) {
siblings.remove(i);
n--;
}
}
setFullResourceNames(context, siblings);
return siblings;
}
/**
* Returns a list of all template resources which must be processed during a static export.<p>
*
* @param context the current request context
* @param parameterResources flag for reading resources with parameters (1) or without (0)
* @param timestamp for reading the data from the db
* @return List of template resources
* @throws CmsException if something goes wrong
*/
public List readStaticExportResources(CmsRequestContext context, int parameterResources, long timestamp) throws CmsException {
return m_projectDriver.readStaticExportResources(context.currentProject(), parameterResources, timestamp);
}
/**
* Returns the parameters of a resource in the table of all published template resources.<p>
*
* @param context the current request context
* @param rfsName the rfs name of the resource
* @return the paramter string of the requested resource
* @throws CmsException if something goes wrong
*/
public String readStaticExportPublishedResourceParamters(CmsRequestContext context, String rfsName) throws CmsException {
return m_projectDriver.readStaticExportPublishedResourceParamters(context.currentProject(), rfsName);
}
/**
* Read a task by id.<p>
*
* @param id the id for the task to read
* @return a task
* @throws CmsException if something goes wrong
*/
public CmsTask readTask(int id) throws CmsException {
return m_workflowDriver.readTask(id);
}
/**
* Reads log entries for a task.<p>
*
* @param taskid the task for the tasklog to read
* @return a Vector of new TaskLog objects
* @throws CmsException if something goes wrong
*/
public Vector readTaskLogs(int taskid) throws CmsException {
return m_workflowDriver.readTaskLogs(taskid);
}
/**
* Reads all tasks for a project.<p>
*
* All users are granted.
*
* @param projectId the id of the Project in which the tasks are defined. Can be null for all tasks
* @param tasktype task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW
* @param orderBy chooses, how to order the tasks
* @param sort sort order C_SORT_ASC, C_SORT_DESC, or null
* @return a vector of tasks
* @throws CmsException if something goes wrong
*/
public Vector readTasksForProject(int projectId, int tasktype, String orderBy, String sort) throws CmsException {
CmsProject project = null;
if (projectId != I_CmsConstants.C_UNKNOWN_ID) {
project = readProject(projectId);
}
return m_workflowDriver.readTasks(project, null, null, null, tasktype, orderBy, sort);
}
/**
* Reads all tasks for a role in a project.<p>
*
* @param projectId the id of the Project in which the tasks are defined
* @param roleName the user who has to process the task
* @param tasktype task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW
* @param orderBy chooses, how to order the tasks
* @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null
* @return a vector of tasks
* @throws CmsException if something goes wrong
*/
public Vector readTasksForRole(int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException {
CmsProject project = null;
CmsGroup role = null;
if (roleName != null) {
role = readGroup(roleName);
}
if (projectId != I_CmsConstants.C_UNKNOWN_ID) {
project = readProject(projectId);
}
return m_workflowDriver.readTasks(project, null, null, role, tasktype, orderBy, sort);
}
/**
* Reads all tasks for a user in a project.<p>
*
* @param projectId the id of the Project in which the tasks are defined
* @param userName the user who has to process the task
* @param taskType task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW
* @param orderBy chooses, how to order the tasks
* @param sort sort order C_SORT_ASC, C_SORT_DESC, or null
* @return a vector of tasks
* @throws CmsException if something goes wrong
*/
public Vector readTasksForUser(int projectId, String userName, int taskType, String orderBy, String sort) throws CmsException {
CmsUser user = readUser(userName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
CmsProject project = null;
// try to read the project, if projectId == -1 we must return the tasks of all projects
if (projectId != I_CmsConstants.C_UNKNOWN_ID) {
project = m_projectDriver.readProject(projectId);
}
return m_workflowDriver.readTasks(project, user, null, null, taskType, orderBy, sort);
}
/**
* Returns a user object based on the id of a user.<p>
*
* All users are granted.
*
* @param id the id of the user to read
* @return the user read
* @throws CmsException if something goes wrong
*/
public CmsUser readUser(CmsUUID id) throws CmsException {
CmsUser user = null;
user = getUserFromCache(id);
if (user == null) {
user = m_userDriver.readUser(id);
putUserInCache(user);
}
return user;
// old implementation:
// try {
// user = getUserFromCache(id);
// if (user == null) {
// user = m_userDriver.readUser(id);
// putUserInCache(user);
// }
// } catch (CmsException ex) {
// return new CmsUser(CmsUUID.getNullUUID(), id + "", "deleted user");
// }
// return user;
}
/**
* Returns a user object.<p>
*
* All users are granted.
*
* @param username the name of the user that is to be read
* @return user read form the cms
* @throws CmsException if operation was not succesful
*/
public CmsUser readUser(String username) throws CmsException {
return readUser(username, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
}
/**
* Returns a user object.<p>
*
* All users are granted.
*
* @param username the name of the user that is to be read
* @param type the type of the user
* @return user read form the cms
* @throws CmsException if operation was not succesful
*/
public CmsUser readUser(String username, int type) throws CmsException {
CmsUser user = getUserFromCache(username, type);
if (user == null) {
user = m_userDriver.readUser(username, type);
putUserInCache(user);
}
return user;
}
/**
* Returns a user object if the password for the user is correct.<p>
*
* All users are granted.
*
* @param username the username of the user that is to be read
* @param password the password of the user that is to be read
* @return user read form the cms
* @throws CmsException if operation was not succesful
*/
public CmsUser readUser(String username, String password) throws CmsException {
// don't read user from cache here because password may have changed
CmsUser user = m_userDriver.readUser(username, password, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
putUserInCache(user);
return user;
}
/**
* Read a web user from the database.<p>
*
* @param username the web user to read
* @return the read web user
* @throws CmsException if the user could not be read
*/
public CmsUser readWebUser(String username) throws CmsException {
return readUser(username, I_CmsConstants.C_USER_TYPE_WEBUSER);
}
/**
* Returns a user object if the password for the user is correct.<p>
*
* All users are granted.
*
* @param username the username of the user that is to be read
* @param password the password of the user that is to be read
* @return user read form the cms
* @throws CmsException if operation was not succesful
*/
public CmsUser readWebUser(String username, String password) throws CmsException {
// don't read user from cache here because password may have changed
CmsUser user = m_userDriver.readUser(username, password, I_CmsConstants.C_USER_TYPE_WEBUSER);
putUserInCache(user);
return user;
}
/**
* Reaktivates a task from the Cms.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task to accept
* @throws CmsException if something goes wrong
*/
public void reaktivateTask(CmsRequestContext context, int taskId) throws CmsException {
CmsTask task = m_workflowDriver.readTask(taskId);
task.setState(I_CmsConstants.C_TASK_STATE_STARTED);
task.setPercentage(0);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Task was reactivated from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Sets a new password if the given recovery password is correct.<p>
*
* @param username the name of the user
* @param recoveryPassword the recovery password
* @param newPassword the new password
* @throws CmsException if operation was not succesfull.
*/
public void recoverPassword(String username, String recoveryPassword, String newPassword) throws CmsException {
// check the new password
validatePassword(newPassword);
// recover the password
m_userDriver.writePassword(username, recoveryPassword, newPassword);
}
/**
* Recovers a resource from the online project back to the offline project as an unchanged resource.<p>
*
* @param context the current request context
* @param resourcename the name of the resource which is recovered
* @return the recovered resource in the offline project
* @throws CmsException if somethong goes wrong
*/
public CmsResource recoverResource(CmsRequestContext context, String resourcename) throws CmsException {
CmsFile onlineFile = null;
byte[] contents = null;
List properties = null;
CmsFile newFile = null;
CmsFolder newFolder = null;
CmsResource newResource = null;
CmsFolder parentFolder = null;
CmsFolder onlineFolder = null;
CmsProject oldProject = null;
try {
parentFolder = readFolder(context, CmsResource.getFolderPath(resourcename));
// switch to the online project
oldProject = context.currentProject();
context.setCurrentProject(readProject(I_CmsConstants.C_PROJECT_ONLINE_ID));
if (!resourcename.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
// read the file content plus properties in the online project
onlineFile = readFile(context, resourcename);
contents = onlineFile.getContents();
properties = readPropertyObjects(context, resourcename, context.getAdjustedSiteRoot(resourcename), false);
} else {
// contents and properties for a folder
onlineFolder = readFolder(context, resourcename);
contents = new byte[0];
properties = readPropertyObjects(context, resourcename, context.getAdjustedSiteRoot(resourcename), false);
}
// switch back to the previous project
context.setCurrentProject(oldProject);
if (!resourcename.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
// create the file in the offline project
newFile = new CmsFile(onlineFile.getStructureId(), onlineFile.getResourceId(), parentFolder.getStructureId(), onlineFile.getFileId(), CmsResource.getName(resourcename), onlineFile.getType(), onlineFile.getFlags(), 0, org.opencms.main.I_CmsConstants.C_STATE_UNCHANGED, getResourceType(onlineFile.getType()).getLoaderId(), 0, context.currentUser().getId(), 0, context.currentUser().getId(), contents.length, 1, contents);
newResource = m_vfsDriver.createFile(context.currentProject(), newFile, context.currentUser().getId(), parentFolder.getStructureId(), CmsResource.getName(resourcename));
} else {
// create the folder in the offline project
newFolder = new CmsFolder(onlineFolder.getStructureId(), onlineFolder.getResourceId(), parentFolder.getStructureId(), CmsUUID.getNullUUID(), CmsResource.getName(resourcename), CmsResourceTypeFolder.C_RESOURCE_TYPE_ID, onlineFolder.getFlags(), 0, org.opencms.main.I_CmsConstants.C_STATE_UNCHANGED, 0, context.currentUser().getId(), 0, context.currentUser().getId(), 1);
newResource = m_vfsDriver.createFolder(context.currentProject(), newFolder, parentFolder.getStructureId());
}
// write the properties of the recovered resource
writePropertyObjects(context, resourcename, properties);
// set the resource state to unchanged coz the resource exists online
newResource.setState(I_CmsConstants.C_STATE_UNCHANGED);
m_vfsDriver.writeResourceState(context.currentProject(), newResource, C_UPDATE_ALL);
} catch (CmsException e) {
// the exception is caught just to have a finally clause to switch back to the
// previous project. the exception should be handled in the upper app. layer.
throw e;
} finally {
// switch back to the previous project
context.setCurrentProject(oldProject);
clearResourceCache();
}
newResource.setFullResourceName(resourcename);
contents = null;
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", newResource)));
return newResource;
}
/**
* Removes an access control entry for a given resource and principal.<p>
*
* Access is granted, if:
* <ul>
* <li>the current user has control permission on the resource
* </ul>
*
* @param context the current request context
* @param resource the resource
* @param principal the id of a group or user to identify the access control entry
* @throws CmsException if something goes wrong
*/
public void removeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsUUID principal) throws CmsException {
// get the old values
long dateLastModified = resource.getDateLastModified();
CmsUUID userLastModified = resource.getUserLastModified();
checkPermissions(context, resource, I_CmsConstants.C_CONTROL_ACCESS);
m_userDriver.removeAccessControlEntry(context.currentProject(), resource.getResourceId(), principal);
clearAccessControlListCache();
touchResource(context, resource, dateLastModified, userLastModified);
}
/**
* Removes user from Cache.<p>
*
* @param user the user to remove
*/
private void removeUserFromCache(CmsUser user) {
m_userCache.remove(getUserCacheKey(user.getName(), user.getType()));
m_userCache.remove(getUserCacheKey(user.getId()));
}
/**
* Removes a user from a group.<p>
*
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param username the name of the user that is to be removed from the group
* @param groupname the name of the group
* @throws CmsException if operation was not succesful
*/
public void removeUserFromGroup(CmsRequestContext context, String username, String groupname) throws CmsException {
// test if this user is existing in the group
if (!userInGroup(context, username, groupname)) {
// user already there, throw exception
throw new CmsException("[" + getClass().getName() + "] remove " + username + " from " + groupname, CmsException.C_NO_USER);
}
if (isAdmin(context)) {
CmsUser user;
CmsGroup group;
user = readUser(username);
//check if the user exists
if (user != null) {
group = readGroup(groupname);
//check if group exists
if (group != null) {
// do not remmove the user from its default group
if (user.getDefaultGroupId() != group.getId()) {
//remove this user from the group
m_userDriver.deleteUserInGroup(user.getId(), group.getId());
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]", CmsException.C_NO_DEFAULT_GROUP);
}
} else {
throw new CmsException("[" + getClass().getName() + "]" + groupname, CmsException.C_NO_GROUP);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] removeUserFromGroup()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] removeUserFromGroup()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Renames the file to a new name.<p>
*
* Rename can only be done in an offline project. To rename a file, the following
* steps have to be done:
* <ul>
* <li> Copy the file with the oldname to a file with the new name, the state
* of the new file is set to NEW (2).
* <ul>
* <li> If the state of the original file is UNCHANGED (0), the file content of the
* file is read from the online project. </li>
* <li> If the state of the original file is CHANGED (1) or NEW (2) the file content
* of the file is read from the offline project. </li>
* </ul>
* </li>
* <li> Set the state of the old file to DELETED (3). </li>
* </ul>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param oldname the complete path to the resource which will be renamed
* @param newname the new name of the resource
* @throws CmsException if operation was not succesful
*/
public void renameResource(CmsRequestContext context, String oldname, String newname) throws CmsException {
String destination = oldname.substring(0, oldname.lastIndexOf("/") + 1);
this.moveResource(context, oldname, destination + newname);
}
/**
* Replaces the content and properties of an existing resource.<p>
*
* @param context the current request context
* @param resourceName the resource name
* @param newResourceType the new resource type
* @param newResourceProperties the new resource properties
* @param newResourceContent the new resource content
* @return CmsResource the resource with replaced content and properties
* @throws CmsException if something goes wrong
*/
public CmsResource replaceResource(CmsRequestContext context, String resourceName, int newResourceType, List newResourceProperties, byte[] newResourceContent) throws CmsException {
CmsResource resource = null;
// clear the cache
clearResourceCache();
// read the existing resource
resource = readFileHeader(context, resourceName, false);
// check if the user has write access
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
// replace the existing with the new file content
m_vfsDriver.replaceResource(context.currentUser(), context.currentProject(), resource, newResourceContent, newResourceType, getResourceType(newResourceType).getLoaderId());
// write the properties
m_vfsDriver.writePropertyObjects(context.currentProject(), resource, newResourceProperties);
m_propertyCache.clear();
// update the resource state
if (resource.getState() == I_CmsConstants.C_STATE_UNCHANGED) {
resource.setState(I_CmsConstants.C_STATE_CHANGED);
}
resource.setUserLastModified(context.currentUser().getId());
touch(context, resourceName, System.currentTimeMillis(), context.currentUser().getId());
m_vfsDriver.writeResourceState(context.currentProject(), resource, C_UPDATE_RESOURCE);
// clear the cache
clearResourceCache();
newResourceContent = null;
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
return resource;
}
/**
* Restores a file in the current project with a version in the backup.<p>
*
* @param context the current request context
* @param tagId the tag id of the resource
* @param filename the name of the file to restore
* @throws CmsException if operation was not succesful
*/
public void restoreResource(CmsRequestContext context, int tagId, String filename) throws CmsException {
if (context.currentProject().isOnlineProject()) {
// this is the onlineproject
throw new CmsSecurityException("Can't write to the online project", CmsSecurityException.C_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT);
}
CmsFile offlineFile = readFile(context, filename);
// check if the user has write access
checkPermissions(context, offlineFile, I_CmsConstants.C_WRITE_ACCESS);
int state = I_CmsConstants.C_STATE_CHANGED;
CmsBackupResource backupFile = readBackupFile(context, tagId, filename);
if (offlineFile.getState() == I_CmsConstants.C_STATE_NEW) {
state = I_CmsConstants.C_STATE_NEW;
}
if (backupFile != null && offlineFile != null) {
// get the backed up flags
int flags = backupFile.getFlags();
if (offlineFile.isLabeled()) {
// set the flag for labeled links on the restored file
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
}
CmsFile newFile = new CmsFile(offlineFile.getStructureId(), offlineFile.getResourceId(), offlineFile.getParentStructureId(), offlineFile.getFileId(), offlineFile.getName(), backupFile.getType(), flags, context.currentProject().getId(), state, backupFile.getLoaderId(), offlineFile.getDateCreated(), backupFile.getUserCreated(), offlineFile.getDateLastModified(), context.currentUser().getId(), backupFile.getLength(), backupFile.getLinkCount(), backupFile.getContents());
writeFile(context, newFile);
// now read the backup properties
List backupProperties = m_backupDriver.readBackupProperties(backupFile);
//and write them to the curent resource
writePropertyObjects(context, filename, backupProperties);
clearResourceCache();
}
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", offlineFile)));
}
/**
* Adds the full resourcename to each resource in a list of CmsResources.<p>
*
* @param context the current request context
* @param resourceList a list of CmsResources
* @return list of CmsResources added with full resource name
* @throws CmsException if something goes wrong
*/
public List setFullResourceNames(CmsRequestContext context, List resourceList) throws CmsException {
Iterator i = resourceList.iterator();
while (i.hasNext()) {
CmsResource res = (CmsResource)i.next();
if (!res.hasFullResourceName()) {
res.setFullResourceName(readPath(context, res, true));
}
updateContextDates(context, res);
}
return resourceList;
}
/**
* Set a new name for a task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task to set the percentage
* @param name the new name value
* @throws CmsException if something goes wrong
*/
public void setName(CmsRequestContext context, int taskId, String name) throws CmsException {
if ((name == null) || name.length() == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
CmsTask task = m_workflowDriver.readTask(taskId);
task.setName(name);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Name was set to " + name + "% from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Sets a new parent-group for an already existing group in the Cms.<p>
*
* Only the admin can do this.
*
* @param context the current request context
* @param groupName the name of the group that should be written to the Cms
* @param parentGroupName the name of the parentGroup to set, or null if the parent group should be deleted
* @throws CmsException if operation was not succesfull
*/
public void setParentGroup(CmsRequestContext context, String groupName, String parentGroupName) throws CmsException {
// Check the security
if (isAdmin(context)) {
CmsGroup group = readGroup(groupName);
CmsUUID parentGroupId = CmsUUID.getNullUUID();
// if the group exists, use its id, else set to unknown.
if (parentGroupName != null) {
parentGroupId = readGroup(parentGroupName).getId();
}
group.setParentId(parentGroupId);
// write the changes to the cms
writeGroup(context, group);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] setParentGroup() " + groupName, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Sets the password for a user.<p>
*
* Only users in the group "Administrators" are granted.<p>
*
* @param context the current request context
* @param username the name of the user
* @param newPassword the new password
* @throws CmsException if operation was not succesfull.
*/
public void setPassword(CmsRequestContext context, String username, String newPassword) throws CmsException {
// check the password
validatePassword(newPassword);
if (isAdmin(context)) {
m_userDriver.writePassword(username, newPassword);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] setPassword() " + username, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Resets the password for a specified user.<p>
*
* @param username the name of the user
* @param oldPassword the old password
* @param newPassword the new password
* @throws CmsException if the user data could not be read from the database
* @throws CmsSecurityException if the specified username and old password could not be verified
*/
public void resetPassword(String username, String oldPassword, String newPassword) throws CmsException, CmsSecurityException {
boolean noSystemUser = false;
boolean noWebUser = false;
boolean unknownException = false;
CmsUser user = null;
// read the user as a system to verify that the specified old password is correct
try {
user = m_userDriver.readUser(username, oldPassword, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
} catch (CmsException e) {
if (e.getType() == CmsException.C_NO_USER) {
noSystemUser = true;
} else {
unknownException = true;
}
}
// dito as a web user
if (user == null) {
try {
user = m_userDriver.readUser(username, oldPassword, I_CmsConstants.C_USER_TYPE_WEBUSER);
} catch (CmsException e) {
if (e.getType() == CmsException.C_NO_USER) {
noWebUser = true;
} else {
unknownException = true;
}
}
}
if (noSystemUser && noWebUser) {
// the specified username + old password don't match
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED);
} else if (unknownException) {
// we caught exceptions different from CmsException.C_NO_USER -> a general error?!
throw new CmsException("[" + getClass().getName() + "] Error resetting password for user '" + username + "'", CmsException.C_UNKNOWN_EXCEPTION);
} else if (user != null) {
// the specified old password was successful verified
validatePassword(newPassword);
m_userDriver.writePassword(username, newPassword);
}
}
/**
* Set priority of a task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task to set the percentage
* @param priority the priority value
* @throws CmsException if something goes wrong
*/
public void setPriority(CmsRequestContext context, int taskId, int priority) throws CmsException {
CmsTask task = m_workflowDriver.readTask(taskId);
task.setPriority(priority);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Priority was set to " + priority + " from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Sets the recovery password for a user.<p>
*
* Users, which are in the group "Administrators" are granted.
* A user can change his own password.<p>
*
* @param username the name of the user
* @param password the password of the user
* @param newPassword the new recoveryPassword to be set
* @throws CmsException if operation was not succesfull
*/
public void setRecoveryPassword(String username, String password, String newPassword) throws CmsException {
// check the password
validatePassword(newPassword);
// read the user in order to ensure that the password is correct
CmsUser user = null;
try {
user = m_userDriver.readUser(username, password, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
} catch (CmsException exc) {
// user will be null
}
if (user == null) {
try {
user = m_userDriver.readUser(username, password, I_CmsConstants.C_USER_TYPE_WEBUSER);
} catch (CmsException e) {
// TODO: Check what happens if this is caught
}
}
m_userDriver.writeRecoveryPassword(username, newPassword);
}
/**
* Set a Parameter for a task.<p>
*
* @param taskId the Id of the task
* @param parName name of the parameter
* @param parValue value if the parameter
* @throws CmsException if something goes wrong.
*/
public void setTaskPar(int taskId, String parName, String parValue) throws CmsException {
m_workflowDriver.writeTaskParameter(taskId, parName, parValue);
}
/**
* Set timeout of a task.<p>
*
* @param context the current request context
* @param taskId the Id of the task to set the percentage
* @param timeout new timeout value
* @throws CmsException if something goes wrong
*/
public void setTimeout(CmsRequestContext context, int taskId, long timeout) throws CmsException {
CmsTask task = m_workflowDriver.readTask(taskId);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
task.setTimeOut(timestamp);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Timeout was set to " + timeout + " from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Access the driver underneath to change the timestamp of a resource.<p>
*
* @param context the current request context
* @param resourceName the name of the resource to change
* @param timestamp timestamp the new timestamp of the changed resource
* @param user the user who is inserted as userladtmodified
* @throws CmsException if something goes wrong
*/
public void touch(CmsRequestContext context, String resourceName, long timestamp, CmsUUID user) throws CmsException {
CmsResource resource = readFileHeader(context, resourceName);
touchResource(context, resource, timestamp, user);
}
/**
* Access the driver underneath to change the timestamp of a resource.<p>
*
* @param context the current request context
* @param res the resource to change
* @param timestamp timestamp the new timestamp of the changed resource
* @param user the user who is inserted as userladtmodified
* @throws CmsException if something goes wrong
*/
private void touchResource(CmsRequestContext context, CmsResource res, long timestamp, CmsUUID user) throws CmsException {
// NOTE: this is the new way to update the state !
// if (res.getState() < I_CmsConstants.C_STATE_CHANGED)
res.setState(I_CmsConstants.C_STATE_CHANGED);
res.setDateLastModified(timestamp);
res.setUserLastModified(user);
m_vfsDriver.writeResourceState(context.currentProject(), res, C_UPDATE_RESOURCE);
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", res)));
}
/**
* Undeletes a file in the Cms.<p>
*
* A file can only be undeleted in an offline project.
* A file is undeleted by setting its state to CHANGED (1).
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callinUser</li>
* </ul>
*
* @param context the current request context
* @param filename the complete m_path of the file
* @throws CmsException if operation was not succesful
*/
public void undeleteResource(CmsRequestContext context, String filename) throws CmsException {
// try to trad the resource
CmsResource resource = readFileHeader(context, filename, true);
// this resource must be marked as deleted
if (resource.getState() == I_CmsConstants.C_STATE_DELETED) {
undoChanges(context, filename);
} else {
throw new CmsException("Resource already exists. Remove the existing blue resource before undeleting.", CmsException.C_FILE_EXISTS);
}
}
/**
* Undo all changes in the resource, restore the online file.<p>
*
* @param context the current request context
* @param resourceName the name of the resource to be restored
* @throws CmsException if something goes wrong
*/
public void undoChanges(CmsRequestContext context, String resourceName) throws CmsException {
if (context.currentProject().isOnlineProject()) {
// this is the onlineproject
throw new CmsSecurityException("Can't undo changes to the online project", CmsSecurityException.C_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT);
}
CmsProject onlineProject = readProject(I_CmsConstants.C_PROJECT_ONLINE_ID);
CmsResource resource = readFileHeader(context, resourceName, true);
// check if the user has write access
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
// change folder or file?
if (resource.isFolder()) {
// read the resource from the online project
CmsFolder onlineFolder = readFolderInProject(I_CmsConstants.C_PROJECT_ONLINE_ID, resourceName);
//we must ensure that the resource contains it full resource name as this is required for the
// property operations
readPath(context, onlineFolder, true);
CmsFolder restoredFolder = new CmsFolder(resource.getStructureId(), resource.getResourceId(), resource.getParentStructureId(), resource.getFileId(), resource.getName(), onlineFolder.getType(), onlineFolder.getFlags(), context.currentProject().getId(), I_CmsConstants.C_STATE_UNCHANGED, onlineFolder.getDateCreated(), onlineFolder.getUserCreated(), onlineFolder.getDateLastModified(), onlineFolder.getUserLastModified(), resource.getLinkCount());
// write the file in the offline project
// this sets a flag so that the file date is not set to the current time
restoredFolder.setDateLastModified(onlineFolder.getDateLastModified());
// write the folder without setting state = changed
m_vfsDriver.writeFolder(context.currentProject(), restoredFolder, C_NOTHING_CHANGED, restoredFolder.getUserLastModified());
// restore the properties in the offline project
readPath(context, restoredFolder, true);
m_vfsDriver.deleteProperties(context.currentProject().getId(), restoredFolder);
List propertyInfos = m_vfsDriver.readPropertyObjects(onlineProject, onlineFolder);
m_vfsDriver.writePropertyObjects(context.currentProject(), restoredFolder, propertyInfos);
} else {
// read the file from the online project
CmsFile onlineFile = readFileInProject(context, I_CmsConstants.C_PROJECT_ONLINE_ID, resource.getStructureId(), false);
//(context, resourceName);
readPath(context, onlineFile, true);
// get flags of the deleted file
int flags = onlineFile.getFlags();
if (resource.isLabeled()) {
// set the flag for labeled links on the restored file
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
}
CmsFile restoredFile = new CmsFile(resource.getStructureId(), resource.getResourceId(), resource.getParentStructureId(), resource.getFileId(), resource.getName(), onlineFile.getType(), flags, context.currentProject().getId(), I_CmsConstants.C_STATE_UNCHANGED, onlineFile.getLoaderId(), onlineFile.getDateCreated(), onlineFile.getUserCreated(), onlineFile.getDateLastModified(), onlineFile.getUserLastModified(), onlineFile.getLength(), resource.getLinkCount(), onlineFile.getContents());
// write the file in the offline project
// this sets a flag so that the file date is not set to the current time
restoredFile.setDateLastModified(onlineFile.getDateLastModified());
// write-acces was granted - write the file without setting state = changed
//m_vfsDriver.writeFile(context.currentProject(), restoredFile, C_NOTHING_CHANGED, restoredFile.getUserLastModified());
m_vfsDriver.writeFileHeader(context.currentProject(), restoredFile, C_NOTHING_CHANGED, restoredFile.getUserLastModified());
m_vfsDriver.writeFileContent(restoredFile.getFileId(), restoredFile.getContents(), context.currentProject().getId(), false);
// restore the properties in the offline project
readPath(context, restoredFile, true);
m_vfsDriver.deleteProperties(context.currentProject().getId(), restoredFile);
List propertyInfos = m_vfsDriver.readPropertyObjects(onlineProject, onlineFile);
m_vfsDriver.writePropertyObjects(context.currentProject(), restoredFile, propertyInfos);
}
m_userDriver.removeAccessControlEntries(context.currentProject(), resource.getResourceId());
// copy the access control entries
ListIterator aceList = m_userDriver.readAccessControlEntries(onlineProject, resource.getResourceId(), false).listIterator();
while (aceList.hasNext()) {
CmsAccessControlEntry ace = (CmsAccessControlEntry)aceList.next();
m_userDriver.createAccessControlEntry(context.currentProject(), resource.getResourceId(), ace.getPrincipal(), ace.getPermissions().getAllowedPermissions(), ace.getPermissions().getDeniedPermissions(), ace.getFlags());
}
// update the cache
clearResourceCache();
m_propertyCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Unlocks all resources in this project.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param context the current request context
* @param projectId the id of the project to be published
* @throws CmsException if something goes wrong
*/
public void unlockProject(CmsRequestContext context, int projectId) throws CmsException {
// read the project
CmsProject project = readProject(projectId);
// check the security
if ((isAdmin(context) || isManagerOfProject(context)) && (project.getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED)) {
// unlock all resources in the project
m_lockManager.removeResourcesInProject(projectId);
clearResourceCache();
m_projectCache.clear();
// we must also clear the permission cache
m_permissionCache.clear();
} else if (!isAdmin(context) && !isManagerOfProject(context)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] unlockProject() " + projectId, CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] unlockProject() " + projectId, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Unlocks a resource by removing the exclusive lock on the exclusive locked sibling.<p>
*
* @param context the current request context
* @param resourcename the resource name that gets locked
* @return the removed lock
* @throws CmsException if something goes wrong
*/
public CmsLock unlockResource(CmsRequestContext context, String resourcename) throws CmsException {
CmsLock oldLock = m_lockManager.removeResource(this, context, resourcename, false);
clearResourceCache();
// cw/060104 we must also clear the permission cache
m_permissionCache.clear();
CmsResource resource = readFileHeader(context, resourcename);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
return oldLock;
}
/**
* Checks if a user is member of a group.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param username the name of the user to check
* @param groupname the name of the group to check
* @return true or false
* @throws CmsException if operation was not succesful
*/
public boolean userInGroup(CmsRequestContext context, String username, String groupname) throws CmsException {
Vector groups = getGroupsOfUser(context, username);
CmsGroup group;
for (int z = 0; z < groups.size(); z++) {
group = (CmsGroup)groups.elementAt(z);
if (groupname.equals(group.getName())) {
return true;
}
}
return false;
}
/**
* This method checks if a new password follows the rules for
* new passwords, which are defined by a Class configured in opencms.properties.<p>
*
* If this method throws no exception the password is valid.
*
* @param password the new password that has to be checked
* @throws CmsSecurityException if the password is not valid
*/
public void validatePassword(String password) throws CmsSecurityException {
if (m_passwordValidationClass == null) {
synchronized (this) {
String className = OpenCms.getPasswordValidatingClass();
try {
m_passwordValidationClass = (I_CmsPasswordValidation)Class.forName(className).getConstructor(new Class[] {}).newInstance(new Class[] {});
} catch (Exception e) {
throw new RuntimeException("Error generating password validation class instance");
}
}
}
m_passwordValidationClass.validatePassword(password);
}
/**
* Checks if characters in a String are allowed for filenames.<p>
*
* @param filename String to check
* @throws CmsException C_BAD_NAME if the check fails
*/
public void validFilename(String filename) throws CmsException {
if (filename == null) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME);
}
int l = filename.length();
// if (l == 0 || filename.startsWith(".")) {
if (l == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME);
}
for (int i = 0; i < l; i++) {
char c = filename.charAt(i);
if (((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') && (c != '$')) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME);
}
}
}
/**
* Checks if characters in a String are allowed for names.<p>
*
* @param name String to check
* @param blank flag to allow blanks
* @throws CmsException C_BAD_NAME if the check fails
*/
protected void validName(String name, boolean blank) throws CmsException {
if (name == null || name.length() == 0 || name.trim().length() == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// throw exception if no blanks are allowed
if (!blank) {
int l = name.length();
for (int i = 0; i < l; i++) {
char c = name.charAt(i);
if (c == ' ') {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
}
}
/*
for (int i=0; i<l; i++) {
char c = name.charAt(i);
if (
((c < 'a') || (c > 'z')) &&
((c < '0') || (c > '9')) &&
((c < 'A') || (c > 'Z')) &&
(c != '-') && (c != '.') &&
(c != '_') && (c != '~')
) {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_BAD_NAME);
}
}
*/
}
/**
* Checks if characters in a String are allowed for filenames.<p>
*
* @param taskname String to check
* @throws CmsException C_BAD_NAME if the check fails
*/
protected void validTaskname(String taskname) throws CmsException {
if (taskname == null) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME);
}
int l = taskname.length();
if (l == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME);
}
for (int i = 0; i < l; i++) {
char c = taskname.charAt(i);
if (((c < '?') || (c > '?')) && ((c < '?') || (c > '?')) && ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') && (c != ' ') && (c != '?') && (c != '/') && (c != '(') && (c != ')') && (c != '\'') && (c != '#') && (c != '&') && (c != ';')) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME);
}
}
}
/**
* Writes an access control entry to the cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the current user has control permission on the resource
* </ul>
*
* @param context the current request context
* @param resource the resource
* @param acEntry the entry to write
* @throws CmsException if something goes wrong
*/
public void writeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsAccessControlEntry acEntry) throws CmsException {
// get the old values
long dateLastModified = resource.getDateLastModified();
CmsUUID userLastModified = resource.getUserLastModified();
checkPermissions(context, resource, I_CmsConstants.C_CONTROL_ACCESS);
m_userDriver.writeAccessControlEntry(context.currentProject(), acEntry);
clearAccessControlListCache();
touchResource(context, resource, dateLastModified, userLastModified);
}
/**
* Writes the Crontable.<p>
*
* Only a administrator can do this.
*
* @param context the current request context
* @param crontable the creontable
* @throws CmsException if something goes wrong
*/
public void writeCronTable(CmsRequestContext context, String crontable) throws CmsException {
if (isAdmin(context)) {
if (m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_CRONTABLE) == null) {
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_CRONTABLE, crontable);
} else {
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_CRONTABLE, crontable);
}
// TODO enable the cron manager
//OpenCms.getCronManager().writeCronTab(crontable);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeCronTable()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Writes a file to the Cms.<p>
*
* A file can only be written to an offline project.
* The state of the resource is set to CHANGED (1). The file content of the file
* is either updated (if it is already existing in the offline project), or created
* in the offline project (if it is not available there).
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param file the name of the file to write
* @throws CmsException if operation was not succesful
*/
public void writeFile(CmsRequestContext context, CmsFile file) throws CmsException {
// check if the user has write access
checkPermissions(context, file, I_CmsConstants.C_WRITE_ACCESS);
// write-acces was granted - write the file.
//m_vfsDriver.writeFile(context.currentProject(), file, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
m_vfsDriver.writeFileHeader(context.currentProject(), file, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
m_vfsDriver.writeFileContent(file.getFileId(), file.getContents(), context.currentProject().getId(), false);
if (file.getState() == I_CmsConstants.C_STATE_UNCHANGED) {
file.setState(I_CmsConstants.C_STATE_CHANGED);
}
// update the cache
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", file)));
}
/**
* Writes the file extensions.<p>
*
* Users, which are in the group for administrators are authorized.
*
* @param context the current request context
* @param extensions holds extensions as keys and resourcetypes (Stings) as values
* @throws CmsException if operation was not succesful
*/
public void writeFileExtensions(CmsRequestContext context, Hashtable extensions) throws CmsException {
if (extensions != null) {
if (isAdmin(context)) {
Enumeration enu = extensions.keys();
while (enu.hasMoreElements()) {
String key = (String)enu.nextElement();
validFilename(key);
}
if (m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS) == null) {
// the property wasn't set before.
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS, extensions);
} else {
// overwrite the property.
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS, extensions);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeFileExtensions() ", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
}
/**
* Writes a fileheader to the Cms.<p>
*
* A file can only be written to an offline project.
* The state of the resource is set to CHANGED (1). The file content of the file
* is either updated (if it is already existing in the offline project), or created
* in the offline project (if it is not available there).
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param file the file to write
*
* @throws CmsException if operation was not succesful
*/
public void writeFileHeader(CmsRequestContext context, CmsFile file) throws CmsException {
// check if the user has write access
checkPermissions(context, file, I_CmsConstants.C_WRITE_ACCESS);
// write-acces was granted - write the file.
m_vfsDriver.writeFileHeader(context.currentProject(), file, C_UPDATE_STRUCTURE_STATE, context.currentUser().getId());
if (file.getState() == I_CmsConstants.C_STATE_UNCHANGED) {
file.setState(I_CmsConstants.C_STATE_CHANGED);
}
// update the cache
//clearResourceCache(file.getResourceName(), context.currentProject(), context.currentUser());
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", file)));
}
/**
* Writes an already existing group in the Cms.<p>
*
* Only the admin can do this.
*
* @param context the current request context
* @param group the group that should be written to the Cms
* @throws CmsException if operation was not succesfull
*/
public void writeGroup(CmsRequestContext context, CmsGroup group) throws CmsException {
// Check the security
if (isAdmin(context)) {
m_userDriver.writeGroup(group);
m_groupCache.put(new CacheId(group), group);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeGroup() " + group.getName(), CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Writes the Linkchecktable.<p>
*
* Only a administrator can do this.
*
* @param context the current request context
* @param linkchecktable the hashtable that contains the links that were not reachable
* @throws CmsException if operation was not succesfull
*/
public void writeLinkCheckTable(CmsRequestContext context, Hashtable linkchecktable) throws CmsException {
if (isAdmin(context)) {
if (m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_LINKCHECKTABLE) == null) {
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_LINKCHECKTABLE, linkchecktable);
} else {
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_LINKCHECKTABLE, linkchecktable);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeLinkCheckTable()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Writes the package for the system.<p>
*
* This path is used for db-export and db-import as well as module packages.
*
* @param context the current request context
* @param path the package path
* @throws CmsException if operation ws not successful
*/
public void writePackagePath(CmsRequestContext context, String path) throws CmsException {
// check the security
if (isAdmin(context)) {
// security is ok - write the exportpath.
if (m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_PACKAGEPATH) == null) {
// the property wasn't set before.
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_PACKAGEPATH, path);
} else {
// overwrite the property.
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_PACKAGEPATH, path);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writePackagePath()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Writes a resource and its properties to the Cms.<p>
*
* A resource can only be written to an offline project.
* The state of the resource is set to CHANGED (1). The file content of the file
* is either updated (if it is already existing in the offline project), or created
* in the offline project (if it is not available there).
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* <li>the user is the owner of the resource or administrator<li>
* </ul>
*
* @param context the current request context
* @param resourcename the name of the resource to write
* @param properties the properties of the resource
* @param filecontent the new filecontent of the resource
* @throws CmsException if operation was not succesful
*/
public void writeResource(CmsRequestContext context, String resourcename, List properties, byte[] filecontent) throws CmsException {
CmsResource resource = readFileHeader(context, resourcename, true);
// check if the user has write access
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
m_vfsDriver.writeResource(context.currentProject(), resource, filecontent, C_UPDATE_STRUCTURE_STATE, context.currentUser().getId());
// mark the resource as modified in the current project
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), resource);
if (resource.getState() == I_CmsConstants.C_STATE_UNCHANGED) {
resource.setState(I_CmsConstants.C_STATE_CHANGED);
}
// write the properties
m_vfsDriver.writePropertyObjects(context.currentProject(), resource, properties);
// update the cache
//clearResourceCache(resource.getResourceName(), context.currentProject(), context.currentUser());
clearResourceCache();
filecontent = null;
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Inserts an entry in the published resource table.<p>
*
* This is done during static export.
* @param context the current request context
* @param resourceName The name of the resource to be added to the static export
* @param linkType the type of resource exported (0= non-paramter, 1=parameter)
* @param linkParameter the parameters added to the resource
* @param timestamp a timestamp for writing the data into the db
* @throws CmsException if something goes wrong
*/
public void writeStaticExportPublishedResource(CmsRequestContext context, String resourceName, int linkType, String linkParameter, long timestamp) throws CmsException {
m_projectDriver.writeStaticExportPublishedResource(context.currentProject(), resourceName, linkType, linkParameter, timestamp);
}
/**
* Writes a new user tasklog for a task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskid the Id of the task
* @param comment description for the log
* @throws CmsException if something goes wrong
*/
public void writeTaskLog(CmsRequestContext context, int taskid, String comment) throws CmsException {
m_workflowDriver.writeTaskLog(taskid, context.currentUser().getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, I_CmsConstants.C_TASKLOG_USER);
}
/**
* Writes a new user tasklog for a task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task
* @param comment description for the log
* @param type type of the tasklog. User tasktypes must be greater then 100
* @throws CmsException something goes wrong
*/
public void writeTaskLog(CmsRequestContext context, int taskId, String comment, int type) throws CmsException {
m_workflowDriver.writeTaskLog(taskId, context.currentUser().getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, type);
}
/**
* Updates the user information.<p>
*
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param user The user to be updated
*
* @throws CmsException if operation was not succesful
*/
public void writeUser(CmsRequestContext context, CmsUser user) throws CmsException {
// Check the security
if (isAdmin(context) || (context.currentUser().equals(user))) {
// prevent the admin to be set disabled!
if (isAdmin(context)) {
user.setEnabled();
}
m_userDriver.writeUser(user);
// update the cache
clearUserCache(user);
putUserInCache(user);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeUser() " + user.getName(), CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Updates the user information of a web user.<p>
*
* Only users of the user type webuser can be updated this way.<p>
*
* @param user the user to be updated
*
* @throws CmsException if operation was not succesful
*/
public void writeWebUser(CmsUser user) throws CmsException {
// Check the security
if (user.isWebUser()) {
m_userDriver.writeUser(user);
// update the cache
clearUserCache(user);
putUserInCache(user);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeWebUser() " + user.getName(), CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Reads the resources that were published in a publish task for a given publish history ID.<p>
*
* @param context the current request context
* @param publishHistoryId unique int ID to identify each publish task in the publish history
* @return a List of CmsPublishedResource objects
* @throws CmsException if something goes wrong
*/
public List readPublishedResources(CmsRequestContext context, CmsUUID publishHistoryId) throws CmsException {
return getProjectDriver().readPublishedResources(context.currentProject().getId(), publishHistoryId);
}
/**
* Update the export points.<p>
*
* All files and folders "inside" an export point are written.<p>
*
* @param context the current request context
* @param report an I_CmsReport instance to print output message, or null to write messages to the log file
*/
public void updateExportPoints(CmsRequestContext context, I_CmsReport report) {
Set exportPoints = null;
String currentExportPoint = null;
List resources = (List) new ArrayList();
Iterator i = null;
CmsResource currentResource = null;
CmsExportPointDriver exportPointDriver = null;
CmsProject oldProject = null;
try {
// save the current project before we switch to the online project
oldProject = context.currentProject();
context.setCurrentProject(readProject(I_CmsConstants.C_PROJECT_ONLINE_ID));
// read the export points and return immediately if there are no export points at all
exportPoints = OpenCms.getExportPoints();
if (exportPoints.size() == 0) {
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn("No export points configured at all.");
}
return;
}
// the report may be null if the export points indicated by an event on a remote server
if (report == null) {
report = (I_CmsReport) new CmsLogReport();
}
// create a disc driver to write exports
exportPointDriver = new CmsExportPointDriver(exportPoints);
// the export point hash table contains RFS export paths keyed by their internal VFS paths
i = exportPointDriver.getExportPointPaths().iterator();
while (i.hasNext()) {
currentExportPoint = (String) i.next();
// print some report messages
if (OpenCms.getLog(this).isInfoEnabled()) {
OpenCms.getLog(this).info("Writing export point " + currentExportPoint);
}
try {
resources = readAllSubResourcesInDfs(context, currentExportPoint, -1);
setFullResourceNames(context, resources);
Iterator j = resources.iterator();
while (j.hasNext()) {
currentResource = (CmsResource) j.next();
if (currentResource.getType() == CmsResourceTypeFolder.C_RESOURCE_TYPE_ID) {
// export the folder
exportPointDriver.createFolder(currentResource.getRootPath(), currentExportPoint);
} else {
// try to create the exportpoint folder
exportPointDriver.createFolder(currentExportPoint, currentExportPoint);
// export the file content online
CmsFile file = getVfsDriver().readFile(I_CmsConstants.C_PROJECT_ONLINE_ID, false, currentResource.getStructureId());
file.setFullResourceName(currentResource.getRootPath());
writeExportPoint(context, exportPointDriver, currentExportPoint, file);
}
}
} catch (CmsException e) {
// there might exist export points without corresponding resources in the VFS
// -> ingore exceptions which are not "resource not found" exception quiet here
if (e.getType() != CmsException.C_NOT_FOUND) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error updating export points", e);
}
}
}
}
} catch (CmsException e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error updating export points", e);
}
} finally {
context.setCurrentProject(oldProject);
}
}
/**
* Writes all export points into the file system for a publish task
* specified by its publish history ID.<p>
*
* @param context the current request context
* @param report an I_CmsReport instance to print output message, or null to write messages to the log file
* @param publishHistoryId unique int ID to identify each publish task in the publish history
*/
public void writeExportPoints(CmsRequestContext context, I_CmsReport report, CmsUUID publishHistoryId) {
Set exportPoints = null;
CmsExportPointDriver exportPointDriver = null;
List publishedResources = null;
CmsPublishedResource currentPublishedResource = null;
String currentExportKey = null;
boolean printReportHeaders = false;
try {
// read the export points and return immediately if there are no export points at all
exportPoints = OpenCms.getExportPoints();
if (exportPoints.size() == 0) {
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn("No export points configured at all.");
}
return;
}
// the report may be null if the export points indicated by an event on a remote server
if (report == null) {
report = (I_CmsReport) new CmsLogReport();
}
// read the "published resources" for the specified publish history ID
publishedResources = getProjectDriver().readPublishedResources(context.currentProject().getId(), publishHistoryId);
if (publishedResources.size() == 0) {
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn("No published resources in the publish history for the specified ID " + publishHistoryId + " found.");
}
return;
}
// create a disc driver to write exports
exportPointDriver = new CmsExportPointDriver(exportPoints);
// iterate over all published resources to export them eventually
Iterator i = publishedResources.iterator();
while (i.hasNext()) {
currentPublishedResource = (CmsPublishedResource) i.next();
currentExportKey = exportPointDriver.getExportPoint(currentPublishedResource.getRootPath());
if (currentExportKey != null) {
if (!printReportHeaders) {
report.println(report.key("report.export_points_write_begin"), I_CmsReport.C_FORMAT_HEADLINE);
printReportHeaders = true;
}
if (currentPublishedResource.getType() == CmsResourceTypeFolder.C_RESOURCE_TYPE_ID) {
// export the folder
if (currentPublishedResource.getState() == I_CmsConstants.C_STATE_DELETED) {
exportPointDriver.removeResource(currentPublishedResource.getRootPath(), currentExportKey);
} else {
exportPointDriver.createFolder(currentPublishedResource.getRootPath(), currentExportKey);
}
} else {
// export the file
if (currentPublishedResource.getState() == I_CmsConstants.C_STATE_DELETED) {
exportPointDriver.removeResource(currentPublishedResource.getRootPath(), currentExportKey);
} else {
// read the file content online
CmsFile file = getVfsDriver().readFile(I_CmsConstants.C_PROJECT_ONLINE_ID, false, currentPublishedResource.getStructureId());
file.setFullResourceName(currentPublishedResource.getRootPath());
writeExportPoint(context, exportPointDriver, currentExportKey, file);
}
}
// print some report messages
if (currentPublishedResource.getState() == I_CmsConstants.C_STATE_DELETED) {
report.print(report.key("report.export_points_delete"), I_CmsReport.C_FORMAT_NOTE);
report.print(currentPublishedResource.getRootPath());
report.print(report.key("report.dots"));
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
} else {
report.print(report.key("report.export_points_write"), I_CmsReport.C_FORMAT_NOTE);
report.print(currentPublishedResource.getRootPath());
report.print(report.key("report.dots"));
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
}
}
}
} catch (CmsException e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error writing export points", e);
}
} finally {
if (printReportHeaders) {
report.println(report.key("report.export_points_write_end"), I_CmsReport.C_FORMAT_HEADLINE);
}
}
}
/**
* Exports a specified resource into the local filesystem as an "export point".<p>
*
* @param context the current request context
* @param discAccess the export point driver
* @param exportKey the export key of the export point
* @param file the file that gets exported
* @throws CmsException if something goes wrong
*/
private void writeExportPoint(
CmsRequestContext context,
CmsExportPointDriver discAccess,
String exportKey,
CmsFile file) throws CmsException {
byte[] contents = null;
String encoding = null;
CmsProperty property = null;
try {
// make sure files are written using the correct character encoding
contents = file.getContents();
property = getVfsDriver().readPropertyObject(
I_CmsConstants.C_PROPERTY_CONTENT_ENCODING,
context.currentProject(),
file);
encoding = (property != null) ? property.getValue() : null;
if (encoding != null) {
// only files that have the encodig property set will be encoded,
// other files will be ignored. images etc. are not touched.
try {
contents = (new String(contents, encoding)).getBytes();
} catch (UnsupportedEncodingException e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Unsupported encoding of " + file.toString(), e);
}
throw new CmsException("Unsupported encoding of " + file.toString(), e);
}
}
discAccess.writeFile(file.getRootPath(), exportKey, contents);
} catch (Exception e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error writing export point of " + file.toString(), e);
}
throw new CmsException("Error writing export point of " + file.toString(), e);
}
contents = null;
}
/**
* Completes all post-publishing tasks for a "directly" published COS resource.<p>
*
* @param context the current request context
* @param publishedBoResource the CmsPublishedResource onject representing the published COS resource
* @param publishId unique int ID to identify each publish task in the publish history
* @param tagId the backup tag revision
* @throws CmsException if something goes wrong
*/
public void postPublishBoResource(CmsRequestContext context, CmsPublishedResource publishedBoResource, CmsUUID publishId, int tagId) throws CmsException {
m_projectDriver.writePublishHistory(context.currentProject(), publishId, tagId, publishedBoResource.getContentDefinitionName(), publishedBoResource.getMasterId(), publishedBoResource.getType(), publishedBoResource.getState());
}
/**
* Returns a Cms publish list object containing the Cms resources that actually get published.<p>
*
* <ul>
* <li>
* <b>Case 1 (publish project)</b>: all new/changed/deleted Cms file resources in the current (offline)
* project are inspected whether they would get published or not.
* </li>
* <li>
* <b>Case 2 (direct publish a resource)</b>: a specified Cms file resource and optionally it's siblings
* are inspected whether they get published.
* </li>
* </ul>
*
* All Cms resources inside the publish ist are equipped with their full resource name including
* the site root.<p>
*
* Please refer to the source code of this method for the rules on how to decide whether a
* new/changed/deleted Cms resource can be published or not.<p>
*
* @param context the current request context
* @param directPublishResource a Cms resource to be published directly (in case 2), or null (in case 1)
* @param directPublishSiblings true, if all eventual siblings of the direct published resource should also get published (in case 2)
* @param report an instance of I_CmsReport to print messages
* @return a publish list with all new/changed/deleted files from the current (offline) project that will be published actually
* @throws CmsException if something goes wrong
* @see org.opencms.db.CmsPublishList
*/
public synchronized CmsPublishList getPublishList(CmsRequestContext context, CmsResource directPublishResource, boolean directPublishSiblings, I_CmsReport report) throws CmsException {
CmsPublishList publishList = null;
List offlineFiles = null;
List siblings = null;
List projectResources = null;
List offlineFolders = null;
List sortedFolderList = null;
Iterator i = null;
Iterator j = null;
Map sortedFolderMap = null;
CmsResource currentSibling = null;
CmsResource currentFileHeader = null;
boolean directPublish = false;
boolean directPublishFile = false;
boolean publishCurrentResource = false;
String currentResourceName = null;
String currentSiblingName = null;
CmsLock currentLock = null;
CmsFolder currentFolder = null;
List deletedFolders = null;
CmsProperty property = null;
try {
report.println(report.key("report.publish_prepare_resources"), I_CmsReport.C_FORMAT_HEADLINE);
////////////////////////////////////////////////////////////////////////////////////////
// read the project resources of the project that gets published
// (= folders that belong to the current project)
report.print(report.key("report.publish_read_projectresources") + report.key("report.dots"));
projectResources = readProjectResources(context.currentProject());
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
////////////////////////////////////////////////////////////////////////////////////////
// construct a publish list
directPublish = directPublishResource != null;
directPublishFile = directPublish && directPublishResource.isFile();
if (directPublishFile) {
// a file resource gets published directly
publishList = new CmsPublishList(directPublishResource, directPublishFile);
} else {
if (directPublish) {
// a folder resource gets published directly
publishList = new CmsPublishList(directPublishResource, directPublishFile);
} else {
// a project gets published directly
publishList = new CmsPublishList();
}
}
////////////////////////////////////////////////////////////////////////////////////////
// identify all new/changed/deleted Cms folder resources to be published
// don't select and sort unpublished folders if a file gets published directly
if (!directPublishFile) {
report.println(report.key("report.publish_prepare_folders"), I_CmsReport.C_FORMAT_HEADLINE);
sortedFolderMap = (Map) new HashMap();
deletedFolders = (List) new ArrayList();
// read all changed/new/deleted folders
report.print(report.key("report.publish_read_projectfolders") + report.key("report.dots"));
offlineFolders = getVfsDriver().readFolders(context.currentProject().getId());
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
// sort out all folders that will not be published
report.print(report.key("report.publish_filter_folders") + report.key("report.dots"));
i = offlineFolders.iterator();
while (i.hasNext()) {
publishCurrentResource = false;
currentFolder = (CmsFolder) i.next();
currentResourceName = readPath(context, currentFolder, true);
currentFolder.setFullResourceName(currentResourceName);
currentLock = getLock(context, currentResourceName);
// the resource must have either a new/deleted state in the link or a new/delete state in the resource record
publishCurrentResource = currentFolder.getState() > I_CmsConstants.C_STATE_UNCHANGED;
if (directPublish) {
// the resource must be a sub resource of the direct-publish-resource in case of a "direct publish"
publishCurrentResource = publishCurrentResource && currentResourceName.startsWith(publishList.getDirectPublishResourceName());
} else {
// the resource must have a changed state and must be changed in the project that is currently published
publishCurrentResource = publishCurrentResource && currentFolder.getProjectLastModified() == context.currentProject().getId();
// the resource must be in one of the paths defined for the project
publishCurrentResource = publishCurrentResource && CmsProject.isInsideProject(projectResources, currentFolder);
}
// the resource must be unlocked
publishCurrentResource = publishCurrentResource && currentLock.isNullLock();
if (publishCurrentResource) {
sortedFolderMap.put(currentResourceName, currentFolder);
}
}
// ensure that the folders appear in the correct (DFS) top-down tree order
sortedFolderList = (List) new ArrayList(sortedFolderMap.keySet());
Collections.sort(sortedFolderList);
// split the folders up into new/changed folders and deleted folders
i = sortedFolderList.iterator();
while (i.hasNext()) {
currentResourceName = (String) i.next();
currentFolder = (CmsFolder) sortedFolderMap.get(currentResourceName);
if (currentFolder.getState() == I_CmsConstants.C_STATE_DELETED) {
deletedFolders.add(currentResourceName);
} else {
publishList.addFolder(currentFolder);
}
}
if (deletedFolders.size() > 0) {
// ensure that the deleted folders appear in the correct (DFS) bottom-up tree order
Collections.sort(deletedFolders);
Collections.reverse(deletedFolders);
i = deletedFolders.iterator();
while (i.hasNext()) {
currentResourceName = (String) i.next();
currentFolder = (CmsFolder) sortedFolderMap.get(currentResourceName);
publishList.addDeletedFolder(currentFolder);
}
}
// clean up any objects that are not needed anymore instantly
if (sortedFolderList != null) {
sortedFolderList.clear();
sortedFolderList = null;
}
if (sortedFolderMap != null) {
sortedFolderMap.clear();
sortedFolderMap = null;
}
if (offlineFolders != null) {
offlineFolders.clear();
offlineFolders = null;
}
if (deletedFolders != null) {
deletedFolders.clear();
deletedFolders = null;
}
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
report.println(report.key("report.publish_prepare_folders_finished"), I_CmsReport.C_FORMAT_HEADLINE);
} else {
// a file gets published directly- the list of unpublished folders remain empty
}
///////////////////////////////////////////////////////////////////////////////////////////
// identify all new/changed/deleted Cms file resources to be published
report.println(report.key("report.publish_prepare_files"), I_CmsReport.C_FORMAT_HEADLINE);
report.print(report.key("report.publish_read_projectfiles") + report.key("report.dots"));
if (directPublishFile) {
// add this resource as a candidate to the unpublished offline file headers
offlineFiles = (List) new ArrayList();
offlineFiles.add(directPublishResource);
if (directPublishSiblings) {
// add optionally all siblings of the direct published resource as candidates
siblings = readSiblings(context, directPublishResource.getRootPath(), false, true);
i = siblings.iterator();
while (i.hasNext()) {
currentSibling = (CmsResource) i.next();
try {
getVfsDriver().readFolder(I_CmsConstants.C_PROJECT_ONLINE_ID, currentSibling.getParentStructureId());
offlineFiles.add(currentSibling);
} catch (CmsException e) {
// the parent folder of the current sibling
// is not yet published- skip this sibling
}
}
}
} else {
// add all unpublished offline file headers as candidates
offlineFiles = getVfsDriver().readFiles(context.currentProject().getId());
}
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
// sort out candidates that will not be published
report.print(report.key("report.publish_filter_files") + report.key("report.dots"));
i = offlineFiles.iterator();
while (i.hasNext()) {
publishCurrentResource = false;
currentFileHeader = (CmsResource) i.next();
currentResourceName = readPath(context, currentFileHeader, true);
currentFileHeader.setFullResourceName(currentResourceName);
currentLock = getLock(context, currentResourceName);
switch (currentFileHeader.getState()) {
// the current resource is deleted
case I_CmsConstants.C_STATE_DELETED :
// it is published, if it was changed to deleted in the current project
property = getVfsDriver().readPropertyObject(I_CmsConstants.C_PROPERTY_INTERNAL, context.currentProject(), currentFileHeader);
String delProject = (property != null) ? property.getValue() : null;
// a project gets published or a folder gets published directly
if (delProject != null && delProject.equals("" + context.currentProject().getId())) {
publishCurrentResource = true;
} else {
publishCurrentResource = false;
}
//}
break;
// the current resource is new
case I_CmsConstants.C_STATE_NEW :
// it is published, if it was created in the current project
// or if it is a new sibling of another resource that is currently not changed in any project
publishCurrentResource = currentFileHeader.getProjectLastModified() == context.currentProject().getId() || currentFileHeader.getProjectLastModified() == 0;
break;
// the current resource is changed
case I_CmsConstants.C_STATE_CHANGED :
// it is published, if it was changed in the current project
publishCurrentResource = currentFileHeader.getProjectLastModified() == context.currentProject().getId();
break;
// the current resource is unchanged
case I_CmsConstants.C_STATE_UNCHANGED :
default :
// so it is not published
publishCurrentResource = false;
break;
}
if (directPublish) {
if (directPublishResource.isFolder()) {
if (directPublishSiblings) {
// a resource must be published if it is inside the folder which was selected
// for direct publishing, or if one of its siblings is inside the folder
if (currentFileHeader.getLinkCount() == 1) {
// this resource has no siblings
// the resource must be a sub resource of the direct-publish-resource in
// case of a "direct publish"
publishCurrentResource = publishCurrentResource && currentResourceName.startsWith(directPublishResource.getRootPath());
} else {
// the resource has some siblings, so check if they are inside the
// folder to be published
siblings = readSiblings(context, currentResourceName, true, true);
j = siblings.iterator();
boolean siblingInside = false;
while (j.hasNext()) {
currentSibling = (CmsResource) j.next();
currentSiblingName = readPath(context, currentSibling, true);
if (currentSiblingName.startsWith(directPublishResource.getRootPath())) {
siblingInside = true;
break;
}
}
publishCurrentResource = publishCurrentResource && siblingInside;
}
} else {
// the resource must be a sub resource of the direct-publish-resource in
// case of a "direct publish"
publishCurrentResource = publishCurrentResource && currentResourceName.startsWith(directPublishResource.getRootPath());
}
}
} else {
// the resource must be in one of the paths defined for the project
publishCurrentResource = publishCurrentResource && CmsProject.isInsideProject(projectResources, currentFileHeader);
}
// do not publish resources that are locked
publishCurrentResource = publishCurrentResource && currentLock.isNullLock();
// NOTE: temporary files are not removed any longer while publishing
if (currentFileHeader.getName().startsWith(I_CmsConstants.C_TEMP_PREFIX)) {
// trash the current resource if it is a temporary file
getVfsDriver().deleteProperties(context.currentProject().getId(), currentFileHeader);
getVfsDriver().removeFile(context.currentProject(), currentFileHeader, true);
}
if (!publishCurrentResource) {
i.remove();
}
}
// add the new/changed/deleted Cms file resources to the publish list
publishList.addFiles(offlineFiles);
// clean up any objects that are not needed anymore instantly
offlineFiles.clear();
offlineFiles = null;
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
report.println(report.key("report.publish_prepare_files_finished"), I_CmsReport.C_FORMAT_HEADLINE);
////////////////////////////////////////////////////////////////////////////////////////////
report.println(report.key("report.publish_prepare_resources_finished"), I_CmsReport.C_FORMAT_HEADLINE);
} catch (OutOfMemoryError o) {
if (OpenCms.getLog(this).isFatalEnabled()) {
OpenCms.getLog(this).fatal("Out of memory error while publish list is built", o);
}
// clear all caches to reclaim memory
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false));
// force a complete object finalization and garbage collection
System.runFinalization();
Runtime.getRuntime().runFinalization();
System.gc();
Runtime.getRuntime().gc();
throw new CmsException("Out of memory error while publish list is built", o);
}
return publishList;
}
/**
* Returns the HTML link validator.<p>
*
* @return the HTML link validator
* @see CmsHtmlLinkValidator
*/
public CmsHtmlLinkValidator getHtmlLinkValidator() {
return m_htmlLinkValidator;
}
/**
* Validates the Cms resources in a Cms publish list.<p>
*
* @param cms the current user's Cms object
* @param publishList a Cms publish list
* @param report an instance of I_CmsReport to print messages
* @return a map with lists of invalid links keyed by resource names
* @throws Exception if something goes wrong
* @see #getPublishList(CmsRequestContext, CmsResource, boolean, I_CmsReport)
*/
public Map validateHtmlLinks(CmsObject cms, CmsPublishList publishList, I_CmsReport report) throws Exception {
return getHtmlLinkValidator().validateResources(cms, publishList.getFileList(), report);
}
/**
* Updates the date information in the request context.<p>
*
* @param context the context to update
* @param resource the resource to get the date information from
*/
private void updateContextDates(CmsRequestContext context, CmsResource resource) {
CmsFlexRequestContextInfo info = (CmsFlexRequestContextInfo) context.getAttribute(I_CmsConstants.C_HEADER_LAST_MODIFIED);
if (info != null) {
info.updateDateLastModified(resource.getDateLastModified());
}
}
/**
* Writes a property object to the database mapped to a specified resource.<p>
*
* @param context the context of the current request
* @param resourceName the name of resource where the property is mapped to
* @param property a CmsProperty object containing a structure and/or resource value
* @throws CmsException if something goes wrong
*/
public void writePropertyObject(CmsRequestContext context, String resourceName, CmsProperty property) throws CmsException {
CmsResource resource = null;
try {
// read the file header
resource = readFileHeader(context, resourceName);
// check the permissions
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
// write the property
m_vfsDriver.writePropertyObject(context.currentProject(), resource, property);
// update the resource state
if (resource.isFile()) {
m_vfsDriver.writeFileHeader(context.currentProject(), (CmsFile)resource, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
} else {
m_vfsDriver.writeFolder(context.currentProject(), (CmsFolder)resource, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
}
} finally {
// update the driver manager cache
clearResourceCache();
m_propertyCache.clear();
// fire an event that a property of a resource has been modified
Map data = (Map) new HashMap();
data.put("resource", resource);
data.put("property", property);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROPERTY_MODIFIED, data));
}
}
/**
* Writes a list of property objects to the database mapped to a specified resource.<p>
*
* @param context the context of the current request
* @param resourceName the name of resource where the property is mapped to
* @param properties a list of CmsPropertys object containing a structure and/or resource value
* @throws CmsException if something goes wrong
*/
public void writePropertyObjects(CmsRequestContext context, String resourceName, List properties) throws CmsException {
CmsProperty property = null;
CmsResource resource = null;
try {
// read the file header
resource = readFileHeader(context, resourceName);
// check the permissions
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
for (int i = 0; i < properties.size(); i++) {
// write the property
property = (CmsProperty) properties.get(i);
m_vfsDriver.writePropertyObject(context.currentProject(), resource, property);
}
// update the resource state
if (resource.isFile()) {
m_vfsDriver.writeFileHeader(context.currentProject(), (CmsFile) resource, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
} else {
m_vfsDriver.writeFolder(context.currentProject(), (CmsFolder) resource, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
}
} finally {
// update the driver manager cache
clearResourceCache();
m_propertyCache.clear();
// fire an event that the properties of a resource have been modified
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", resource)));
}
}
/**
* Reads all property objects mapped to a specified resource from the database.<p>
*
* Returns an empty list if no properties are found at all.<p>
*
* @param context the context of the current request
* @param resourceName the name of resource where the property is mapped to
* @param siteRoot the current site root
* @param search true, if the properties should be searched on all parent folders if not found on the resource
* @return a list of CmsProperty objects containing the structure and/or resource value
* @throws CmsException if something goes wrong
*/
public List readPropertyObjects(CmsRequestContext context, String resourceName, String siteRoot, boolean search) throws CmsException {
// read the file header
CmsResource resource = readFileHeader(context, resourceName);
// check the permissions
checkPermissions(context, resource, I_CmsConstants.C_READ_OR_VIEW_ACCESS);
// check if search mode is enabled
search = search && (siteRoot != null);
// check if we have the result already cached
String cacheKey = getCacheKey(C_CACHE_ALL_PROPERTIES + search, context.currentProject().getId(), resource.getRootPath());
List value = (List)m_propertyCache.get(cacheKey);
if (value == null) {
// result not cached, let's look it up in the DB
if (search) {
boolean cont;
siteRoot += "/";
value = (List)new ArrayList();
List parentValue;
do {
try {
parentValue = readPropertyObjects(context, resourceName, siteRoot, false);
parentValue.addAll(value);
value.clear();
value.addAll(parentValue);
resourceName = CmsResource.getParentFolder(resourceName);
cont = (!"/".equals(resourceName));
} catch (CmsSecurityException se) {
// a security exception (probably no read permission) we return the current result
cont = false;
}
} while (cont);
} else {
value = m_vfsDriver.readPropertyObjects(context.currentProject(), resource);
}
// store the result in the cache
m_propertyCache.put(cacheKey, value);
}
return (List) new ArrayList(value);
}
/**
* Reads a property object from the database specified by it's key name mapped to a resource.<p>
*
* Returns null if the property is not found.<p>
*
* @param context the context of the current request
* @param resourceName the name of resource where the property is mapped to
* @param siteRoot the current site root
* @param key the property key name
* @param search true, if the property should be searched on all parent folders if not found on the resource
* @return a CmsProperty object containing the structure and/or resource value
* @throws CmsException if something goes wrong
*/
public CmsProperty readPropertyObject(CmsRequestContext context, String resourceName, String siteRoot, String key, boolean search) throws CmsException {
// read the resource
CmsResource resource = readFileHeader(context, resourceName);
// check the security
checkPermissions(context, resource, I_CmsConstants.C_READ_OR_VIEW_ACCESS);
// check if search mode is enabled
search = search && (siteRoot != null);
// check if we have the result already cached
String cacheKey = getCacheKey(key + search, context.currentProject().getId(), resource.getRootPath());
CmsProperty value = (CmsProperty) m_propertyCache.get(cacheKey);
if (value == null) {
// check if the map of all properties for this resource is already cached
String cacheKey2 = getCacheKey(C_CACHE_ALL_PROPERTIES + search, context.currentProject().getId(), resource.getRootPath());
List allProperties = (List) m_propertyCache.get(cacheKey2);
if (allProperties != null) {
// list of properties already read, look up value there
for (int i = 0; i < allProperties.size(); i++) {
CmsProperty property = (CmsProperty) allProperties.get(i);
if (property.getKey().equals(key)) {
value = property;
break;
}
}
} else if (search) {
// result not cached, look it up recursivly with search enabled
String cacheKey3 = getCacheKey(key + false, context.currentProject().getId(), resource.getRootPath());
value = (CmsProperty) m_propertyCache.get(cacheKey3);
if ((value == null) || value.isNullProperty()) {
boolean cont;
siteRoot += "/";
do {
try {
value = readPropertyObject(context, resourceName, siteRoot, key, false);
cont = (value.isNullProperty() && (!"/".equals(resourceName)));
} catch (CmsSecurityException se) {
// a security exception (probably no read permission) we return the current result
cont = false;
}
if (cont) {
resourceName = CmsResource.getParentFolder(resourceName);
}
} while (cont);
}
} else {
// result not cached, look it up in the DB without search
value = m_vfsDriver.readPropertyObject(key, context.currentProject(), resource);
}
if (value == null) {
value = CmsProperty.getNullProperty();
}
// store the result in the cache
m_propertyCache.put(cacheKey, value);
}
return value;
}
}
| src/org/opencms/db/CmsDriverManager.java | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/db/CmsDriverManager.java,v $
* Date : $Date: 2004/04/02 17:01:11 $
* Version: $Revision: 1.348 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2002 - 2003 Alkacon Software (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.db;
import org.opencms.file.*;
import org.opencms.flex.CmsFlexRequestContextInfo;
import org.opencms.lock.CmsLock;
import org.opencms.lock.CmsLockException;
import org.opencms.lock.CmsLockManager;
import org.opencms.main.CmsEvent;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.I_CmsConstants;
import org.opencms.main.I_CmsEventListener;
import org.opencms.main.OpenCms;
import org.opencms.main.OpenCmsCore;
import org.opencms.report.CmsLogReport;
import org.opencms.report.I_CmsReport;
import org.opencms.security.CmsAccessControlEntry;
import org.opencms.security.CmsAccessControlList;
import org.opencms.security.CmsPermissionSet;
import org.opencms.security.CmsSecurityException;
import org.opencms.security.I_CmsPasswordValidation;
import org.opencms.security.I_CmsPrincipal;
import org.opencms.util.CmsUUID;
import org.opencms.validation.CmsHtmlLinkValidator;
import org.opencms.workflow.CmsTask;
import org.opencms.workflow.CmsTaskLog;
import org.opencms.workplace.CmsWorkplaceManager;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.commons.collections.map.LRUMap;
/**
* This is the driver manager.<p>
*
* @author Alexander Kandzior ([email protected])
* @author Thomas Weckert ([email protected])
* @author Carsten Weinholz ([email protected])
* @author Michael Emmerich ([email protected])
* @version $Revision: 1.348 $ $Date: 2004/04/02 17:01:11 $
* @since 5.1
*/
public class CmsDriverManager extends Object implements I_CmsEventListener {
/**
* Provides a method to build cache keys for groups and users that depend either on
* a name string or an id.<p>
*
* @author Alkexander Kandzior ([email protected])
*/
private class CacheId extends Object {
/**
* Name of the object
*/
public String m_name = null;
/**
* Id of the object
*/
public CmsUUID m_uuid = null;
/**
* Creates a new CacheId for a CmsGroup.<p>
*
* @param group the group to create a cache id from
*/
public CacheId(CmsGroup group) {
m_name = group.getName();
m_uuid = group.getId();
}
/**
* Creates a new CacheId for a CmsResource.<p>
*
* @param resource the resource to create a cache id from
*/
public CacheId(CmsResource resource) {
m_name = resource.getName();
m_uuid = resource.getResourceId();
}
/**
* Creates a new CacheId for a CmsUser.<p>
*
* @param user the user to create a cache id from
*/
public CacheId(CmsUser user) {
m_name = user.getName() + user.getType();
m_uuid = user.getId();
}
/**
* Creates a new CacheId for a CmsUUID.<p>
*
* @param uuid the uuid to create a cache id from
*/
public CacheId(CmsUUID uuid) {
m_uuid = uuid;
}
/**
* Creates a new CacheId for a String.<p>
*
* @param str the string to create a cache id from
*/
public CacheId(String str) {
m_name = str;
}
/**
* Creates a new CacheId for a String and CmsUUID.<p>
*
* @param name the string to create a cache id from
* @param uuid the uuid to create a cache id from
*/
public CacheId(String name, CmsUUID uuid) {
m_name = name;
m_uuid = uuid;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof CacheId)) {
return false;
}
CacheId other = (CacheId)o;
boolean result;
if (m_uuid != null) {
result = m_uuid.equals(other.m_uuid);
if (result) {
return true;
}
}
if (m_name != null) {
result = m_name.equals(other.m_name);
if (result) {
return true;
}
}
return false;
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
if (m_uuid == null) {
return 509;
} else {
return m_uuid.hashCode();
}
}
}
/**
* Key for all properties
*/
public static final String C_CACHE_ALL_PROPERTIES = "__CACHE_ALL_PROPERTIES__";
/**
* Key for null value
*/
public static final String C_CACHE_NULL_PROPERTY_VALUE = "__CACHE_NULL_PROPERTY_VALUE__";
/**
* Key for indicating no changes
*/
public static final int C_NOTHING_CHANGED = 0;
/**
* Key to indicate complete update
*/
public static final int C_UPDATE_ALL = 3;
/**
* Key to indicate update of resource record
*/
public static final int C_UPDATE_RESOURCE = 4;
/**
* Key to indicate update of resource state
*/
public static final int C_UPDATE_RESOURCE_STATE = 1;
/**
* Key to indicate update of struicture record
*/
public static final int C_UPDATE_STRUCTURE = 5;
/**
* Key to indicate update of structure state
*/
public static final int C_UPDATE_STRUCTURE_STATE = 2;
/**
* Separator for user cache
*/
private static final String C_USER_CACHE_SEP = "\u0000";
/**
* Cache for access control lists
*/
private Map m_accessControlListCache;
/**
* The backup driver
*/
private I_CmsBackupDriver m_backupDriver;
/**
* The configuration of the property-file.
*/
private ExtendedProperties m_configuration;
/**
* Constant to count the file-system changes if Folders are involved.
*/
private long m_fileSystemFolderChanges;
/**
* Cache for groups
*/
private Map m_groupCache;
/**
* The portnumber the workplace access is limited to.
*/
private int m_limitedWorkplacePort = -1;
/**
* The lock manager
*/
private CmsLockManager m_lockManager = OpenCms.getLockManager();
/**
* The class used for password validation
*/
private I_CmsPasswordValidation m_passwordValidationClass;
/**
* The class used for cache key generation
*/
private I_CmsCacheKey m_keyGenerator;
/**
* Cache for permission checks
*/
private Map m_permissionCache;
/**
* Cache for offline projects
*/
private Map m_projectCache;
/**
* The project driver
*/
private I_CmsProjectDriver m_projectDriver;
/**
* Cache for properties
*/
private Map m_propertyCache;
/**
* Comment for <code>m_refresh</code>
*/
private String m_refresh;
/**
* The Registry
*/
private CmsRegistry m_registry;
/**
* Cache for resources
*/
private Map m_resourceCache;
/**
* Cache for resource lists
*/
private Map m_resourceListCache;
/**
* Hashtable with resource-types.
*/
private I_CmsResourceType[] m_resourceTypes = null;
/**
* Cache for user data
*/
private Map m_userCache;
/** The user driver. */
private I_CmsUserDriver m_userDriver;
/**
* Cache for user groups
*/
private Map m_userGroupsCache;
/**
* The VFS driver
*/
private I_CmsVfsDriver m_vfsDriver;
/**
* The workflow driver
*/
private I_CmsWorkflowDriver m_workflowDriver;
/**
* The HTML link validator
*/
private CmsHtmlLinkValidator m_htmlLinkValidator;
/**
* Reads the required configurations from the opencms.properties file and creates
* the various drivers to access the cms resources.<p>
*
* The initialization process of the driver manager and its drivers is split into
* the following phases:
* <ul>
* <li>the database pool configuration is read</li>
* <li>a plain and empty driver manager instance is created</li>
* <li>an instance of each driver is created</li>
* <li>the driver manager is passed to each driver during initialization</li>
* <li>finally, the driver instances are passed to the driver manager during initialization</li>
* </ul>
*
* @param configuration the configurations from the propertyfile
* @param resourceTypes the initialized configured resource types
* @return CmsDriverManager the instanciated driver manager.
* @throws CmsException if the driver manager couldn't be instanciated.
*/
public static final CmsDriverManager newInstance(ExtendedProperties configuration, List resourceTypes) throws CmsException {
// initialize static hastables
CmsDbUtil.init();
List drivers = null;
String driverName = null;
I_CmsVfsDriver vfsDriver = null;
I_CmsUserDriver userDriver = null;
I_CmsProjectDriver projectDriver = null;
I_CmsWorkflowDriver workflowDriver = null;
I_CmsBackupDriver backupDriver = null;
CmsDriverManager driverManager = null;
try {
// create a driver manager instance
driverManager = new CmsDriverManager();
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 1 - initializing database");
}
} catch (Exception exc) {
String message = "Critical error while loading driver manager";
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isFatalEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).fatal(message, exc);
}
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 2 - initializing pools");
}
// read the pool names to initialize
String driverPoolNames[] = configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_DB + ".pools");
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
String names = "";
for (int p = 0; p < driverPoolNames.length; p++) {
names += driverPoolNames[p] + " ";
}
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Resource pools : " + names);
}
// initialize each pool
for (int p = 0; p < driverPoolNames.length; p++) {
driverManager.newPoolInstance(configuration, driverPoolNames[p]);
}
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 3 - initializing drivers");
}
// read the vfs driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_VFS));
driverName = configuration.getString((String)drivers.get(0) + ".vfs.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
vfsDriver = (I_CmsVfsDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
// read the user driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_USER));
driverName = configuration.getString((String)drivers.get(0) + ".user.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
userDriver = (I_CmsUserDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
// read the project driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_PROJECT));
driverName = configuration.getString((String)drivers.get(0) + ".project.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
projectDriver = (I_CmsProjectDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
// read the workflow driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_WORKFLOW));
driverName = configuration.getString((String)drivers.get(0) + ".workflow.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
workflowDriver = (I_CmsWorkflowDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
// read the backup driver class properties and initialize a new instance
drivers = Arrays.asList(configuration.getStringArray(I_CmsConstants.C_CONFIGURATION_BACKUP));
driverName = configuration.getString((String)drivers.get(0) + ".backup.driver");
drivers = (drivers.size() > 1) ? drivers.subList(1, drivers.size()) : null;
backupDriver = (I_CmsBackupDriver)driverManager.newDriverInstance(configuration, driverName, drivers);
try {
// invoke the init method of the driver manager
driverManager.init(configuration, vfsDriver, userDriver, projectDriver, workflowDriver, backupDriver);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 4 ok - finished");
}
} catch (Exception exc) {
String message = "Critical error while loading driver manager";
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isFatalEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).fatal(message, exc);
}
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
// set the pool for the COS
// TODO: check if there is a better place for this
String cosPoolUrl = configuration.getString("db.cos.pool");
OpenCms.setRuntimeProperty("cosPoolUrl", cosPoolUrl);
CmsDbUtil.setDefaultPool(cosPoolUrl);
// register the driver manager for clearcache events
org.opencms.main.OpenCms.addCmsEventListener(driverManager, new int[] {
I_CmsEventListener.EVENT_CLEAR_CACHES,
I_CmsEventListener.EVENT_PUBLISH_PROJECT
});
// set the resource type list
driverManager.setResourceTypes(resourceTypes);
// return the configured driver manager
return driverManager;
}
/**
* Sets the internal list of configured resource types.<p>
*
* @param resourceTypes the list of configured resource types
* @throws CmsException if something goes wrong
*/
private void setResourceTypes(List resourceTypes) throws CmsException {
m_resourceTypes = new I_CmsResourceType[resourceTypes.size() * 2];
for (int i = 0; i < resourceTypes.size(); i++) {
// add the resource-type
try {
I_CmsResourceType resTypeClass = (I_CmsResourceType)resourceTypes.get(i);
int pos = resTypeClass.getResourceType();
if (pos > m_resourceTypes.length) {
I_CmsResourceType[] buffer = new I_CmsResourceType[pos * 2];
System.arraycopy(m_resourceTypes, 0, buffer, 0, m_resourceTypes.length);
m_resourceTypes = buffer;
}
m_resourceTypes[pos] = resTypeClass;
} catch (Exception e) {
OpenCms.getLog(this).error("Error initializing resource types", e);
throw new CmsException("[" + getClass().getName() + "] Error while getting ResourceType: " + resourceTypes.get(i) + " from registry ", CmsException.C_UNKNOWN_EXCEPTION);
}
}
}
/**
* Accept a task from the Cms.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task to accept.
*
* @throws CmsException if something goes wrong
*/
public void acceptTask(CmsRequestContext context, int taskId) throws CmsException {
CmsTask task = m_workflowDriver.readTask(taskId);
task.setPercentage(1);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Task was accepted from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Tests if the user can access the project.<p>
*
* All users are granted.
*
* @param context the current request context
* @param projectId the id of the project
* @return true, if the user has access, else returns false
* @throws CmsException if something goes wrong
*/
public boolean accessProject(CmsRequestContext context, int projectId) throws CmsException {
CmsProject testProject = readProject(projectId);
if (projectId == I_CmsConstants.C_PROJECT_ONLINE_ID) {
return true;
}
// is the project unlocked?
if (testProject.getFlags() != I_CmsConstants.C_PROJECT_STATE_UNLOCKED && testProject.getFlags() != I_CmsConstants.C_PROJECT_STATE_INVISIBLE) {
return (false);
}
// is the current-user admin, or the owner of the project?
if ((context.currentProject().getOwnerId().equals(context.currentUser().getId())) || isAdmin(context)) {
return (true);
}
// get all groups of the user
Vector groups = getGroupsOfUser(context, context.currentUser().getName());
// test, if the user is in the same groups like the project.
for (int i = 0; i < groups.size(); i++) {
CmsUUID groupId = ((CmsGroup)groups.elementAt(i)).getId();
if ((groupId.equals(testProject.getGroupId())) || (groupId.equals(testProject.getManagerGroupId()))) {
return (true);
}
}
return (false);
}
/**
* Adds a file extension to the list of known file extensions.<p>
*
* Users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param extension a file extension like 'html'
* @param resTypeName name of the resource type associated to the extension
* @throws CmsException if something goes wrong
*/
public void addFileExtension(CmsRequestContext context, String extension, String resTypeName) throws CmsException {
if (extension != null && resTypeName != null) {
if (isAdmin(context)) {
Hashtable suffixes = (Hashtable)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS);
if (suffixes == null) {
suffixes = new Hashtable();
suffixes.put(extension, resTypeName);
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS, suffixes);
} else {
suffixes.put(extension, resTypeName);
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS, suffixes);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] addFileExtension() " + extension, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
}
/**
* Adds a user to the Cms.<p>
*
* Only a adminstrator can add users to the cms.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param id the id of the user
* @param name the name for the user
* @param password the password for the user
* @param recoveryPassword the recoveryPassword for the user
* @param description the description for the user
* @param firstname the firstname of the user
* @param lastname the lastname of the user
* @param email the email of the user
* @param flags the flags for a user (e.g. I_CmsConstants.C_FLAG_ENABLED)
* @param additionalInfos a Hashtable with additional infos for the user, these
* Infos may be stored into the Usertables (depending on the implementation)
* @param defaultGroup the default groupname for the user
* @param address the address of the user
* @param section the section of the user
* @param type the type of the user
* @return the new user will be returned.
* @throws CmsException if operation was not succesfull
*/
public CmsUser addImportUser(CmsRequestContext context, String id, String name, String password, String recoveryPassword, String description, String firstname, String lastname, String email, int flags, Hashtable additionalInfos, String defaultGroup, String address, String section, int type) throws CmsException {
// Check the security
if (isAdmin(context)) {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
CmsGroup group = readGroup(defaultGroup);
CmsUser newUser = m_userDriver.importUser(new CmsUUID(id), name, password, recoveryPassword, description, firstname, lastname, email, 0, 0, flags, additionalInfos, group, address, section, type, null);
addUserToGroup(context, newUser.getName(), group.getName());
return newUser;
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] addImportUser() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Adds a user to the Cms.<p>
*
* Only a adminstrator can add users to the cms.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param name the new name for the user
* @param password the new password for the user
* @param group the default groupname for the user
* @param description the description for the user
* @param additionalInfos a Hashtable with additional infos for the user, these
* Infos may be stored into the Usertables (depending on the implementation)
* @return the new user will be returned
* @throws CmsException if operation was not succesfull
*/
public CmsUser addUser(CmsRequestContext context, String name, String password, String group, String description, Hashtable additionalInfos) throws CmsException {
// Check the security
if (isAdmin(context)) {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
// check the password
validatePassword(password);
if (name.length() > 0) {
CmsGroup defaultGroup = readGroup(group);
CmsUser newUser = m_userDriver.createUser(name, password, description, " ", " ", " ", 0, I_CmsConstants.C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
addUserToGroup(context, newUser.getName(), defaultGroup.getName());
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_INVALID_PASSWORD);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] addUser() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Adds a user to a group.<p>
*
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param username the name of the user that is to be added to the group
* @param groupname the name of the group
* @throws CmsException if operation was not succesfull
*/
public void addUserToGroup(CmsRequestContext context, String username, String groupname) throws CmsException {
if (!userInGroup(context, username, groupname)) {
// Check the security
if (isAdmin(context)) {
CmsUser user;
CmsGroup group;
try {
user = readUser(username);
} catch (CmsException e) {
if (e.getType() == CmsException.C_NO_USER) {
user = readWebUser(username);
} else {
throw e;
}
}
//check if the user exists
if (user != null) {
group = readGroup(groupname);
//check if group exists
if (group != null) {
//add this user to the group
m_userDriver.createUserInGroup(user.getId(), group.getId(), null);
// update the cache
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]" + groupname, CmsException.C_NO_GROUP);
}
} else {
throw new CmsException("[" + getClass().getName() + "]" + username, CmsException.C_NO_USER);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] addUserToGroup() " + username + " " + groupname, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
}
/**
* Adds a web user to the Cms.<p>
*
* A web user has no access to the workplace but is able to access personalized
* functions controlled by the OpenCms.
*
* @param name the new name for the user
* @param password the new password for the user
* @param group the default groupname for the user
* @param description the description for the user
* @param additionalInfos a Hashtable with additional infos for the user, these
* Infos may be stored into the Usertables (depending on the implementation)
* @return the new user will be returned.
* @throws CmsException if operation was not succesfull.
*/
public CmsUser addWebUser(String name, String password, String group, String description, Hashtable additionalInfos) throws CmsException {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
// check the password
validatePassword(password);
if ((name.length() > 0)) {
CmsGroup defaultGroup = readGroup(group);
CmsUser newUser = m_userDriver.createUser(name, password, description, " ", " ", " ", 0, I_CmsConstants.C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", I_CmsConstants.C_USER_TYPE_WEBUSER);
CmsUser user;
CmsGroup usergroup;
user = m_userDriver.readUser(newUser.getName(), I_CmsConstants.C_USER_TYPE_WEBUSER);
//check if the user exists
if (user != null) {
usergroup = readGroup(group);
//check if group exists
if (usergroup != null) {
//add this user to the group
m_userDriver.createUserInGroup(user.getId(), usergroup.getId(), null);
// update the cache
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]" + group, CmsException.C_NO_GROUP);
}
} else {
throw new CmsException("[" + getClass().getName() + "]" + name, CmsException.C_NO_USER);
}
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_INVALID_PASSWORD);
}
}
/**
* Adds a web user to the Cms.<p>
*
* A web user has no access to the workplace but is able to access personalized
* functions controlled by the OpenCms.<p>
*
* @param name the new name for the user
* @param password the new password for the user
* @param group the default groupname for the user
* @param additionalGroup an additional group for the user
* @param description the description for the user
* @param additionalInfos a Hashtable with additional infos for the user, these
* Infos may be stored into the Usertables (depending on the implementation)
* @return the new user will be returned.
* @throws CmsException if operation was not succesfull.
*/
public CmsUser addWebUser(String name, String password, String group, String additionalGroup, String description, Hashtable additionalInfos) throws CmsException {
// no space before or after the name
name = name.trim();
// check the username
validFilename(name);
// check the password
validatePassword(password);
if ((name.length() > 0)) {
CmsGroup defaultGroup = readGroup(group);
CmsUser newUser = m_userDriver.createUser(name, password, description, " ", " ", " ", 0, I_CmsConstants.C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", I_CmsConstants.C_USER_TYPE_WEBUSER);
CmsUser user;
CmsGroup usergroup;
CmsGroup addGroup;
user = m_userDriver.readUser(newUser.getName(), I_CmsConstants.C_USER_TYPE_WEBUSER);
//check if the user exists
if (user != null) {
usergroup = readGroup(group);
//check if group exists
if (usergroup != null && isWebgroup(usergroup)) {
//add this user to the group
m_userDriver.createUserInGroup(user.getId(), usergroup.getId(), null);
// update the cache
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]" + group, CmsException.C_NO_GROUP);
}
// if an additional groupname is given and the group does not belong to
// Users, Administrators or Projectmanager add the user to this group
if (additionalGroup != null && !"".equals(additionalGroup)) {
addGroup = readGroup(additionalGroup);
if (addGroup != null && isWebgroup(addGroup)) {
//add this user to the group
m_userDriver.createUserInGroup(user.getId(), addGroup.getId(), null);
// update the cache
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]" + additionalGroup, CmsException.C_NO_GROUP);
}
}
} else {
throw new CmsException("[" + getClass().getName() + "]" + name, CmsException.C_NO_USER);
}
return newUser;
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_INVALID_PASSWORD);
}
}
/**
* Creates a backup of the published project.<p>
*
* @param context the current request context
* @param backupProject the project to be backuped
* @param tagId the version of the backup
* @param publishDate the date of publishing
* @throws CmsException if operation was not succesful
*/
public void backupProject(CmsRequestContext context, CmsProject backupProject, int tagId, long publishDate) throws CmsException {
m_backupDriver.writeBackupProject(backupProject, tagId, publishDate, context.currentUser());
}
/**
* Changes the lock of a resource.<p>
*
* @param context the current request context
* @param resourcename the name of the resource
* @throws CmsException if operation was not succesful
*/
public void changeLock(CmsRequestContext context, String resourcename) throws CmsException {
CmsResource resource = readFileHeader(context, resourcename);
CmsLock oldLock = getLock(context, resourcename);
CmsLock exclusiveLock = null;
if (oldLock.isNullLock()) {
throw new CmsLockException("Unable to steal lock on a unlocked resource", CmsLockException.C_RESOURCE_UNLOCKED);
}
// stealing a lock: checking permissions will throw an exception coz the
// resource is still locked for the other user. thus, the resource is unlocked
// before the permissions of the new user are checked. if the new user
// has insufficient permissions, the previous lock is restored.
// save the lock of the resource's exclusive locked sibling
exclusiveLock = m_lockManager.getExclusiveLockedSibling(this, context, resourcename);
// save the lock of the resource itself
oldLock = getLock(context, resourcename);
// remove the lock
m_lockManager.removeResource(this, context, resourcename, true);
try {
// check if the user has write access to the resource
m_permissionCache.clear();
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
} catch (CmsSecurityException e) {
// restore the lock of the exclusive locked sibling in case a lock gets stolen by
// a new user with insufficient permissions on the resource
m_lockManager.addResource(this, context, exclusiveLock.getResourceName(), exclusiveLock.getUserId(), exclusiveLock.getProjectId(), CmsLock.C_MODE_COMMON);
throw e;
}
if (resource.getState() != I_CmsConstants.C_STATE_UNCHANGED) {
// update the project flag of a modified resource as "modified inside the current project"
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), resource);
}
m_lockManager.addResource(this, context, resource.getRootPath(), context.currentUser().getId(), context.currentProject().getId(), CmsLock.C_MODE_COMMON);
clearResourceCache();
m_permissionCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Changes the project-id of a resource to the current project,
* for publishing the resource directly.<p>
*
* @param resourcename the name of the resource to change
* @param context the current request context
* @throws CmsException if something goes wrong
*/
public void changeLockedInProject(CmsRequestContext context, String resourcename) throws CmsException {
// include deleted resources, otherwise publishing of them will not work
List path = readPath(context, resourcename, true);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
// update the project flag of a modified resource as "modified inside the current project"
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), resource);
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Changes the user type of the user.<p>
* Only the administrator can change the type.
*
* @param context the current request context
* @param user the user to change
* @param userType the new usertype of the user
* @throws CmsException if something goes wrong
*/
public void changeUserType(CmsRequestContext context, CmsUser user, int userType) throws CmsException {
if (isAdmin(context)) {
// try to remove user from cache
clearUserCache(user);
m_userDriver.writeUserType(user.getId(), userType);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] changeUserType() " + user.getName(), CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Changes the user type of the user.<p>
* Only the administrator can change the type.
*
* @param context the current request context
* @param userId the id of the user to change
* @param userType the new usertype of the user
* @throws CmsException if something goes wrong
*/
public void changeUserType(CmsRequestContext context, CmsUUID userId, int userType) throws CmsException {
CmsUser theUser = m_userDriver.readUser(userId);
changeUserType(context, theUser, userType);
}
/**
* Changes the user type of the user.<p>
* Only the administrator can change the type.
*
* @param context the current request context
* @param username the name of the user to change
* @param userType the new usertype of the user
* @throws CmsException if something goes wrong
*/
public void changeUserType(CmsRequestContext context, String username, int userType) throws CmsException {
CmsUser theUser = null;
try {
// try to read the webuser
theUser = this.readWebUser(username);
} catch (CmsException e) {
// try to read the systemuser
if (e.getType() == CmsException.C_NO_USER) {
theUser = this.readUser(username);
} else {
throw e;
}
}
changeUserType(context, theUser, userType);
}
/**
* Performs a blocking permission check on a resource.<p>
* If the required permissions are not satisfied by the permissions the user has on the resource,
* an no access exception is thrown.
*
* @param context the current request context
* @param resource the resource on which permissions are required
* @param requiredPermissions the set of permissions required to access the resource
* @throws CmsException in case of any i/o error
* @throws CmsSecurityException if the required permissions are not satisfied
*/
public void checkPermissions(CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions) throws CmsException, CmsSecurityException {
if (!hasPermissions(context, resource, requiredPermissions, false)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] denied access to resource " + resource.getName() + ", required permissions are " + requiredPermissions.getPermissionString() + " (required one)", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Changes the state for this resource.<p>
* The user may change this, if he is admin of the resource.
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param filename the complete path to the resource
* @param state the new state of this resource
*
* @throws CmsException if the user has not the rights for this resource
*/
public void chstate(CmsRequestContext context, String filename, int state) throws CmsException {
CmsResource resource = null;
// read the resource to check the access
if (CmsResource.isFolder(filename)) {
resource = readFolder(context, filename);
} else {
resource = (CmsFile)readFileHeader(context, filename);
}
// check the access rights
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
// set the state of the resource
resource.setState(state);
// write-acces was granted - write the file.
if (CmsResource.isFolder(filename)) {
m_vfsDriver.writeFolder(context.currentProject(), (CmsFolder)resource, C_UPDATE_ALL, context.currentUser().getId());
// update the cache
//clearResourceCache(filename, context.currentProject(), context.currentUser());
clearResourceCache();
} else {
m_vfsDriver.writeFileHeader(context.currentProject(), (CmsFile)resource, C_UPDATE_ALL, context.currentUser().getId());
// update the cache
//clearResourceCache(filename, context.currentProject(), context.currentUser());
clearResourceCache();
}
}
/**
* Changes the resourcetype for this resource.<p>
*
* Only the resourcetype of a resource in an offline project can be changed. The state
* of the resource is set to CHANGED (1).
* If the content of this resource is not exisiting in the offline project already,
* it is read from the online project and written into the offline project.
* The user may change this, if he is admin of the resource. <br>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user is owner of the resource or is admin</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param filename the complete m_path to the resource
* @param newType the name of the new resourcetype for this resource
*
* @throws CmsException if operation was not succesful
*/
public void chtype(CmsRequestContext context, String filename, int newType) throws CmsException {
I_CmsResourceType type = getResourceType(newType);
// read the resource to check the access
CmsResource resource = readFileHeader(context, filename);
resource.setType(type.getResourceType());
resource.setLoaderId(type.getLoaderId());
writeFileHeader(context, (CmsFile)resource);
}
/**
* Clears the access control list cache when access control entries are changed.<p>
*/
protected void clearAccessControlListCache() {
m_accessControlListCache.clear();
m_resourceCache.clear();
m_resourceListCache.clear();
m_permissionCache.clear();
}
/**
* Clears all internal DB-Caches.<p>
*/
// TODO: should become protected, use event instead
public void clearcache() {
m_userCache.clear();
m_groupCache.clear();
m_userGroupsCache.clear();
m_projectCache.clear();
m_resourceCache.clear();
m_resourceListCache.clear();
m_propertyCache.clear();
m_accessControlListCache.clear();
m_permissionCache.clear();
}
/**
* Clears all the depending caches when a resource was changed.<p>
*/
protected void clearResourceCache() {
m_resourceCache.clear();
m_resourceListCache.clear();
}
/**
* Clears all the depending caches when a resource was changed.<p>
*
* @param context the current request context
* @param resourcename The name of the changed resource
*/
protected void clearResourceCache(CmsRequestContext context, String resourcename) {
m_resourceCache.remove(getCacheKey(null, context.currentProject(), resourcename));
m_resourceCache.remove(getCacheKey("file", context.currentProject(), resourcename));
m_resourceCache.remove(getCacheKey("path", context.currentProject(), resourcename));
m_resourceCache.remove(getCacheKey("parent", context.currentProject(), resourcename));
m_resourceListCache.clear();
}
/**
* Clears the user cache for the given user.<p>
* @param user the user
*/
protected void clearUserCache(CmsUser user) {
removeUserFromCache(user);
m_resourceListCache.clear();
}
/**
* @see org.opencms.main.I_CmsEventListener#cmsEvent(org.opencms.main.CmsEvent)
*/
public void cmsEvent(CmsEvent event) {
if (org.opencms.main.OpenCms.getLog(this).isDebugEnabled()) {
org.opencms.main.OpenCms.getLog(this).debug("handling event: " + event.getType());
}
switch (event.getType()) {
case I_CmsEventListener.EVENT_PUBLISH_PROJECT:
case I_CmsEventListener.EVENT_CLEAR_CACHES:
this.clearcache();
break;
default:
break;
}
}
/**
* Copies the access control entries of a given resource to another resorce.<p>
*
* Already existing access control entries of this resource are removed.
* Access is granted, if:
* <ul>
* <li>the current user has control permission on the destination resource
* </ul>
*
* @param context the current request context
* @param source the resource which access control entries are copied
* @param dest the resource to which the access control entries are applied
* @throws CmsException if something goes wrong
*/
public void copyAccessControlEntries(CmsRequestContext context, CmsResource source, CmsResource dest) throws CmsException {
checkPermissions(context, dest, I_CmsConstants.C_CONTROL_ACCESS);
ListIterator acEntries = m_userDriver.readAccessControlEntries(context.currentProject(), source.getResourceId(), false).listIterator();
m_userDriver.removeAccessControlEntries(context.currentProject(), dest.getResourceId());
clearAccessControlListCache();
while (acEntries.hasNext()) {
writeAccessControlEntry(context, dest, (CmsAccessControlEntry)acEntries.next());
}
touchResource(context, dest, System.currentTimeMillis(), context.currentUser().getId());
}
/**
* Copies a file in the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the sourceresource</li>
* <li>the user can create the destinationresource</li>
* <li>the destinationresource doesn't exist</li>
* </ul>
*
* @param context the current request context
* @param source the complete m_path of the sourcefile
* @param destination the complete m_path to the destination
* @param lockCopy flag to lock the copied resource
* @param copyAsLink force the copy mode to link
* @param copyMode mode of the copy operation, described how to handle linked resourced during copy.
* Possible values are:
* <ul>
* <li>C_COPY_AS_NEW</li>
* <li>C_COPY_AS_SIBLING</li>
* <li>C_COPY_PRESERVE_SIBLING</li>
* </ul>
* @throws CmsException if operation was not succesful
*/
public void copyFile(CmsRequestContext context, String source, String destination, boolean lockCopy, boolean copyAsLink, int copyMode) throws CmsException {
String destinationFileName = null;
String destinationFolderName = null;
CmsResource newResource = null;
List properties = null;
if (CmsResource.isFolder(destination)) {
copyFolder(context, source, destination, lockCopy, false);
return;
}
// validate the destination path/filename
validFilename(destination.replace('/', 'a'));
// extract the destination folder and filename
destinationFolderName = destination.substring(0, destination.lastIndexOf("/") + 1);
destinationFileName = destination.substring(destination.lastIndexOf("/") + 1, destination.length());
// read the source file and destination parent folder
CmsFile sourceFile = readFile(context, source, false);
CmsFolder destinationFolder = readFolder(context, destinationFolderName);
// check the link mode to see if this resource has to be copied as a link.
// only check this if the override flag "copyAsLink" is not set.
if (!copyAsLink) {
// if we have the copy mode "copy as link, set the override flag to true
if (copyMode == I_CmsConstants.C_COPY_AS_SIBLING) {
copyAsLink = true;
}
// if the mode is "preservre links", we have to check the link counter
if (copyMode == I_CmsConstants.C_COPY_PRESERVE_SIBLING) {
if (sourceFile.getLinkCount() > 1) {
copyAsLink = true;
}
}
}
// checks, if the type is valid, i.e. the user can copy files of this type
// we can't utilize the access guard to do this, since it needs a resource to check
if (!isAdmin(context) && (sourceFile.getType() == CmsResourceTypeXMLTemplate.C_RESOURCE_TYPE_ID || sourceFile.getType() == CmsResourceTypeJsp.C_RESOURCE_TYPE_ID)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] copyFile() " + source, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
// check if the user has read access to the source file and write access to the destination folder
checkPermissions(context, sourceFile, I_CmsConstants.C_READ_ACCESS);
checkPermissions(context, destinationFolder, I_CmsConstants.C_WRITE_ACCESS);
// read the source properties
properties = readPropertyObjects(context, source, null, false);
if (copyAsLink) {
// create a copy of the source file in the destination parent folder
newResource = createSibling(context, destination, source, properties, false);
} else {
// create a new resource in the destination folder
// check the resource flags
int flags = sourceFile.getFlags();
if (sourceFile.isLabeled()) {
// reset "labeled" link flag for new resource
flags &= ~I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
}
// create the file
newResource = m_vfsDriver.createFile(context.currentUser(), context.currentProject(), destinationFileName, flags, destinationFolder, sourceFile.getContents(), getResourceType(sourceFile.getType()));
newResource.setFullResourceName(destination);
// copy the properties
m_vfsDriver.writePropertyObjects(context.currentProject(), newResource, properties);
m_propertyCache.clear();
// copy the access control entries
ListIterator aceList = m_userDriver.readAccessControlEntries(context.currentProject(), sourceFile.getResourceId(), false).listIterator();
while (aceList.hasNext()) {
CmsAccessControlEntry ace = (CmsAccessControlEntry)aceList.next();
m_userDriver.createAccessControlEntry(context.currentProject(), newResource.getResourceId(), ace.getPrincipal(), ace.getPermissions().getAllowedPermissions(), ace.getPermissions().getDeniedPermissions(), ace.getFlags());
}
m_vfsDriver.writeResourceState(context.currentProject(), newResource, C_UPDATE_ALL);
touch(context, destination, sourceFile.getDateLastModified(), sourceFile.getUserLastModified());
if (lockCopy) {
lockResource(context, destination);
}
}
clearAccessControlListCache();
clearResourceCache();
List modifiedResources = (List)new ArrayList();
modifiedResources.add(sourceFile);
modifiedResources.add(newResource);
modifiedResources.add(destinationFolder);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_COPIED, Collections.singletonMap("resources", modifiedResources)));
}
/**
* Copies a folder in the Cms. <p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the sourceresource</li>
* <li>the user can create the destinationresource</li>
* <li>the destinationresource doesn't exist</li>
* </ul>
*
* @param context the current request context
* @param source the complete m_path of the sourcefolder
* @param destination the complete m_path to the destination
* @param lockCopy flag to lock the copied folder
* @param preserveTimestamps true if the timestamps and users of the folder should be kept
* @throws CmsException if operation was not succesful.
*/
public void copyFolder(CmsRequestContext context, String source, String destination, boolean lockCopy, boolean preserveTimestamps) throws CmsException {
long dateLastModified = 0;
long dateCreated = 0;
CmsUUID userLastModified = null;
CmsUUID userCreated = null;
CmsResource newResource = null;
String destinationFoldername = null;
String destinationResourceName = null;
// checks, if the destinateion is valid, if not it throws a exception
validFilename(destination.replace('/', 'a'));
destinationFoldername = destination.substring(0, destination.substring(0, destination.length() - 1).lastIndexOf("/") + 1);
destinationResourceName = destination.substring(destinationFoldername.length());
if (CmsResource.isFolder(destinationResourceName)) {
destinationResourceName = destinationResourceName.substring(0, destinationResourceName.length() - 1);
}
CmsFolder destinationFolder = readFolder(context, destinationFoldername);
CmsFolder sourceFolder = readFolder(context, source);
// check if the user has write access to the destination folder (checking read access to the source is done implicitly by read folder)
checkPermissions(context, destinationFolder, I_CmsConstants.C_WRITE_ACCESS);
// set user and creation timestamps
if (preserveTimestamps) {
dateLastModified = sourceFolder.getDateLastModified();
dateCreated = sourceFolder.getDateCreated();
userLastModified = sourceFolder.getUserLastModified();
userCreated = sourceFolder.getUserCreated();
} else {
dateLastModified = System.currentTimeMillis();
dateCreated = System.currentTimeMillis();
userLastModified = context.currentUser().getId();
userCreated = context.currentUser().getId();
}
// create a copy of the folder
newResource = m_vfsDriver.createFolder(context.currentProject(), destinationFolder.getStructureId(), CmsUUID.getNullUUID(), destinationResourceName, sourceFolder.getFlags(), dateLastModified, userLastModified, dateCreated, userCreated);
newResource.setFullResourceName(destination);
clearResourceCache();
// copy the properties
List properties = readPropertyObjects(context, source, null, false);
m_vfsDriver.writePropertyObjects(context.currentProject(), newResource, properties);
m_propertyCache.clear();
if (preserveTimestamps) {
touch(context, destination, dateLastModified, userLastModified);
}
// copy the access control entries of this resource
ListIterator aceList = getAccessControlEntries(context, sourceFolder, false).listIterator();
while (aceList.hasNext()) {
CmsAccessControlEntry ace = (CmsAccessControlEntry)aceList.next();
m_userDriver.createAccessControlEntry(context.currentProject(), newResource.getResourceId(), ace.getPrincipal(), ace.getPermissions().getAllowedPermissions(), ace.getPermissions().getDeniedPermissions(), ace.getFlags());
}
if (lockCopy) {
lockResource(context, destination);
}
clearAccessControlListCache();
m_resourceListCache.clear();
List modifiedResources = (List)new ArrayList();
modifiedResources.add(sourceFolder);
modifiedResources.add(newResource);
modifiedResources.add(destinationFolder);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_COPIED, Collections.singletonMap("resources", modifiedResources)));
}
/**
* Copies a resource from the online project to a new, specified project.<p>
*
* Copying a resource will copy the file header or folder into the specified
* offline project and set its state to UNCHANGED.
* Access is granted, if:
* <ul>
* <li>the user is the owner of the project</li>
* </ul>
*
* @param context the current request context
* @param resource the name of the resource
* @throws CmsException if operation was not succesful
*/
// TODO: change checking access
public void copyResourceToProject(CmsRequestContext context, String resource) throws CmsException {
// is the current project the onlineproject?
// and is the current user the owner of the project?
// and is the current project state UNLOCKED?
if ((!context.currentProject().isOnlineProject()) && (isManagerOfProject(context)) && (context.currentProject().getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED)) {
// is offlineproject and is owner
// try to read the resource from the offline project, include deleted
CmsResource offlineRes = null;
try {
clearResourceCache();
// must include files marked as deleted for publishing deleted resources
//offlineRes = readFileHeaderInProject(context, context.currentProject().getId(), resource, true);
offlineRes = readFileHeader(context, resource, true);
if (!isInsideCurrentProject(context, offlineRes)) {
offlineRes = null;
}
} catch (CmsException exc) {
// if the resource does not exist in the offlineProject - it's ok
}
// create the projectresource only if the resource is not in the current project
if ((offlineRes == null) || (offlineRes.getProjectLastModified() != context.currentProject().getId())) {
// check if there are already any subfolders of this resource
if (CmsResource.isFolder(resource)) {
List projectResources = m_projectDriver.readProjectResources(context.currentProject());
for (int i = 0; i < projectResources.size(); i++) {
String resname = (String)projectResources.get(i);
if (resname.startsWith(resource)) {
// delete the existing project resource first
m_projectDriver.deleteProjectResource(context.currentProject().getId(), resname);
}
}
}
try {
m_projectDriver.createProjectResource(context.currentProject().getId(), resource, null);
} catch (CmsException exc) {
// if the subfolder exists already - all is ok
} finally {
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROJECT_MODIFIED, Collections.singletonMap("project", context.currentProject())));
}
}
} else {
// no changes on the onlineproject!
throw new CmsSecurityException("[" + this.getClass().getName() + "] " + context.currentProject().getName(), CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Moves a resource to the lost and found folder.<p>
*
* @param context the current request context
* @param resourcename the complete path of the sourcefile.
* @param copyResource true, if the resource should be copied to its destination inside the lost+found folder
* @return location of the moved resource
* @throws CmsException if the user has not the rights to move this resource,
* or if the file couldn't be moved.
*/
public String copyToLostAndFound(CmsRequestContext context, String resourcename, boolean copyResource) throws CmsException {
String siteRoot = context.getSiteRoot();
Stack storage = new Stack();
context.setSiteRoot("/");
String destination = I_CmsConstants.C_VFS_LOST_AND_FOUND + resourcename;
// create the require folders if nescessary
String des = destination;
// collect all folders...
try {
while (des.indexOf("/") == 0) {
des = des.substring(0, des.lastIndexOf("/"));
storage.push(des.concat("/"));
}
// ...now create them....
while (storage.size() != 0) {
des = (String)storage.pop();
try {
readFolder(context, des);
} catch (Exception e1) {
// the folder is not existing, so create it
createFolder(context, des, Collections.EMPTY_LIST);
}
}
// check if this resource name does already exist
// if so add a psotfix to the name
des = destination;
int postfix = 1;
boolean found = true;
while (found) {
try {
// try to read the file.....
found = true;
readFileHeader(context, des);
// ....it's there, so add a postfix and try again
String path = destination.substring(0, destination.lastIndexOf("/") + 1);
String filename = destination.substring(destination.lastIndexOf("/") + 1, destination.length());
des = path;
if (filename.lastIndexOf(".") > 0) {
des += filename.substring(0, filename.lastIndexOf("."));
} else {
des += filename;
}
des += "_" + postfix;
if (filename.lastIndexOf(".") > 0) {
des += filename.substring(filename.lastIndexOf("."), filename.length());
}
postfix++;
} catch (CmsException e3) {
// the file does not exist, so we can use this filename
found = false;
}
}
destination = des;
if (copyResource) {
// move the existing resource to the lost and foud folder
moveResource(context, resourcename, destination);
}
} catch (CmsException e2) {
throw e2;
} finally {
// set the site root to the old value again
context.setSiteRoot(siteRoot);
}
return destination;
}
/**
* Counts the locked resources in this project.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param context the current request context
* @param id the id of the project
* @return the amount of locked resources in this project.
* @throws CmsException if something goes wrong
*/
public int countLockedResources(CmsRequestContext context, int id) throws CmsException {
// read the project.
CmsProject project = readProject(id);
// check the security
if (isAdmin(context) || isManagerOfProject(context) || (project.getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED)) {
// count locks
return m_lockManager.countExclusiveLocksInProject(project);
} else if (!isAdmin(context) && !isManagerOfProject(context)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] countLockedResources()", CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] countLockedResources()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Counts the locked resources in a given folder.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param context the current request context
* @param foldername the folder to search in
* @return the amount of locked resources in this project
* @throws CmsException if something goes wrong
*/
public int countLockedResources(CmsRequestContext context, String foldername) throws CmsException {
// check the security
if (isAdmin(context) || isManagerOfProject(context) || (context.currentProject().getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED)) {
// count locks
return m_lockManager.countExclusiveLocksInFolder(foldername);
} else if (!isAdmin(context) && !isManagerOfProject(context)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] countLockedResources()", CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] countLockedResources()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Creates a project for the direct publish.<p>
*
* Only the users which are in the admin or projectleader-group of the current project are granted.
*
* @param context the current context (user/project)
* @param name The name of the project to read
* @param description The description for the new project
* @param groupname the group to be set
* @param managergroupname the managergroup to be set
* @param projecttype the type of the project
* @return the direct publish project
* @throws CmsException if something goes wrong
*/
/*
public CmsProject createDirectPublishProject(CmsRequestContext context, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException {
if (isAdmin(context) || isManagerOfProject(context)) {
if (I_CmsConstants.C_PROJECT_ONLINE.equals(name)) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// read the needed groups from the cms
CmsGroup group = readGroup(context, groupname);
CmsGroup managergroup = readGroup(context, managergroupname);
return m_projectDriver.createProject(context.currentUser(), group, managergroup, noTask, name, description, I_CmsConstants.C_PROJECT_STATE_UNLOCKED, projecttype, null);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createDirectPublishProject()", CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
}
}
*/
/**
* Creates a new file with the given content and resourcetype.<p>
*
* Files can only be created in an offline project, the state of the new file
* is set to NEW (2). <br>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the folder-resource is not locked by another user</li>
* <li>the file doesn't exist</li>
* </ul>
*
* @param context the current request context
* @param newFileName the name of the new file
* @param contents the contents of the new file
* @param type the name of the resourcetype of the new file
* @param propertyinfos a Hashtable of propertyinfos, that should be set for this folder.
* The keys for this Hashtable are the names for propertydefinitions, the values are
* the values for the propertyinfos.
* @return the created file.
* @throws CmsException if operation was not succesful.
*/
public CmsFile createFile(CmsRequestContext context, String newFileName, byte[] contents, String type, List propertyinfos) throws CmsException {
// extract folder information
String folderName = newFileName.substring(0, newFileName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR, newFileName.length()) + 1);
String resourceName = newFileName.substring(folderName.length(), newFileName.length());
// checks, if the filename is valid, if not it throws a exception
validFilename(resourceName);
// checks, if the type is valid, i.e. the user can create files of this type
// we can't utilize the access guard to do this, since it needs a resource to check
if (!isAdmin(context) && (CmsResourceTypeXMLTemplate.C_RESOURCE_TYPE_NAME.equals(type) || CmsResourceTypeJsp.C_RESOURCE_TYPE_NAME.equals(type))) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createFile() " + resourceName, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
CmsFolder parentFolder = readFolder(context, folderName);
// check if the user has write access to the destination folder
checkPermissions(context, parentFolder, I_CmsConstants.C_WRITE_ACCESS);
// create and return the file.
CmsFile newFile = m_vfsDriver.createFile(context.currentUser(), context.currentProject(), resourceName, 0, parentFolder, contents, getResourceType(type));
newFile.setFullResourceName(newFileName);
// write the metainfos
//writeProperties(context, newFileName, propertyinfos);
m_vfsDriver.writePropertyObjects(context.currentProject(), newFile, propertyinfos);
m_propertyCache.clear();
contents = null;
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_CREATED, Collections.singletonMap("resource", newFile)));
return newFile;
}
/**
* Creates a new folder.<p>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is not locked by another user</li>
* </ul>
*
* @param context the current request context
* @param newFolderName the name of the new folder (No pathinformation allowed).
* @param propertyinfos a Hashtable of propertyinfos, that should be set for this folder.
* The keys for this Hashtable are the names for propertydefinitions, the values are
* the values for the propertyinfos.
* @return the created folder.
* @throws CmsException for missing propertyinfos, for worng propertydefs
* or if the filename is not valid. The CmsException will also be thrown, if the
* user has not the rights for this resource.
*/
public CmsFolder createFolder(CmsRequestContext context, String newFolderName, List propertyinfos) throws CmsException {
// append I_CmsConstants.C_FOLDER_SEPARATOR if required
if (!newFolderName.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
newFolderName += I_CmsConstants.C_FOLDER_SEPARATOR;
}
// extract folder information
String folderName = newFolderName.substring(0, newFolderName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR, newFolderName.length() - 2) + 1);
String resourceName = newFolderName.substring(folderName.length(), newFolderName.length() - 1);
// checks, if the filename is valid, if not it throws a exception
validFilename(resourceName);
CmsFolder cmsFolder = readFolder(context, folderName);
// check if the user has write access to the destination folder
checkPermissions(context, cmsFolder, I_CmsConstants.C_WRITE_ACCESS);
// create the folder.
CmsFolder newFolder = m_vfsDriver.createFolder(context.currentProject(), cmsFolder.getStructureId(), CmsUUID.getNullUUID(), resourceName, 0, 0, context.currentUser().getId(), 0, context.currentUser().getId());
newFolder.setFullResourceName(newFolderName);
// write metainfos for the folder
m_vfsDriver.writePropertyObjects(context.currentProject(), newFolder, propertyinfos);
m_propertyCache.clear();
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_CREATED, Collections.singletonMap("resource", newFolder)));
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROJECT_MODIFIED, Collections.singletonMap("project", context.currentProject())));
// return the folder
return newFolder;
}
/**
* Creates a new sibling of the target resource.<p>
*
* @param context the context
* @param linkName the name of the link
* @param targetName the name of the target
* @param linkProperties the properties to attach via the the link
* @param lockResource true, if the new created link should be initially locked
* @return the new resource
* @throws CmsException if something goes wrong
*/
public CmsResource createSibling(CmsRequestContext context, String linkName, String targetName, List linkProperties, boolean lockResource) throws CmsException {
CmsResource targetResource = null;
CmsResource linkResource = null;
String parentFolderName = null;
CmsFolder parentFolder = null;
String resourceName = null;
parentFolderName = linkName.substring(0, linkName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR) + 1);
resourceName = linkName.substring(linkName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR) + 1, linkName.length());
// read the target resource
targetResource = this.readFileHeader(context, targetName);
if (targetResource.isFolder()) {
throw new CmsException("Setting links on folders is not supported");
}
// read the parent folder
parentFolder = this.readFolder(context, parentFolderName, false);
// for the parent folder is write access required
checkPermissions(context, parentFolder, I_CmsConstants.C_WRITE_ACCESS);
// construct a dummy that is written to the db
linkResource = new CmsResource(new CmsUUID(), targetResource.getResourceId(), parentFolder.getStructureId(), CmsUUID.getNullUUID(), resourceName, targetResource.getType(), targetResource.getFlags(), context.currentProject().getId(), org.opencms.main.I_CmsConstants.C_STATE_NEW, targetResource.getLoaderId(), System.currentTimeMillis(), context.currentUser().getId(), System.currentTimeMillis(), context.currentUser().getId(), 0, targetResource.getLinkCount() + 1);
// check if the resource has to be labeled now
if (labelResource(context, targetResource, linkName, 1)) {
int flags = linkResource.getFlags();
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
linkResource.setFlags(flags);
}
// setting the full resource name twice here looks crude but is essential!
linkResource.setFullResourceName(linkName);
linkResource = m_vfsDriver.createSibling(context.currentProject(), linkResource, context.currentUser().getId(), parentFolder.getStructureId(), resourceName);
linkResource.setFullResourceName(linkName);
// mark the new sibling as modified in the current project
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), linkResource);
if (linkProperties == null) {
// "empty" properties are represented by an empty property map
linkProperties = Collections.EMPTY_LIST;
}
// write its properties
CmsProperty.setAutoCreatePropertyDefinitions(linkProperties, true);
m_vfsDriver.writePropertyObjects(context.currentProject(), linkResource, linkProperties);
// if the source
clearResourceCache();
m_propertyCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", parentFolder)));
if (lockResource) {
// lock the resource
lockResource(context, linkName);
}
return linkResource;
}
/**
* Add a new group to the Cms.<p>
*
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param id the id of the new group
* @param name the name of the new group
* @param description the description for the new group
* @param flags the flags for the new group
* @param parent the name of the parent group (or null)
* @return new created group
* @throws CmsException if operation was not successfull.
*/
public CmsGroup createGroup(CmsRequestContext context, CmsUUID id, String name, String description, int flags, String parent) throws CmsException {
// Check the security
if (isAdmin(context)) {
name = name.trim();
validFilename(name);
// check the lenght of the groupname
if (name.length() > 1) {
return m_userDriver.createGroup(id, name, description, flags, parent, null);
} else {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createGroup() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Add a new group to the Cms.<p>
*
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param name the name of the new group
* @param description the description for the new group
* @param flags the flags for the new group
* @param parent the name of the parent group (or null)
* @return new created group
* @throws CmsException if operation was not successfull.
*/
public CmsGroup createGroup(CmsRequestContext context, String name, String description, int flags, String parent) throws CmsException {
return createGroup(context, new CmsUUID(), name, description, flags, parent);
}
/**
* Add a new group to the Cms.<p>
*
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param id the id of the new group
* @param name the name of the new group
* @param description the description for the new group
* @param flags the flags for the new group
* @param parent the name of the parent group (or null)
* @return new created group
* @throws CmsException if operation was not successfull
*/
public CmsGroup createGroup(CmsRequestContext context, String id, String name, String description, int flags, String parent) throws CmsException {
return createGroup(context, new CmsUUID(id), name, description, flags, parent);
}
/**
* Creates a new project for task handling.<p>
*
* @param context the current request context
* @param projectName name of the project
* @param roleName usergroup for the project
* @param timeout time when the Project must finished
* @param priority priority for the Project
* @return The new task project
*
* @throws CmsException if something goes wrong
*/
public CmsTask createProject(CmsRequestContext context, String projectName, String roleName, long timeout, int priority) throws CmsException {
CmsGroup role = null;
// read the role
if (roleName != null && !roleName.equals("")) {
role = readGroup(roleName);
}
// create the timestamp
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
return m_workflowDriver.createTask(0, 0, 1, // standart project type,
context.currentUser().getId(), context.currentUser().getId(), role.getId(), projectName, now, timestamp, priority);
}
/**
* Creates a project.<p>
*
* Only the users which are in the admin or projectmanager groups are granted.<p>
*
* @param context the current request context
* @param name the name of the project to create
* @param description the description of the project
* @param groupname the project user group to be set
* @param managergroupname the project manager group to be set
* @param projecttype type the type of the project
* @return the created project
* @throws CmsException if something goes wrong
*/
public CmsProject createProject(CmsRequestContext context, String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException {
if (isAdmin(context) || isProjectManager(context)) {
if (I_CmsConstants.C_PROJECT_ONLINE.equals(name)) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// read the needed groups from the cms
CmsGroup group = readGroup(groupname);
CmsGroup managergroup = readGroup(managergroupname);
// create a new task for the project
CmsTask task = createProject(context, name, group.getName(), System.currentTimeMillis(), I_CmsConstants.C_TASK_PRIORITY_NORMAL);
return m_projectDriver.createProject(context.currentUser(), group, managergroup, task, name, description, I_CmsConstants.C_PROJECT_STATE_UNLOCKED, projecttype, null);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createProject()", CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
}
}
/**
* Creates the propertydefinition for the resource type.<p>
*
* Only the admin can do this.
*
* @param context the current request context
* @param name the name of the propertydefinition to overwrite
* @param resourcetype the name of the resource-type for the propertydefinition
* @return the created propertydefinition
* @throws CmsException if something goes wrong.
*/
public CmsPropertydefinition createPropertydefinition(CmsRequestContext context, String name, int resourcetype) throws CmsException {
CmsPropertydefinition propertyDefinition = null;
if (isAdmin(context)) {
name = name.trim();
validFilename(name);
try {
propertyDefinition = m_vfsDriver.readPropertyDefinition(name, context.currentProject().getId(), resourcetype);
} catch (CmsException e) {
propertyDefinition = m_vfsDriver.createPropertyDefinition(name, context.currentProject().getId(), resourcetype);
}
try {
m_vfsDriver.readPropertyDefinition(name, I_CmsConstants.C_PROJECT_ONLINE_ID, resourcetype);
} catch (CmsException e) {
m_vfsDriver.createPropertyDefinition(name, I_CmsConstants.C_PROJECT_ONLINE_ID, resourcetype);
}
try {
m_backupDriver.readBackupPropertyDefinition(name, resourcetype);
} catch (CmsException e) {
m_backupDriver.createBackupPropertyDefinition(name, resourcetype);
}
//propertyDefinition = m_vfsDriver.createPropertyDefinition(name, context.currentProject().getId(), resourcetype));
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createPropertydefinition() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
return propertyDefinition;
}
/**
* Creates a new task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param agentName username who will edit the task
* @param roleName usergroupname for the task
* @param taskname name of the task
* @param timeout time when the task must finished
* @param priority Id for the priority
* @return A new Task Object
* @throws CmsException if something goes wrong
*/
public CmsTask createTask(CmsRequestContext context, String agentName, String roleName, String taskname, long timeout, int priority) throws CmsException {
CmsGroup role = m_userDriver.readGroup(roleName);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
CmsUUID agentId = CmsUUID.getNullUUID();
validTaskname(taskname); // check for valid Filename
try {
agentId = readUser(agentName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER).getId();
} catch (Exception e) {
// ignore that this user doesn't exist and create a task for the role
}
return m_workflowDriver.createTask(context.currentProject().getTaskId(), context.currentProject().getTaskId(), 1, // standart Task Type
context.currentUser().getId(), agentId, role.getId(), taskname, now, timestamp, priority);
}
/**
* Creates a new task.<p>
*
* All users are granted.
*
* @param currentUser the current user
* @param projectid the current project id
* @param agentName user who will edit the task
* @param roleName usergroup for the task
* @param taskName name of the task
* @param taskType type of the task
* @param taskComment description of the task
* @param timeout time when the task must finished
* @param priority Id for the priority
* @return a new task object
* @throws CmsException if something goes wrong.
*/
public CmsTask createTask(CmsUser currentUser, int projectid, String agentName, String roleName, String taskName, String taskComment, int taskType, long timeout, int priority) throws CmsException {
CmsUser agent = readUser(agentName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
CmsGroup role = m_userDriver.readGroup(roleName);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
validTaskname(taskName); // check for valid Filename
CmsTask task = m_workflowDriver.createTask(projectid, projectid, taskType, currentUser.getId(), agent.getId(), role.getId(), taskName, now, timestamp, priority);
if (taskComment != null && !taskComment.equals("")) {
m_workflowDriver.writeTaskLog(task.getId(), currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), taskComment, I_CmsConstants.C_TASKLOG_USER);
}
return task;
}
/**
* Creates the project for the temporary files.<p>
*
* Only the users which are in the admin or projectleader-group are granted.
*
* @param context the current request context
* @return the new tempfile project
* @throws CmsException if something goes wrong
*/
public CmsProject createTempfileProject(CmsRequestContext context) throws CmsException {
if (isAdmin(context)) {
// read the needed groups from the cms
CmsGroup group = readGroup(OpenCms.getDefaultUsers().getGroupUsers());
CmsGroup managergroup = readGroup(OpenCms.getDefaultUsers().getGroupAdministrators());
// create a new task for the project
CmsTask task = createProject(context, CmsWorkplaceManager.C_TEMP_FILE_PROJECT_NAME, group.getName(), System.currentTimeMillis(), I_CmsConstants.C_TASK_PRIORITY_NORMAL);
CmsProject tempProject = m_projectDriver.createProject(context.currentUser(), group, managergroup, task, CmsWorkplaceManager.C_TEMP_FILE_PROJECT_NAME, CmsWorkplaceManager.C_TEMP_FILE_PROJECT_DESCRIPTION, I_CmsConstants.C_PROJECT_STATE_INVISIBLE, I_CmsConstants.C_PROJECT_STATE_INVISIBLE, null);
m_projectDriver.createProjectResource(tempProject.getId(), "/", null);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROJECT_MODIFIED, Collections.singletonMap("project", tempProject)));
return tempProject;
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] createTempfileProject() ", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Creates a new sibling of the target resource.<p>
*
* @param context the context
* @param linkName the name of the link
* @param targetName the name of the target
* @param linkProperties the properties to attach via the the link
* @param lockResource true, if the new created link should be initially locked
* @return the new resource
* @throws CmsException if something goes wrong
*/
public CmsResource createVfsLink(CmsRequestContext context, String linkName, String targetName, List linkProperties, boolean lockResource) throws CmsException {
CmsResource targetResource = null;
CmsResource linkResource = null;
String parentFolderName = null;
CmsFolder parentFolder = null;
String resourceName = null;
parentFolderName = linkName.substring(0, linkName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR) + 1);
resourceName = linkName.substring(linkName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR) + 1, linkName.length());
// read the target resource
targetResource = this.readFileHeader(context, targetName);
if (targetResource.isFolder()) {
throw new CmsException("Setting links on folders is not supported");
}
// read the parent folder
parentFolder = this.readFolder(context, parentFolderName, false);
// for the parent folder is write access required
checkPermissions(context, parentFolder, I_CmsConstants.C_WRITE_ACCESS);
// construct a dummy that is written to the db
linkResource = new CmsResource(new CmsUUID(), targetResource.getResourceId(), parentFolder.getStructureId(), CmsUUID.getNullUUID(), resourceName, targetResource.getType(), targetResource.getFlags(), context.currentProject().getId(), org.opencms.main.I_CmsConstants.C_STATE_NEW, targetResource.getLoaderId(), System.currentTimeMillis(), context.currentUser().getId(), System.currentTimeMillis(), context.currentUser().getId(), 0, targetResource.getLinkCount() + 1);
// check if the resource has to be labeled now
if (labelResource(context, targetResource, linkName, 1)) {
int flags = linkResource.getFlags();
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
linkResource.setFlags(flags);
}
// setting the full resource name twice here looks crude but is essential!
linkResource.setFullResourceName(linkName);
linkResource = m_vfsDriver.createSibling(context.currentProject(), linkResource, context.currentUser().getId(), parentFolder.getStructureId(), resourceName);
linkResource.setFullResourceName(linkName);
// mark the new sibling as modified in the current project
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), linkResource);
if (linkProperties == null) {
// "empty" properties are represented by an empty property map
linkProperties = Collections.EMPTY_LIST;
}
// write its properties
m_vfsDriver.writePropertyObjects(context.currentProject(), linkResource, linkProperties);
// if the source
clearResourceCache();
m_propertyCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", parentFolder)));
if (lockResource) {
// lock the resource
lockResource(context, linkName);
}
return linkResource;
}
/**
* Marks all access control entries belonging to a resource as deleted.<p>
*
* Access is granted, if:
* <ul>
* <li>the current user has write permission on the resource
* </ul>
*
* @param context the current request context
* @param resource the resource
* @throws CmsException if something goes wrong
*/
private void deleteAllAccessControlEntries(CmsRequestContext context, CmsResource resource) throws CmsException {
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
m_userDriver.deleteAccessControlEntries(context.currentProject(), resource.getResourceId());
// not here
// touchResource(context, resource, System.currentTimeMillis());
clearAccessControlListCache();
}
/**
* Deletes all propertyinformation for a file or folder.<p>
*
* Only the user is granted, who has the right to write the resource.
*
* @param context the current request context
* @param resourceName the name of the resource of which the propertyinformations have to be deleted.
* @throws CmsException if operation was not succesful
*/
public void deleteAllProperties(CmsRequestContext context, String resourceName) throws CmsException {
CmsResource resource = null;
try {
// read the resource
resource = readFileHeader(context, resourceName);
// check the security
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
//delete all Properties
m_vfsDriver.deleteProperties(context.currentProject().getId(), resource);
} finally {
// clear the driver manager cache
m_propertyCache.clear();
// fire an event that all properties of a resource have been deleted
OpenCms.fireCmsEvent(new CmsEvent(
new CmsObject(),
I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED,
Collections.singletonMap("resource", resource)));
}
}
/**
* Deletes all backup versions of a single resource.<p>
*
* @param res the resource to delete all backups from
* @throws CmsException if operation was not succesful
*/
public void deleteBackup(CmsResource res) throws CmsException {
// we need a valid CmsBackupResource, so get all backup file headers of the
// requested resource
List backupFileHeaders=m_backupDriver.readBackupFileHeaders(res.getResourceId());
// check if we have some results
if (backupFileHeaders.size()>0) {
// get the first backup resource
CmsBackupResource backupResource=(CmsBackupResource)backupFileHeaders.get(0);
// create a timestamp slightly in the future
long timestamp=System.currentTimeMillis()+100000;
// get the maximum tag id and add ne to include the current publish process as well
int maxTag = m_backupDriver.readBackupProjectTag(timestamp)+1;
int resVersions = m_backupDriver.readBackupMaxVersion(res.getResourceId());
// delete the backups
m_backupDriver.deleteBackup(backupResource, maxTag, resVersions);
}
}
/**
* Deletes the versions from the backup tables that are older then the given timestamp and/or number of remaining versions.<p>
*
* The number of verions always wins, i.e. if the given timestamp would delete more versions than given in the
* versions parameter, the timestamp will be ignored.
* Deletion will delete file header, content and properties.
*
* @param context the current request context
* @param timestamp the max age of backup resources
* @param versions the number of remaining backup versions for each resource
* @param report the report for output logging
* @throws CmsException if operation was not succesful
*/
public void deleteBackups(CmsRequestContext context, long timestamp, int versions, I_CmsReport report) throws CmsException {
if (isAdmin(context)) {
// get all resources from the backup table
// do only get one version per resource
List allBackupFiles = m_backupDriver.readBackupFileHeaders();
int counter = 1;
int size = allBackupFiles.size();
// get the tagId of the oldest Backupproject which will be kept in the database
int maxTag = m_backupDriver.readBackupProjectTag(timestamp);
Iterator i = allBackupFiles.iterator();
while (i.hasNext()) {
// now check get a single backup resource
CmsBackupResource res = (CmsBackupResource)i.next();
// get the full resource path if not present
if (!res.hasFullResourceName()) {
res.setFullResourceName(readPath(context, res, true));
}
report.print("( " + counter + " / " + size + " ) ", I_CmsReport.C_FORMAT_NOTE);
report.print(report.key("report.history.checking"), I_CmsReport.C_FORMAT_NOTE);
report.print(res.getRootPath() + " ");
// now delete all versions of this resource that have more than the maximun number
// of allowed versions and which are older then the maximum backup date
int resVersions = m_backupDriver.readBackupMaxVersion(res.getResourceId());
int versionsToDelete = resVersions - versions;
// now we know which backup versions must be deleted, so remove them now
if (versionsToDelete > 0) {
report.print(report.key("report.history.deleting") + report.key("report.dots"));
m_backupDriver.deleteBackup(res, maxTag, versionsToDelete);
} else {
report.print(report.key("report.history.nothing") + report.key("report.dots"));
}
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
counter++;
//TODO: delete the old backup projects as well
m_projectDriver.deletePublishHistory(context.currentProject().getId(), maxTag);
}
}
}
/**
* Deletes a file in the Cms.<p>
*
* A file can only be deleteed in an offline project.
* A file is deleted by setting its state to DELETED (3).
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callinUser</li>
* </ul>
*
* @param context the current request context
* @param filename the complete m_path of the file
* @param deleteOption flag to delete siblings as well
*
* @throws CmsException if operation was not succesful.
*/
public void deleteFile(CmsRequestContext context, String filename, int deleteOption) throws CmsException {
List resources = (List)new ArrayList();
CmsResource currentResource = null;
CmsLock currentLock = null;
CmsResource resource = null;
Iterator i = null;
boolean existsOnline = false;
// TODO set the flag deleteOption in all calling methods correct
// read the resource to delete/remove
resource = readFileHeader(context, filename, false);
// upgrade a potential inherited, non-shared lock into an exclusive lock
currentLock = getLock(context, filename);
if (currentLock.getType() == CmsLock.C_TYPE_INHERITED) {
lockResource(context, filename);
}
// add the resource itself to the list of all resources that get deleted/removed
resources.add(resource);
// if selected, add all links pointing to this resource to the list of files that get deleted/removed
if (deleteOption == I_CmsConstants.C_DELETE_OPTION_DELETE_SIBLINGS) {
resources.addAll(readSiblings(context, filename, false, false));
}
// ensure that each link pointing to the resource is unlocked or locked by the current user
i = resources.iterator();
while (i.hasNext()) {
currentResource = (CmsResource)i.next();
currentLock = getLock(context, currentResource);
if (!currentLock.equals(CmsLock.getNullLock()) && !currentLock.getUserId().equals(context.currentUser().getId())) {
// the resource is locked by a user different from the current user
int exceptionType = currentLock.getUserId().equals(context.currentUser().getId()) ? CmsLockException.C_RESOURCE_LOCKED_BY_CURRENT_USER : CmsLockException.C_RESOURCE_LOCKED_BY_OTHER_USER;
throw new CmsLockException("VFS link " + currentResource.getRootPath() + " pointing to " + filename + " is locked by another user!", exceptionType);
}
}
// delete/remove all collected resources
i = resources.iterator();
while (i.hasNext()) {
existsOnline = false;
currentResource = (CmsResource)i.next();
// try to delete/remove the resource only if the user has write access to the resource
if (hasPermissions(context, currentResource, I_CmsConstants.C_WRITE_ACCESS, false)) {
try {
// try to read the corresponding online resource to decide if the resource should be either removed or deleted
readFileHeaderInProject(I_CmsConstants.C_PROJECT_ONLINE_ID, currentResource.getRootPath(), false);
existsOnline = true;
} catch (CmsException exc) {
existsOnline = false;
}
m_lockManager.removeResource(this, context, currentResource.getRootPath(), true);
if (!existsOnline) {
// remove the properties
deleteAllProperties(context, currentResource.getRootPath());
// remove the access control entries
m_userDriver.removeAccessControlEntries(context.currentProject(), currentResource.getResourceId());
// the resource doesn't exist online => remove the file
if (currentResource.isLabeled() && !labelResource(context, currentResource, null, 2)) {
// update the resource flags to "unlabel" the other siblings
int flags = currentResource.getFlags();
flags &= ~I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
currentResource.setFlags(flags);
}
m_vfsDriver.removeFile(context.currentProject(), currentResource, true);
} else {
// delete the access control entries
deleteAllAccessControlEntries(context, currentResource);
// the resource exists online => mark the file as deleted
//m_vfsDriver.deleteFile(context.currentProject(), currentResource);
currentResource.setState(I_CmsConstants.C_STATE_DELETED);
m_vfsDriver.writeResourceState(context.currentProject(), currentResource, C_UPDATE_STRUCTURE_STATE);
// add the project id as a property, this is later used for publishing
CmsProperty property = new CmsProperty();
property.setKey(I_CmsConstants.C_PROPERTY_INTERNAL);
property.setStructureValue("" + context.currentProject().getId());
m_vfsDriver.writePropertyObject(context.currentProject(), currentResource, property);
// TODO: still necessary after we have the property?
// update the project ID
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), currentResource);
}
}
}
// flush all caches
clearAccessControlListCache();
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_DELETED, Collections.singletonMap("resources", resources)));
}
/**
* Deletes a folder in the Cms.<p>
*
* Only folders in an offline Project can be deleted. A folder is deleted by
* setting its state to DELETED (3).
* In its current implmentation, this method can ONLY delete empty folders.
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read and write this resource and all subresources</li>
* <li>the resource is not locked</li>
* </ul>
*
* @param context the current request context
* @param foldername the complete m_path of the folder
*
* @throws CmsException if operation was not succesful
*/
public void deleteFolder(CmsRequestContext context, String foldername) throws CmsException {
CmsResource onlineFolder;
// TODO: "/" is currently used inconsistent !!!
if (!CmsResource.isFolder(foldername)) {
foldername = foldername.concat("/");
}
// read the folder, that should be deleted
CmsFolder cmsFolder = readFolder(context, foldername);
try {
onlineFolder = readFolderInProject(I_CmsConstants.C_PROJECT_ONLINE_ID, foldername);
} catch (CmsException exc) {
// the file dosent exist
onlineFolder = null;
}
// check if the user has write access to the folder
checkPermissions(context, cmsFolder, I_CmsConstants.C_WRITE_ACCESS);
m_lockManager.removeResource(this, context, foldername, true);
// write-acces was granted - delete the folder and metainfos.
if (onlineFolder == null) {
// the onlinefile dosent exist => remove the file realy!
deleteAllProperties(context, foldername);
m_vfsDriver.removeFolder(context.currentProject(), cmsFolder);
// remove the access control entries
m_userDriver.removeAccessControlEntries(context.currentProject(), cmsFolder.getResourceId());
} else {
// m_vfsDriver.deleteFolder(context.currentProject(), cmsFolder);
// add the project id as a property, this is later used for publishing
CmsProperty property = new CmsProperty();
property.setKey(I_CmsConstants.C_PROPERTY_INTERNAL);
property.setStructureValue("" + context.currentProject().getId());
m_vfsDriver.writePropertyObject(context.currentProject(), cmsFolder, property);
cmsFolder.setState(I_CmsConstants.C_STATE_DELETED);
m_vfsDriver.writeResourceState(context.currentProject(), cmsFolder, C_UPDATE_STRUCTURE_STATE);
// delete the access control entries
deleteAllAccessControlEntries(context, cmsFolder);
// update the project ID
// TODO: still nescessary?
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), cmsFolder);
}
// update cache
clearAccessControlListCache();
clearResourceCache();
List resources = (List) new ArrayList();
resources.add(cmsFolder);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_DELETED, Collections.singletonMap("resources", resources)));
}
/**
* Delete a group from the Cms.<p>
*
* Only groups that contain no subgroups can be deleted.
* Only the admin can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param delgroup the name of the group that is to be deleted
* @throws CmsException if operation was not succesfull
*/
public void deleteGroup(CmsRequestContext context, String delgroup) throws CmsException {
// Check the security
if (isAdmin(context)) {
Vector childs = null;
Vector users = null;
// get all child groups of the group
childs = getChild(context, delgroup);
// get all users in this group
users = getUsersOfGroup(context, delgroup);
// delete group only if it has no childs and there are no users in this group.
if ((childs == null) && ((users == null) || (users.size() == 0))) {
m_userDriver.deleteGroup(delgroup);
m_groupCache.remove(new CacheId(delgroup));
} else {
throw new CmsException(delgroup, CmsException.C_GROUP_NOT_EMPTY);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteGroup() " + delgroup, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Deletes a project.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param context the current request context
* @param projectId the id of the project to be published
*
* @throws CmsException if something goes wrong
*/
public void deleteProject(CmsRequestContext context, int projectId) throws CmsException {
Vector deletedFolders = new Vector();
// read the project that should be deleted.
CmsProject deleteProject = readProject(projectId);
if ((isAdmin(context) || isManagerOfProject(context)) && (projectId != I_CmsConstants.C_PROJECT_ONLINE_ID)) {
// List allFiles = m_vfsDriver.readFiles(deleteProject.getId(), false, true);
// List allFolders = m_vfsDriver.readFolders(deleteProject, false, true);
List allFiles = readChangedResourcesInsideProject(context, projectId, 1);
List allFolders = readChangedResourcesInsideProject(context, projectId, CmsResourceTypeFolder.C_RESOURCE_TYPE_ID);
// first delete files or undo changes in files
for (int i = 0; i < allFiles.size(); i++) {
CmsFile currentFile = (CmsFile)allFiles.get(i);
String currentResourceName = readPath(context, currentFile, true);
if (currentFile.getState() == I_CmsConstants.C_STATE_NEW) {
CmsLock lock = getLock(context, currentFile);
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// delete the properties
m_vfsDriver.deleteProperties(projectId, currentFile);
// delete the file
m_vfsDriver.removeFile(context.currentProject(), currentFile, true);
// remove the access control entries
m_userDriver.removeAccessControlEntries(context.currentProject(), currentFile.getResourceId());
} else if (currentFile.getState() == I_CmsConstants.C_STATE_CHANGED) {
CmsLock lock = getLock(context, currentFile);
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// undo all changes in the file
undoChanges(context, currentResourceName);
} else if (currentFile.getState() == I_CmsConstants.C_STATE_DELETED) {
// first undelete the file
undeleteResource(context, currentResourceName);
CmsLock lock = getLock(context, currentFile);
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// then undo all changes in the file
undoChanges(context, currentResourceName);
}
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", currentFile)));
}
// now delete folders or undo changes in folders
for (int i = 0; i < allFolders.size(); i++) {
CmsFolder currentFolder = (CmsFolder)allFolders.get(i);
String currentResourceName = readPath(context, currentFolder, true);
CmsLock lock = getLock(context, currentFolder);
if (currentFolder.getState() == I_CmsConstants.C_STATE_NEW) {
// delete the properties
m_vfsDriver.deleteProperties(projectId, currentFolder);
// add the folder to the vector of folders that has to be deleted
deletedFolders.addElement(currentFolder);
} else if (currentFolder.getState() == I_CmsConstants.C_STATE_CHANGED) {
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// undo all changes in the folder
undoChanges(context, currentResourceName);
} else if (currentFolder.getState() == I_CmsConstants.C_STATE_DELETED) {
// undelete the folder
undeleteResource(context, currentResourceName);
if (lock.isNullLock()) {
// lock the resource
lockResource(context, currentResourceName);
} else if (!lock.getUserId().equals(context.currentUser().getId()) || lock.getProjectId() != context.currentProject().getId()) {
changeLock(context, currentResourceName);
}
// then undo all changes in the folder
undoChanges(context, currentResourceName);
}
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", currentFolder)));
}
// now delete the folders in the vector
for (int i = deletedFolders.size() - 1; i > -1; i--) {
CmsFolder delFolder = ((CmsFolder)deletedFolders.elementAt(i));
m_vfsDriver.removeFolder(context.currentProject(), delFolder);
// remove the access control entries
m_userDriver.removeAccessControlEntries(context.currentProject(), delFolder.getResourceId());
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", delFolder)));
}
// unlock all resources in the project
m_lockManager.removeResourcesInProject(deleteProject.getId());
clearAccessControlListCache();
clearResourceCache();
// set project to online project if current project is the one which will be deleted
if (projectId == context.currentProject().getId()) {
context.setCurrentProject(readProject(I_CmsConstants.C_PROJECT_ONLINE_ID));
}
// delete the project
m_projectDriver.deleteProject(deleteProject);
m_projectCache.remove(new Integer(projectId));
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROJECT_MODIFIED, Collections.singletonMap("project", deleteProject)));
} else if (projectId == I_CmsConstants.C_PROJECT_ONLINE_ID) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteProject() " + deleteProject.getName(), CmsSecurityException.C_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteProject() " + deleteProject.getName(), CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
}
}
/**
* Delete the propertydefinition for the resource type.<p>
*
* Only the admin can do this.
*
* @param context the current request context
* @param name the name of the propertydefinition to read
* @param resourcetype the name of the resource type for which the propertydefinition is valid
*
* @throws CmsException if something goes wrong
*/
public void deletePropertydefinition(CmsRequestContext context, String name, int resourcetype) throws CmsException {
CmsPropertydefinition propertyDefinition = null;
// check the security
if (isAdmin(context)) {
try {
// first read and then delete the metadefinition.
propertyDefinition = readPropertydefinition(context, name, resourcetype);
m_vfsDriver.deletePropertyDefinition(propertyDefinition);
} finally {
// fire an event that a property of a resource has been deleted
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROPERTY_DEFINITION_MODIFIED, Collections.singletonMap("propertyDefinition", propertyDefinition)));
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deletePropertydefinition() " + name, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Deletes an entry in the published resource table.<p>
*
* @param context the current request context
* @param resourceName The name of the resource to be deleted in the static export
* @param linkType the type of resource deleted (0= non-paramter, 1=parameter)
* @param linkParameter the parameters ofthe resource
* @throws CmsException if something goes wrong
*/
public void deleteStaticExportPublishedResource(CmsRequestContext context, String resourceName, int linkType, String linkParameter) throws CmsException {
m_projectDriver.deleteStaticExportPublishedResource(context.currentProject(), resourceName, linkType, linkParameter);
}
/**
* Deletes all entries in the published resource table.<p>
*
* @param context the current request context
* @param linkType the type of resource deleted (0= non-paramter, 1=parameter)
* @throws CmsException if something goes wrong
*/
public void deleteAllStaticExportPublishedResources(CmsRequestContext context, int linkType) throws CmsException {
m_projectDriver.deleteAllStaticExportPublishedResources(context.currentProject(), linkType);
}
/**
* Deletes a user from the Cms.<p>
*
* Only a adminstrator can do this.
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param userId the Id of the user to be deleted
*
* @throws CmsException if operation was not succesfull
*/
public void deleteUser(CmsRequestContext context, CmsUUID userId) throws CmsException {
CmsUser user = readUser(userId);
deleteUser(context, user.getName());
}
/**
* Deletes a user from the Cms.<p>
*
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param username the name of the user to be deleted
*
* @throws CmsException if operation was not succesfull
*/
public void deleteUser(CmsRequestContext context, String username) throws CmsException {
// Test is this user is existing
CmsUser user = readUser(username);
// Check the security
// Avoid to delete admin or guest-user
if (isAdmin(context) && !(username.equals(OpenCms.getDefaultUsers().getUserAdmin()) || username.equals(OpenCms.getDefaultUsers().getUserGuest()))) {
m_userDriver.deleteUser(username);
// delete user from cache
clearUserCache(user);
} else if (username.equals(OpenCms.getDefaultUsers().getUserAdmin()) || username.equals(OpenCms.getDefaultUsers().getUserGuest())) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteUser() " + username, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] deleteUser() " + username, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Deletes a web user from the Cms.<p>
*
* @param userId the Id of the user to be deleted
*
* @throws CmsException if operation was not succesfull
*/
public void deleteWebUser(CmsUUID userId) throws CmsException {
CmsUser user = readUser(userId);
m_userDriver.deleteUser(user.getName());
// delete user from cache
clearUserCache(user);
}
/**
* Destroys this driver manager.<p>
*
* @throws Throwable if something goes wrong
*/
public void destroy() throws Throwable {
finalize();
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Shutting down : " + this.getClass().getName() + " ... ok!");
}
}
/**
* Method to encrypt the passwords.<p>
*
* @param value the value to encrypt
* @return the encrypted value
*/
public String digest(String value) {
return m_userDriver.encryptPassword(value);
}
/**
* Ends a task from the Cms.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskid the ID of the task to end
*
* @throws CmsException if something goes wrong
*/
public void endTask(CmsRequestContext context, int taskid) throws CmsException {
m_workflowDriver.endTask(taskid);
if (context.currentUser() == null) {
m_workflowDriver.writeSystemTaskLog(taskid, "Task finished.");
} else {
m_workflowDriver.writeSystemTaskLog(taskid, "Task finished by " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
}
/**
* Tests if a resource with the given resourceId does already exist in the Database.<p>
*
* @param context the current request context
* @param resourceId the resource id to test for
* @return true if a resource with the given id was found, false otherweise
* @throws CmsException if something goes wrong
*/
public boolean existsResourceId(CmsRequestContext context, CmsUUID resourceId) throws CmsException {
return m_vfsDriver.validateResourceIdExists(context.currentProject().getId(), resourceId);
}
/**
* Extracts resources from a given resource list which are inside a given folder tree.<p>
*
* @param context the current request context
* @param storage ste of CmsUUID of all folders instide the folder tree
* @param resources list of CmsResources
* @return filtered list of CsmResources which are inside the folder tree
* @throws CmsException if operation was not succesful
*/
private List extractResourcesInTree(CmsRequestContext context, Set storage, List resources) throws CmsException {
List result = (List)new ArrayList();
Iterator i = resources.iterator();
// now select only those resources which are in the folder tree below the given folder
while (i.hasNext()) {
CmsResource res = (CmsResource)i.next();
// ckeck if the parent id of the resource is within the folder tree
if (storage.contains(res.getParentStructureId())) {
//this resource is inside the folder tree.
// now check if it is not marked as deleted
if (res.getState() != I_CmsConstants.C_STATE_DELETED) {
// check the read access
if (hasPermissions(context, res, I_CmsConstants.C_READ_ACCESS, false)) {
// this is a valid resouce, add it to the result list
res.setFullResourceName(readPath(context, res, false));
result.add(res);
updateContextDates(context, res);
}
}
}
}
return result;
}
/**
* Releases any allocated resources during garbage collection.<p>
*
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable {
try {
clearcache();
m_projectDriver.destroy();
m_userDriver.destroy();
m_vfsDriver.destroy();
m_workflowDriver.destroy();
m_backupDriver.destroy();
m_userCache = null;
m_groupCache = null;
m_userGroupsCache = null;
m_projectCache = null;
m_propertyCache = null;
m_resourceCache = null;
m_resourceListCache = null;
m_accessControlListCache = null;
m_projectDriver = null;
m_userDriver = null;
m_vfsDriver = null;
m_workflowDriver = null;
m_backupDriver = null;
m_htmlLinkValidator = null;
} catch (Throwable t) {
// ignore
}
super.finalize();
}
/**
* Forwards a task to a new user.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskid the Id of the task to forward
* @param newRoleName the new group name for the task
* @param newUserName the new user who gets the task. if its "" the a new agent will automatic selected
* @throws CmsException if something goes wrong
*/
public void forwardTask(CmsRequestContext context, int taskid, String newRoleName, String newUserName) throws CmsException {
CmsGroup newRole = m_userDriver.readGroup(newRoleName);
CmsUser newUser = null;
if (newUserName.equals("")) {
newUser = readUser(m_workflowDriver.readAgent(newRole.getId()));
} else {
newUser = readUser(newUserName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
}
m_workflowDriver.forwardTask(taskid, newRole.getId(), newUser.getId());
m_workflowDriver.writeSystemTaskLog(taskid, "Task fowarded from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + " to " + newUser.getFirstname() + " " + newUser.getLastname() + ".");
}
/**
* Reads all relevant access control entries for a given resource.<p>
*
* The access control entries of a resource are readable by everyone.
*
* @param context the current request context
* @param resource the resource
* @param getInherited true in order to include access control entries inherited by parent folders
* @return a vector of access control entries defining all permissions for the given resource
* @throws CmsException if something goes wrong
*/
public Vector getAccessControlEntries(CmsRequestContext context, CmsResource resource, boolean getInherited) throws CmsException {
CmsResource res = resource;
CmsUUID resourceId = res.getResourceId();
//CmsAccessControlList acList = new CmsAccessControlList();
// add the aces of the resource itself
Vector acEntries = m_userDriver.readAccessControlEntries(context.currentProject(), resourceId, false);
// add the aces of each predecessor
CmsUUID structureId;
while (getInherited && !(structureId = res.getParentStructureId()).isNullUUID()) {
res = m_vfsDriver.readFolder(context.currentProject().getId(), structureId);
acEntries.addAll(m_userDriver.readAccessControlEntries(context.currentProject(), res.getResourceId(), getInherited));
}
return acEntries;
}
/**
* Returns the access control list of a given resource.<p>
*
* Note: the current project must be the project the resource belongs to !
* The access control list of a resource is readable by everyone.
*
* @param context the current request context
* @param resource the resource
* @return the access control list of the resource
* @throws CmsException if something goes wrong
*/
public CmsAccessControlList getAccessControlList(CmsRequestContext context, CmsResource resource) throws CmsException {
return getAccessControlList(context, resource, false);
}
/**
* Returns the access control list of a given resource.<p>
*
* If inheritedOnly is set, non-inherited entries of the resource are skipped.
*
* @param context the current request context
* @param resource the resource
* @param inheritedOnly skip non-inherited entries if set
* @return the access control list of the resource
* @throws CmsException if something goes wrong
*/
public CmsAccessControlList getAccessControlList(CmsRequestContext context, CmsResource resource, boolean inheritedOnly) throws CmsException {
CmsResource res = resource;
CmsAccessControlList acList = (CmsAccessControlList)m_accessControlListCache.get(getCacheKey(inheritedOnly + "_", context.currentProject(), resource.getStructureId().toString()));
ListIterator acEntries = null;
CmsUUID resourceId = null;
// return the cached acl if already available
if (acList != null) {
return acList;
}
// otherwise, get the acl of the parent or a new one
if (!(resourceId = res.getParentStructureId()).isNullUUID()) {
res = m_vfsDriver.readFolder(context.currentProject().getId(), resourceId);
acList = (CmsAccessControlList)getAccessControlList(context, res, true).clone();
} else {
acList = new CmsAccessControlList();
}
// add the access control entries belonging to this resource
acEntries = m_userDriver.readAccessControlEntries(context.currentProject(), resource.getResourceId(), inheritedOnly).listIterator();
while (acEntries.hasNext()) {
CmsAccessControlEntry acEntry = (CmsAccessControlEntry)acEntries.next();
// if the overwrite flag is set, reset the allowed permissions to the permissions of this entry
if ((acEntry.getFlags() & I_CmsConstants.C_ACCESSFLAGS_OVERWRITE) > 0) {
acList.setAllowedPermissions(acEntry);
} else {
acList.add(acEntry);
}
}
m_accessControlListCache.put(getCacheKey(inheritedOnly + "_", context.currentProject(), resource.getStructureId().toString()), acList);
return acList;
}
/**
* Returns all projects, which are owned by the user or which are accessible for the group of the user.<p>
*
* All users are granted.
*
* @param context the current request context
* @return a vector of projects
* @throws CmsException if something goes wrong
*/
public Vector getAllAccessibleProjects(CmsRequestContext context) throws CmsException {
// get all groups of the user
Vector groups = getGroupsOfUser(context, context.currentUser().getName());
// get all projects which are owned by the user.
Vector projects = m_projectDriver.readProjectsForUser(context.currentUser());
// get all projects, that the user can access with his groups.
for (int i = 0; i < groups.size(); i++) {
Vector projectsByGroup;
// is this the admin-group?
if (((CmsGroup)groups.elementAt(i)).getName().equals(OpenCms.getDefaultUsers().getGroupAdministrators())) {
// yes - all unlocked projects are accessible for him
projectsByGroup = m_projectDriver.readProjects(I_CmsConstants.C_PROJECT_STATE_UNLOCKED);
} else {
// no - get all projects, which can be accessed by the current group
projectsByGroup = m_projectDriver.readProjectsForGroup((CmsGroup)groups.elementAt(i));
}
// merge the projects to the vector
for (int j = 0; j < projectsByGroup.size(); j++) {
// add only projects, which are new
if (!projects.contains(projectsByGroup.elementAt(j))) {
projects.addElement(projectsByGroup.elementAt(j));
}
}
}
// return the vector of projects
return (projects);
}
/**
* Returns a Vector with all projects from history.<p>
*
* @return Vector with all projects from history.
* @throws CmsException if operation was not succesful.
*/
public Vector getAllBackupProjects() throws CmsException {
Vector projects = new Vector();
projects = m_backupDriver.readBackupProjects();
return projects;
}
/**
* Returns all projects, which are owned by the user or which are manageable for the group of the user.<p>
*
* All users are granted.
*
* @param context the current request context
* @return a Vector of projects
* @throws CmsException if operation was not succesful
*/
public Vector getAllManageableProjects(CmsRequestContext context) throws CmsException {
// get all groups of the user
Vector groups = getGroupsOfUser(context, context.currentUser().getName());
// get all projects which are owned by the user.
Vector projects = m_projectDriver.readProjectsForUser(context.currentUser());
// get all projects, that the user can manage with his groups.
for (int i = 0; i < groups.size(); i++) {
// get all projects, which can be managed by the current group
Vector projectsByGroup;
// is this the admin-group?
if (((CmsGroup)groups.elementAt(i)).getName().equals(OpenCms.getDefaultUsers().getGroupAdministrators())) {
// yes - all unlocked projects are accessible for him
projectsByGroup = m_projectDriver.readProjects(I_CmsConstants.C_PROJECT_STATE_UNLOCKED);
} else {
// no - get all projects, which can be accessed by the current group
projectsByGroup = m_projectDriver.readProjectsForManagerGroup((CmsGroup)groups.elementAt(i));
}
// merge the projects to the vector
for (int j = 0; j < projectsByGroup.size(); j++) {
// add only projects, which are new
if (!projects.contains(projectsByGroup.elementAt(j))) {
projects.addElement(projectsByGroup.elementAt(j));
}
}
}
// remove the online-project, it is not manageable!
projects.removeElement(onlineProject());
// return the vector of projects
return projects;
}
/**
* Returns an array with all all initialized resource types.<p>
*
* @return array with all initialized resource types
*/
public I_CmsResourceType[] getAllResourceTypes() {
// return the resource-types.
return m_resourceTypes;
}
/**
* Gets the backup driver.<p>
*
* @return CmsBackupDriver
*/
public final I_CmsBackupDriver getBackupDriver() {
return m_backupDriver;
}
/**
* Get the next version id for the published backup resources.<p>
*
* @return the new version id
*/
public int getBackupTagId() {
return m_backupDriver.readNextBackupTagId();
}
/**
* Return a cache key build from the provided information.<p>
*
* @param prefix a prefix for the key
* @param project the project for which to genertate the key
* @param resource the resource for which to genertate the key
* @return String a cache key build from the provided information
*/
private String getCacheKey(String prefix, CmsProject project, String resource) {
StringBuffer buffer = new StringBuffer(32);
if (prefix != null) {
buffer.append(prefix);
buffer.append("_");
}
if (project != null) {
if (project.isOnlineProject()) {
buffer.append("on");
} else {
buffer.append("of");
}
buffer.append("_");
}
buffer.append(resource);
return buffer.toString();
}
/**
* Return a cache key build from the provided information.<p>
*
* @param prefix a prefix for the key
* @param projectId the project for which to genertate the key
* @param resource the resource for which to genertate the key
* @return String a cache key build from the provided information
*/
private String getCacheKey(String prefix, int projectId, String resource) {
StringBuffer buffer = new StringBuffer(32);
if (prefix != null) {
buffer.append(prefix);
buffer.append("_");
}
if (projectId >= I_CmsConstants.C_PROJECT_ONLINE_ID) {
if (projectId == I_CmsConstants.C_PROJECT_ONLINE_ID) {
buffer.append("on");
} else {
buffer.append("of");
}
buffer.append("_");
}
buffer.append(resource);
return buffer.toString();
}
/**
* Returns all child groups of a group.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param groupname the name of the group
* @return groups a Vector of all child groups or null
* @throws CmsException if operation was not succesful.
*/
public Vector getChild(CmsRequestContext context, String groupname) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readChildGroups(groupname);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getChild()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns all child groups of a group.<p>
* This method also returns all sub-child groups of the current group.
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param groupname the name of the group
* @return a Vector of all child groups or null
* @throws CmsException if operation was not succesful
*/
public Vector getChilds(CmsRequestContext context, String groupname) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
Vector childs = new Vector();
Vector allChilds = new Vector();
Vector subchilds = new Vector();
CmsGroup group = null;
// get all child groups if the user group
childs = m_userDriver.readChildGroups(groupname);
if (childs != null) {
allChilds = childs;
// now get all subchilds for each group
Enumeration enu = childs.elements();
while (enu.hasMoreElements()) {
group = (CmsGroup)enu.nextElement();
subchilds = getChilds(context, group.getName());
//add the subchilds to the already existing groups
Enumeration enusub = subchilds.elements();
while (enusub.hasMoreElements()) {
group = (CmsGroup)enusub.nextElement();
allChilds.addElement(group);
}
}
}
return allChilds;
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getChilds()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Method to access the configurations of the properties-file.<p>
*
* All users are granted.
*
* @return the Configurations of the properties-file
*/
public ExtendedProperties getConfigurations() {
return m_configuration;
}
/**
* Returns the list of groups to which the user directly belongs to<P/>
*
* <B>Security:</B>
* All users are granted.
*
* @param context the current request context
* @param username The name of the user.
* @return Vector of groups
* @throws CmsException Throws CmsException if operation was not succesful
*/
public Vector getDirectGroupsOfUser(CmsRequestContext context, String username) throws CmsException {
CmsUser user = readUser(username);
return m_userDriver.readGroupsOfUser(user.getId(), context.getRemoteAddress());
}
/**
* Returns a Vector with all resource-names that have set the given property to the given value.<p>
*
* All users are granted.
*
* @param context the current request context
* @param propertyDefinition the name of the propertydefinition to check
* @param propertyValue the value of the property for the resource
* @return vector with all names of resources
* @throws CmsException if operation was not succesful
*/
public Vector getFilesWithProperty(CmsRequestContext context, String propertyDefinition, String propertyValue) throws CmsException {
List result = setFullResourceNames(context, m_vfsDriver.readResourceNames(context.currentProject().getId(), propertyDefinition, propertyValue));
return new Vector(result);
}
/**
* This method can be called, to determine if the file-system was changed
* in the past. A module can compare its previosly stored number with this
* returned number. If they differ, a change was made.<p>
*
* All users are granted.
*
* @return the number of file-system-changes.
*/
public long getFileSystemFolderChanges() {
return m_fileSystemFolderChanges;
}
/**
* Creates Set containing all CmsUUIDs of the subfolders of a given folder.<p>
*
* This HashSet can be used to test if a resource is inside a subtree of the given folder.
* No permission check is performed on the set of folders, if required this has to be done
* in the method that calls this method.<p>
*
* @param context the current request context
* @param folder the folder to get the subresources from
* @return Set of CmsUUIDs
* @throws CmsException if operation was not succesful
*/
private Set getFolderIds(CmsRequestContext context, String folder) throws CmsException {
CmsFolder parentFolder = readFolder(context, folder);
return (Set)new HashSet(m_vfsDriver.readFolderTree(context.currentProject(), parentFolder));
}
/**
* Returns all groups.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @return users a Vector of all existing groups
* @throws CmsException if operation was not succesful
*/
public Vector getGroups(CmsRequestContext context) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readGroups();
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getGroups()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns the groups of a Cms user.<p>
*
* @param context the current request context
* @param username the name of the user
* @return a vector of Cms groups filtered by the specified IP address
* @throws CmsException if operation was not succesful
*/
public Vector getGroupsOfUser(CmsRequestContext context, String username) throws CmsException {
return getGroupsOfUser(context, username, context.getRemoteAddress());
}
/**
* Returns the groups of a Cms user filtered by the specified IP address.<p>
*
* @param context the current request context
* @param username the name of the user
* @param remoteAddress the IP address to filter the groups in the result vector
* @return a vector of Cms groups
* @throws CmsException if operation was not succesful
*/
public Vector getGroupsOfUser(CmsRequestContext context, String username, String remoteAddress) throws CmsException {
CmsUser user = readUser(username);
String cacheKey = m_keyGenerator.getCacheKeyForUserGroups(remoteAddress, context, user);
Vector allGroups = (Vector)m_userGroupsCache.get(cacheKey);
if ((allGroups == null) || (allGroups.size() == 0)) {
CmsGroup subGroup;
CmsGroup group;
// get all groups of the user
Vector groups = m_userDriver.readGroupsOfUser(user.getId(), remoteAddress);
allGroups = new Vector();
// now get all childs of the groups
Enumeration enu = groups.elements();
while (enu.hasMoreElements()) {
group = (CmsGroup)enu.nextElement();
subGroup = getParent(group.getName());
while ((subGroup != null) && (!allGroups.contains(subGroup))) {
allGroups.addElement(subGroup);
// read next sub group
subGroup = getParent(subGroup.getName());
}
if (!allGroups.contains(group)) {
allGroups.add(group);
}
}
m_userGroupsCache.put(cacheKey, allGroups);
}
return allGroups;
}
/**
* Returns all groups with a name like the specified pattern.<p>
*
* All users are granted, except the anonymous user.<p>
*
* @param context the current request context
* @param namePattern pattern for the group name
* @return a Vector of all groups with a name like the given pattern
* @throws CmsException if something goes wrong
*/
public Vector getGroupsLike(CmsRequestContext context, String namePattern) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readGroupsLike(namePattern);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getGroupsLike()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Checks if a user is a direct member of a group having a name like the specified pattern.<p>
*
* All users are granted.<p>
*
* @param context the current request context
* @param username the name of the user.
* @param groupNamePattern pattern for the group name
* @return <code>true</code> if the given user is a direct member of a group having a name like the specified pattern
* @throws CmsException if something goes wrong
*/
public boolean hasDirectGroupsOfUserLike(CmsRequestContext context, String username, String groupNamePattern) throws CmsException {
CmsUser user = readUser(username);
return m_userDriver.hasGroupsOfUserLike(user.getId(), context.getRemoteAddress(), groupNamePattern);
}
/**
* This is the port the workplace access is limited to. With the opencms.properties
* the access to the workplace can be limited to a user defined port. With this
* feature a firewall can block all outside requests to this port with the result
* the workplace is only available in the local net segment.<p>
*
* @return the portnumber or -1 if no port is set
*/
public int getLimitedWorkplacePort() {
return m_limitedWorkplacePort;
}
/**
* Returns the lock for a resource.<p>
*
* @param context the current request context
* @param resource the resource
* @return the lock
* @throws CmsException if something goes wrong
*/
public CmsLock getLock(CmsRequestContext context, CmsResource resource) throws CmsException {
if (!resource.hasFullResourceName()) {
try {
// cw: it must be possible to check if there is a lock set on a resource even if the resource is deleted
readPath(context, resource, true);
} catch (CmsException e) {
return CmsLock.getNullLock();
}
}
return getLock(context, resource.getRootPath());
}
/**
* Returns the lock for a resource name.<p>
*
* @param context the current request context
* @param resourcename name of the resource
* @return the lock
* @throws CmsException if something goes wrong
*/
public CmsLock getLock(CmsRequestContext context, String resourcename) throws CmsException {
return m_lockManager.getLock(this, context, resourcename);
}
/**
* Returns the parent group of a group.<p>
*
* @param groupname the name of the group
* @return group the parent group or null
* @throws CmsException if operation was not succesful
*/
public CmsGroup getParent(String groupname) throws CmsException {
CmsGroup group = readGroup(groupname);
if (group.getParentId().isNullUUID()) {
return null;
}
// try to read from cache
CmsGroup parent = (CmsGroup)m_groupCache.get(new CacheId(group.getParentId()));
if (parent == null) {
parent = m_userDriver.readGroup(group.getParentId());
m_groupCache.put(new CacheId(parent), parent);
}
return parent;
}
/**
* Returns the parent resource of a resouce.<p>
*
* All users are granted.
*
* @param context the current request context
* @param resourcename the name of the resource to find the parent for
* @return the parent resource read from the VFS
* @throws CmsException if parent resource could not be read
*/
public CmsResource getParentResource(CmsRequestContext context, String resourcename) throws CmsException {
// check if this is the root resource
if (!resourcename.equals(I_CmsConstants.C_ROOT)) {
return readFileHeader(context, CmsResource.getParentFolder(resourcename));
} else {
// just return the root
return readFileHeader(context, I_CmsConstants.C_ROOT);
}
}
/**
* Returns the current permissions of an user on the given resource.<p>
*
* Permissions are readable by everyone.
*
* @param context the current request context
* @param resource the resource
* @param user the user
* @return bitset with allowed permissions
* @throws CmsException if something goes wrong
*/
public CmsPermissionSet getPermissions(CmsRequestContext context, CmsResource resource, CmsUser user) throws CmsException {
CmsAccessControlList acList = getAccessControlList(context, resource);
return acList.getPermissions(user, getGroupsOfUser(context, user.getName()));
}
/**
* Gets the project driver.<p>
*
* @return CmsProjectDriver
*/
public final I_CmsProjectDriver getProjectDriver() {
return m_projectDriver;
}
/**
* Returns the current OpenCms registry.<p>
*
* @param cms the current OpenCms context object
* @return the current OpenCms registry
*/
public CmsRegistry getRegistry(CmsObject cms) {
return m_registry.clone(cms);
}
/**
* Returns a Vector with the subresources for a folder.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read and view this resource</li>
* </ul>
*
* @param context the current request context
* @param folder the name of the folder to get the subresources from
* @return a Vector with resources.
*
* @throws CmsException if operation was not successful
*/
public Vector getResourcesInFolder(CmsRequestContext context, String folder) throws CmsException {
CmsFolder folderRes = null;
Vector resources = new Vector();
Vector retValue = new Vector();
try {
folderRes = readFolder(context, folder);
if (folderRes.getState() == I_CmsConstants.C_STATE_DELETED) {
folderRes = null;
}
} catch (CmsException exc) {
// ignore the exception - folder was not found in this project
}
if (folderRes == null) {
// the folder is not existent
throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_NOT_FOUND);
} else {
// try to read from cache
String cacheKey = getCacheKey(context.currentUser().getName() + "_resources", context.currentProject(), folderRes.getRootPath());
retValue = (Vector)m_resourceListCache.get(cacheKey);
if (retValue == null || retValue.size() == 0) {
//resources = m_vfsDriver.getResourcesInFolder(context.currentProject().getId(), folderRes);
List subFolders = m_vfsDriver.readChildResources(context.currentProject(), folderRes, true);
List subFiles = m_vfsDriver.readChildResources(context.currentProject(), folderRes, false);
resources.addAll(subFolders);
resources.addAll(subFiles);
setFullResourceNames(context, resources);
retValue = new Vector(resources.size());
// make sure that we have access to all these
Iterator i = resources.iterator();
while (i.hasNext()) {
CmsResource res = (CmsResource)i.next();
if (hasPermissions(context, res, I_CmsConstants.C_VIEW_ACCESS, false)) {
if (res.isFolder() && !CmsResource.isFolder(res.getName())) {
res.setFullResourceName(folderRes.getRootPath() + res.getName().concat("/"));
} else {
res.setFullResourceName(folderRes.getRootPath() + res.getName());
}
retValue.addElement(res);
updateContextDates(context, res);
}
}
m_resourceListCache.put(cacheKey, retValue);
}
}
return (retValue == null) ? null : (Vector)retValue.clone();
}
/**
* Returns a list with all sub resources of a given folder that have benn modified in a given time range.<p>
*
* All users are granted.
*
* @param context the current request context
* @param folder the folder to get the subresources from
* @param starttime the begin of the time range
* @param endtime the end of the time range
* @return list with all resources
*
* @throws CmsException if operation was not succesful
*/
public List getResourcesInTimeRange(CmsRequestContext context, String folder, long starttime, long endtime) throws CmsException {
List extractedResources = null;
String cacheKey = null;
cacheKey = getCacheKey(context.currentUser().getName() + "_SubtreeResourcesInTimeRange", context.currentProject(), folder + "_" + starttime + "_" + endtime);
if ((extractedResources = (List)m_resourceListCache.get(cacheKey)) == null) {
// get the folder tree
Set storage = getFolderIds(context, folder);
// now get all resources which contain the selected property
List resources = m_vfsDriver.readResources(context.currentProject().getId(), starttime, endtime);
// filter the resources inside the tree
extractedResources = extractResourcesInTree(context, storage, resources);
// cache the calculated result list
m_resourceListCache.put(cacheKey, extractedResources);
resources = null;
storage = null;
}
return extractedResources;
}
/**
* Returns a list with all sub resources of a given folder that have set the given property.<p>
*
* All users are granted.
*
* @param context the current request context
* @param folder the folder to get the subresources from
* @param propertyDefinition the name of the propertydefinition to check
* @return list with all resources
*
* @throws CmsException if operation was not succesful
*/
public List getResourcesWithProperty(CmsRequestContext context, String folder, String propertyDefinition) throws CmsException {
List extractedResources = null;
String cacheKey = null;
cacheKey = getCacheKey(context.currentUser().getName() + "_SubtreeResourcesWithProperty", context.currentProject(), folder + "_" + propertyDefinition);
if ((extractedResources = (List)m_resourceListCache.get(cacheKey)) == null) {
// get the folder tree
Set storage = getFolderIds(context, folder);
// now get all resources which contain the selected property
List resources = m_vfsDriver.readResources(context.currentProject().getId(), propertyDefinition);
// filter the resources inside the tree
extractedResources = extractResourcesInTree(context, storage, resources);
// cache the calculated result list
m_resourceListCache.put(cacheKey, extractedResources);
}
return extractedResources;
}
/**
* Returns a vector with all resources of the given type that have set the given property to the given value.<p>
*
* All users are granted.
*
* @param context the current request context
* @param propertyDefinition the name of the propertydefinition to check
* @return Vector with all resources
* @throws CmsException if operation was not succesful
*/
public Vector getResourcesWithPropertyDefinition(CmsRequestContext context, String propertyDefinition) throws CmsException {
List result = setFullResourceNames(context, m_vfsDriver.readResources(context.currentProject().getId(), propertyDefinition));
return new Vector(result);
}
/**
* Returns a vector with all resources of the given type that have set the given property to the given value.<p>
*
* All users are granted.
*
* @param context the current request context
* @param propertyDefinition the name of the propertydefinition to check
* @param propertyValue the value of the property for the resource
* @param resourceType the resource type of the resource
* @return vector with all resources.
*
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public Vector getResourcesWithPropertyDefintion(CmsRequestContext context, String propertyDefinition, String propertyValue, int resourceType) throws CmsException {
return m_vfsDriver.readResources(context.currentProject().getId(), propertyDefinition, propertyValue, resourceType);
}
/**
* Returns the initialized resource type instance for the given id.<p>
*
* @param resourceType the id of the resourceType to get
* @return the initialized resource type instance for the given id
* @throws CmsException if something goes wrong
*/
public I_CmsResourceType getResourceType(int resourceType) throws CmsException {
try {
return getAllResourceTypes()[resourceType];
} catch (Exception e) {
throw new CmsException("[" + this.getClass().getName() + "] Unknown resource type id requested: " + resourceType, CmsException.C_NOT_FOUND);
}
}
/**
* Returns the initialized resource type instance for the given resource type name.<p>
*
* @param resourceType the name of the resourceType to get
* @return the initialized resource type instance for the given id
* @throws CmsException if something goes wrong
*/
public I_CmsResourceType getResourceType(String resourceType) throws CmsException {
try {
I_CmsResourceType[] types = getAllResourceTypes();
for (int i = 0; i < types.length; i++) {
I_CmsResourceType t = types[i];
if ((t != null) && (t.getResourceTypeName().equals(resourceType))) {
return t;
}
}
throw new Exception("Resource type not found");
} catch (Exception e) {
throw new CmsException("[" + this.getClass().getName() + "] Unknown resource type name requested: " + resourceType, CmsException.C_NOT_FOUND);
}
}
/**
* Gets the sub files of a folder.<p>
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @return a List of all sub files
* @throws CmsException if something goes wrong
*/
public List getSubFiles(CmsRequestContext context, String parentFolderName) throws CmsException {
return getSubFiles(context, parentFolderName, false);
}
/**
* Gets the sub files of a folder.<p>
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @param includeDeleted true if deleted files should be included in the result
* @return a List of all sub files
* @throws CmsException if something goes wrong
*/
public List getSubFiles(CmsRequestContext context, String parentFolderName, boolean includeDeleted) throws CmsException {
return getSubResources(context, parentFolderName, includeDeleted, false);
}
/**
* Gets the sub folders of a folder.<p>
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @return a List of all sub folders
* @throws CmsException if something goes wrong
*/
public List getSubFolders(CmsRequestContext context, String parentFolderName) throws CmsException {
return getSubFolders(context, parentFolderName, false);
}
/**
* Gets the sub folder of a folder.<p>
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @param includeDeleted true if deleted files should be included in the result
* @return a List of all sub folders
* @throws CmsException if something goes wrong
*/
public List getSubFolders(CmsRequestContext context, String parentFolderName, boolean includeDeleted) throws CmsException {
return getSubResources(context, parentFolderName, includeDeleted, true);
}
/**
* Gets all sub folders or sub files in a folder.<p>
* Note: the list contains all resources that are readable or visible.
*
* @param context the current request context
* @param parentFolderName the name of the parent folder
* @param includeDeleted true if deleted files should be included in the result
* @param getSubFolders true if the sub folders of the parent folder are requested, false if the sub files are requested
* @return a list of all sub folders or sub files
* @throws CmsException if something goes wrong
*/
protected List getSubResources(CmsRequestContext context, String parentFolderName, boolean includeDeleted, boolean getSubFolders) throws CmsException {
List subResources = null;
CmsFolder parentFolder = null;
CmsResource currentResource = null;
String cacheKey = null;
// try to get the sub resources from the cache
if (getSubFolders) {
cacheKey = getCacheKey(context.currentUser().getName() + "_folders", context.currentProject(), parentFolderName);
} else {
cacheKey = getCacheKey(context.currentUser().getName() + "_files_" + includeDeleted, context.currentProject(), parentFolderName);
}
subResources = (List)m_resourceListCache.get(cacheKey);
try {
// validate the parent folder name
if (! CmsResource.isFolder(parentFolderName)) {
parentFolderName += "/";
}
// read the parent folder
parentFolder = readFolder(context, parentFolderName, includeDeleted);
checkPermissions(context, parentFolder, I_CmsConstants.C_READ_ACCESS);
} catch (CmsException e) {
return new ArrayList(0);
}
if ((parentFolder.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted)) {
// the parent folder was found, but it is deleted -> sub resources are not available
return new ArrayList(0);
}
if (subResources != null && subResources.size() > 0) {
// the parent folder is not deleted, and the sub resources were cached, no further operations required
// we must return a copy (see below)
return new ArrayList(subResources);
}
// get the sub resources from the VFS driver and check the required permissions
subResources = m_vfsDriver.readChildResources(context.currentProject(), parentFolder, getSubFolders);
for (int i = 0; i < subResources.size(); i++) {
currentResource = (CmsResource)subResources.get(i);
if (!includeDeleted && currentResource.getState() == I_CmsConstants.C_STATE_DELETED) {
subResources.remove(i--);
} else if (!hasPermissions(context, currentResource, I_CmsConstants.C_READ_OR_VIEW_ACCESS, false)) {
subResources.remove(i--);
} else {
if (currentResource.isFolder() && !CmsResource.isFolder(currentResource.getName())) {
currentResource.setFullResourceName(parentFolderName + currentResource.getName().concat("/"));
} else {
currentResource.setFullResourceName(parentFolderName + currentResource.getName());
}
updateContextDates(context, currentResource);
}
}
// cache the sub resources
m_resourceListCache.put(cacheKey, subResources);
// currently we must return a copy to prevent the cached copy from being modified externally
return new ArrayList(subResources);
}
/**
* Get a parameter value for a task.<p>
*
* All users are granted.
*
* @param taskId the Id of the task
* @param parName name of the parameter
* @return task parameter value
* @throws CmsException if something goes wrong
*/
public String getTaskPar(int taskId, String parName) throws CmsException {
return m_workflowDriver.readTaskParameter(taskId, parName);
}
/**
* Get the template task id for a given taskname.<p>
*
* @param taskName name of the task
* @return id from the task template
* @throws CmsException if something goes wrong
*/
public int getTaskType(String taskName) throws CmsException {
return m_workflowDriver.readTaskType(taskName);
}
/**
* Gets a user cache key.<p>
*
* @param id the user uuid
* @return the user cache key
*/
private String getUserCacheKey(CmsUUID id) {
return id.toString();
}
/**
* Gets a user cache key.<p>
*
* @param username the name of the user
* @param type the user type
* @return the user cache key
*/
private String getUserCacheKey(String username, int type) {
return username + C_USER_CACHE_SEP + CmsUser.isSystemUser(type);
}
/**
* Gets the user driver.<p>
*
* @return I_CmsUserDriver
*/
public final I_CmsUserDriver getUserDriver() {
return m_userDriver;
}
/**
* Gets a user from cache.<p>
*
* @param id the user uuid
* @return CmsUser from cache
*/
private CmsUser getUserFromCache(CmsUUID id) {
return (CmsUser)m_userCache.get(getUserCacheKey(id));
}
/**
* Gets a user from cache.<p>
*
* @param username the username
* @param type the user tpye
* @return CmsUser from cache
*/
private CmsUser getUserFromCache(String username, int type) {
return (CmsUser)m_userCache.get(getUserCacheKey(username, type));
}
/**
* Returns all users.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @return a Vector of all existing users
* @throws CmsException if operation was not succesful.
*/
public Vector getUsers(CmsRequestContext context) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsers(I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsers()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns all users from a given type.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param type the type of the users
* @return a Vector of all existing users
* @throws CmsException if operation was not succesful
*/
public Vector getUsers(CmsRequestContext context, int type) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsers(type);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsers()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns all users from a given type that start with a specified string.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param type the type of the users
* @param namestart the filter for the username
* @return a Vector of all existing users
* @throws CmsException if operation was not succesful
*/
public Vector getUsers(CmsRequestContext context, int type, String namestart) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsers(type, namestart);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsers()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Gets all users with a certain Lastname.<p>
*
* @param context the current request context
* @param Lastname the start of the users lastname
* @param UserType webuser or systemuser
* @param UserStatus enabled, disabled
* @param wasLoggedIn was the user ever locked in?
* @param nMax max number of results
* @return vector of users
* @throws CmsException if operation was not successful
*/
public Vector getUsersByLastname(CmsRequestContext context, String Lastname, int UserType, int UserStatus, int wasLoggedIn, int nMax) throws CmsException {
// check security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsers(Lastname, UserType, UserStatus, wasLoggedIn, nMax);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsersByLastname()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Returns a list of users in a group.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param groupname the name of the group to list users from
* @return vector of users
* @throws CmsException if operation was not succesful
*/
public Vector getUsersOfGroup(CmsRequestContext context, String groupname) throws CmsException {
// check the security
if (!context.currentUser().isGuestUser()) {
return m_userDriver.readUsersOfGroup(groupname, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] getUsersOfGroup()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Gets the VfsDriver.<p>
*
* @return CmsVfsDriver
*/
public final I_CmsVfsDriver getVfsDriver() {
return m_vfsDriver;
}
/**
* Returns a Vector with all resources of the given type that have set the given property to the given value.<p>
*
* All users that have read and view access are granted.
*
* @param context the current request context
* @param propertyDefinition the name of the propertydefinition to check.
* @param propertyValue the value of the property for the resource.
* @param resourceType the resource type of the resource
* @return Vector with all resources
* @throws CmsException if operation was not succesful
*/
public Vector getVisibleResourcesWithProperty(CmsRequestContext context, String propertyDefinition, String propertyValue, int resourceType) throws CmsException {
Vector visibleResources = new Vector();
Vector allResources = new Vector();
allResources = m_vfsDriver.readResources(context.currentProject().getId(), propertyDefinition, propertyValue, resourceType);
// check if the user has view access
Enumeration e = allResources.elements();
String lastcheck = "#"; // just a char that is not valid in a filename
while (e.hasMoreElements()) {
CmsResource res = (CmsResource)e.nextElement();
if (!context.removeSiteRoot(readPath(context, res, false)).equals(lastcheck)) {
if (hasPermissions(context, res, I_CmsConstants.C_VIEW_ACCESS, false)) {
visibleResources.addElement(res);
lastcheck = context.removeSiteRoot(readPath(context, res, false));
}
}
}
return visibleResources;
}
/**
* Gets the workflow driver.<p>
*
* @return I_CmsWorkflowDriver
*/
public final I_CmsWorkflowDriver getWorkflowDriver() {
return m_workflowDriver;
}
/**
* Performs a non-blocking permission check on a resource.<p>
*
* @param context the current request context
* @param resource the resource on which permissions are required
* @param requiredPermissions the set of permissions required to access the resource
* @param strongCheck if set to true, all required permission have to be granted, otherwise only one
* @return true if the user has sufficient permissions on the resource
* @throws CmsException if something goes wrong
*/
public boolean hasPermissions(CmsRequestContext context, CmsResource resource, CmsPermissionSet requiredPermissions, boolean strongCheck) throws CmsException {
String cacheKey = m_keyGenerator.getCacheKeyForUserPermissions(new Boolean(strongCheck).toString(), context, resource, requiredPermissions);
Boolean cacheResult = (Boolean)m_permissionCache.get(cacheKey);
if (cacheResult != null) {
return cacheResult.booleanValue();
}
CmsLock lock = getLock(context, resource);
CmsPermissionSet permissions = null;
int denied = 0;
// if this is the onlineproject, write is rejected
if (context.currentProject().isOnlineProject()) {
denied |= I_CmsConstants.C_PERMISSION_WRITE;
}
// check if the current user is admin
boolean isAdmin = isAdmin(context);
// if the resource type is jsp or xml template
// write is only allowed for administrators
if (!isAdmin && ((resource.getType() == CmsResourceTypeXMLTemplate.C_RESOURCE_TYPE_ID) || (resource.getType() == CmsResourceTypeJsp.C_RESOURCE_TYPE_ID))) {
denied |= I_CmsConstants.C_PERMISSION_WRITE;
}
if (!lock.isNullLock()) {
// if the resource is locked by another user, write is rejected
// read must still be possible, since the explorer file list needs some properties
if (!context.currentUser().getId().equals(lock.getUserId())) {
denied |= I_CmsConstants.C_PERMISSION_WRITE;
}
}
if (isAdmin) {
// if the current user is administrator, anything is allowed
permissions = new CmsPermissionSet(~0);
} else {
// otherwise, get the permissions from the access control list
CmsAccessControlList acl = getAccessControlList(context, resource);
permissions = acl.getPermissions(context.currentUser(), getGroupsOfUser(context, context.currentUser().getName()));
}
permissions.denyPermissions(denied);
boolean result;
if (strongCheck) {
result = (requiredPermissions.getPermissions() & (permissions.getPermissions())) == requiredPermissions.getPermissions();
} else {
result = (requiredPermissions.getPermissions() & (permissions.getPermissions())) > 0;
}
m_permissionCache.put(cacheKey, new Boolean(result));
if (!result && OpenCms.getLog(this).isDebugEnabled()) {
OpenCms.getLog(this).debug(
"Access to resource " + resource.getRootPath() + " "
+ "not permitted for user " + context.currentUser().getName() + ", "
+ "required permissions " + requiredPermissions.getPermissionString() + " "
+ "not satisfied by " + permissions.getPermissionString() + " "
+ ((strongCheck) ? "(required all)" : "(required one)"));
}
return result;
}
/**
* Writes a vector of access control entries as new access control entries of a given resource.<p>
*
* Already existing access control entries of this resource are removed before.
* Access is granted, if:
* <ul>
* <li>the current user has control permission on the resource
* </ul>
*
* @param context the current request context
* @param resource the resource
* @param acEntries vector of access control entries applied to the resource
* @throws CmsException if something goes wrong
*/
public void importAccessControlEntries(CmsRequestContext context, CmsResource resource, Vector acEntries) throws CmsException {
checkPermissions(context, resource, I_CmsConstants.C_CONTROL_ACCESS);
m_userDriver.removeAccessControlEntries(context.currentProject(), resource.getResourceId());
Iterator i = acEntries.iterator();
while (i.hasNext()) {
m_userDriver.writeAccessControlEntry(context.currentProject(), (CmsAccessControlEntry)i.next());
}
clearAccessControlListCache();
//touchResource(context, resource, System.currentTimeMillis());
}
/**
* Imports a import-resource (folder or zipfile) to the cms.<p>
*
* Only Administrators can do this.
*
* @param cms the cms-object to use for the export
* @param context the current request context
* @param importFile the name (absolute Path) of the import resource (zip or folder)
* @param importPath the name (absolute Path) of folder in which should be imported
* @throws CmsException if something goes wrong
*/
public void importFolder(CmsObject cms, CmsRequestContext context, String importFile, String importPath) throws CmsException {
if (isAdmin(context)) {
new CmsImportFolder(importFile, importPath, cms);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] importFolder()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Imports a resource.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is not locked by another user</li>
* </ul>
*
* @param context the current request ocntext
* @param newResourceName the name of the new resource (No pathinformation allowed)
* @param resource the resource to be imported
* @param propertyinfos a Hashtable of propertyinfos, that should be set for this folder
* The keys for this Hashtable are the names for propertydefinitions, the values are
* the values for the propertyinfos
* @param filecontent the content of the resource if it is of type file
* @return CmsResource The created resource
* @throws CmsException will be thrown for missing propertyinfos, for worng propertydefs
* or if the filename is not valid. The CmsException will also be thrown, if the
* user has not the rights for this resource.
*/
public CmsResource importResource(CmsRequestContext context, String newResourceName, CmsResource resource, byte[] filecontent, List propertyinfos) throws CmsException {
// extract folder information
String folderName = null;
String resourceName = null;
if (resource.isFolder()) {
// append I_CmsConstants.C_FOLDER_SEPARATOR if required
if (!newResourceName.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
newResourceName += I_CmsConstants.C_FOLDER_SEPARATOR;
}
// extract folder information
folderName = newResourceName.substring(0, newResourceName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR, newResourceName.length() - 2) + 1);
resourceName = newResourceName.substring(folderName.length(), newResourceName.length() - 1);
} else {
folderName = newResourceName.substring(0, newResourceName.lastIndexOf(I_CmsConstants.C_FOLDER_SEPARATOR, newResourceName.length()) + 1);
resourceName = newResourceName.substring(folderName.length(), newResourceName.length());
// check if a link to the imported resource lies in a marked site
if (labelResource(context, resource, newResourceName, 2)) {
int flags = resource.getFlags();
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
resource.setFlags(flags);
}
}
// checks, if the filename is valid, if not it throws a exception
validFilename(resourceName);
CmsFolder parentFolder = readFolder(context, folderName);
// check if the user has write access to the destination folder
checkPermissions(context, parentFolder, I_CmsConstants.C_WRITE_ACCESS);
// create a new CmsResourceObject
if (filecontent == null) {
filecontent = new byte[0];
}
// set the parent id
resource.setParentId(parentFolder.getStructureId());
// create the folder
CmsResource newResource = m_vfsDriver.importResource(context.currentProject(), parentFolder.getStructureId(), resource, filecontent, context.currentUser().getId(), resource.isFolder());
newResource.setFullResourceName(newResourceName);
filecontent = null;
clearResourceCache();
// write metainfos for the folder
m_vfsDriver.writePropertyObjects(context.currentProject(), newResource, propertyinfos);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_LIST_MODIFIED, Collections.singletonMap("resource", parentFolder)));
// return the folder
return newResource;
}
/**
* Initializes the driver and sets up all required modules and connections.<p>
*
* @param config the OpenCms configuration
* @param vfsDriver the vfsdriver
* @param userDriver the userdriver
* @param projectDriver the projectdriver
* @param workflowDriver the workflowdriver
* @param backupDriver the backupdriver
* @throws CmsException if something goes wrong
* @throws Exception if something goes wrong
*/
public void init(ExtendedProperties config, I_CmsVfsDriver vfsDriver, I_CmsUserDriver userDriver, I_CmsProjectDriver projectDriver, I_CmsWorkflowDriver workflowDriver, I_CmsBackupDriver backupDriver) throws CmsException, Exception {
// store the limited workplace port
m_limitedWorkplacePort = config.getInteger("workplace.limited.port", -1);
// initialize the access-module.
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver manager init : phase 4 - connecting to the database");
}
// store the access objects
m_vfsDriver = vfsDriver;
m_userDriver = userDriver;
m_projectDriver = projectDriver;
m_workflowDriver = workflowDriver;
m_backupDriver = backupDriver;
m_configuration = config;
// initialize the key generator
m_keyGenerator = (I_CmsCacheKey)Class.forName(config.getString(I_CmsConstants.C_CONFIGURATION_CACHE + ".keygenerator")).newInstance();
// initalize the caches
LRUMap hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".user", 50));
m_userCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_userCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".group", 50));
m_groupCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_groupCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".usergroups", 50));
m_userGroupsCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_userGroupsCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".project", 50));
m_projectCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_projectCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".resource", 2500));
m_resourceCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_resourceCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".resourcelist", 100));
m_resourceListCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_resourceListCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".property", 5000));
m_propertyCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_propertyCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".accesscontrollists", 1000));
m_accessControlListCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_accessControlListCache", hashMap);
}
hashMap = new LRUMap(config.getInteger(I_CmsConstants.C_CONFIGURATION_CACHE + ".permissions", 1000));
m_permissionCache = Collections.synchronizedMap(hashMap);
if (OpenCms.getMemoryMonitor().enabled()) {
OpenCms.getMemoryMonitor().register(this.getClass().getName()+"."+"m_permissionCache", hashMap);
}
m_refresh = config.getString(I_CmsConstants.C_CONFIGURATION_CACHE + ".refresh", "");
// initialize the registry
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Initializing registry: starting");
}
try {
m_registry = new CmsRegistry(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(config.getString(I_CmsConstants.C_CONFIGURATION_REGISTRY)));
} catch (CmsException ex) {
throw ex;
} catch (Exception ex) {
// init of registry failed - throw exception
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error(OpenCmsCore.C_MSG_CRITICAL_ERROR + "4", ex);
}
throw new CmsException("Init of registry failed", CmsException.C_REGISTRY_ERROR, ex);
}
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Initializing registry: finished");
}
getProjectDriver().fillDefaults();
// initialize the HTML link validator
m_htmlLinkValidator = new CmsHtmlLinkValidator(this);
}
/**
* Determines, if the users current group is the admin-group.<p>
*
* All users are granted.
*
* @param context the current request context
* @return true, if the users current group is the admin-group, else it returns false
* @throws CmsException if operation was not succesful
*/
public boolean isAdmin(CmsRequestContext context) throws CmsException {
return userInGroup(context, context.currentUser().getName(), OpenCms.getDefaultUsers().getGroupAdministrators());
}
/**
* Proves if a specified resource is inside the current project.<p>
*
* @param context the current request context
* @param resource the specified resource
* @return true, if the resource name of the specified resource matches any of the current project's resources
*/
public boolean isInsideCurrentProject(CmsRequestContext context, CmsResource resource) {
List projectResources = null;
try {
projectResources = readProjectResources(context.currentProject());
} catch (CmsException e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("[CmsDriverManager.isInsideProject()] error reading project resources " + e.getMessage());
}
return false;
}
return CmsProject.isInsideProject(projectResources, resource);
}
/**
*
* Proves if a resource is locked.<p>
*
* @see org.opencms.lock.CmsLockManager#isLocked(org.opencms.db.CmsDriverManager, org.opencms.file.CmsRequestContext, java.lang.String)
*
* @param context the current request context
* @param resourcename the full resource name including the site root
* @return true, if and only if the resource is currently locked
* @throws CmsException if something goes wrong
*/
public boolean isLocked(CmsRequestContext context, String resourcename) throws CmsException {
return m_lockManager.isLocked(this, context, resourcename);
}
/**
* Determines, if the users may manage a project.<p>
* Only the manager of a project may publish it.
*
* All users are granted.
*
* @param context the current request context
* @return true, if the user manage this project
* @throws CmsException Throws CmsException if operation was not succesful.
*/
public boolean isManagerOfProject(CmsRequestContext context) throws CmsException {
// is the user owner of the project?
if (context.currentUser().getId().equals(context.currentProject().getOwnerId())) {
// YES
return true;
}
if (isAdmin(context)) {
return true;
}
// get all groups of the user
Vector groups = getGroupsOfUser(context, context.currentUser().getName());
for (int i = 0; i < groups.size(); i++) {
// is this a managergroup for this project?
if (((CmsGroup)groups.elementAt(i)).getId().equals(context.currentProject().getManagerGroupId())) {
// this group is manager of the project
return true;
}
}
// this user is not manager of this project
return false;
}
/**
* Determines if the user is a member of the "Projectmanagers" group.<p>
*
* All users are granted.
*
* @param context the current request context
* @return true, if the users current group is the projectleader-group, else it returns false
* @throws CmsException if operation was not succesful
*/
public boolean isProjectManager(CmsRequestContext context) throws CmsException {
return userInGroup(context, context.currentUser().getName(), OpenCms.getDefaultUsers().getGroupProjectmanagers());
}
/**
* Checks if a project is the tempfile project.<p>
* @param project the project to test
* @return true if the project is the tempfile project
*/
public boolean isTempfileProject(CmsProject project) {
return project.getName().equals("tempFileProject");
}
/**
* Determines if the user is a member of the default users group.<p>
*
* All users are granted.
*
* @param context the current request context
* @return true, if the users current group is the projectleader-group, else it returns false
* @throws CmsException if operation was not succesful
*/
public boolean isUser(CmsRequestContext context) throws CmsException {
return userInGroup(context, context.currentUser().getName(), OpenCms.getDefaultUsers().getGroupUsers());
}
/**
* Checks if this is a valid group for webusers.<p>
*
* @param group the group to be checked
* @return true if the group does not belong to users, administrators or projectmanagers
* @throws CmsException if operation was not succesful
*/
protected boolean isWebgroup(CmsGroup group) throws CmsException {
try {
CmsUUID user = m_userDriver.readGroup(OpenCms.getDefaultUsers().getGroupUsers()).getId();
CmsUUID admin = m_userDriver.readGroup(OpenCms.getDefaultUsers().getGroupAdministrators()).getId();
CmsUUID manager = m_userDriver.readGroup(OpenCms.getDefaultUsers().getGroupProjectmanagers()).getId();
if ((group.getId().equals(user)) || (group.getId().equals(admin)) || (group.getId().equals(manager))) {
return false;
} else {
CmsUUID parentId = group.getParentId();
// check if the group belongs to Users, Administrators or Projectmanager
if (!parentId.isNullUUID()) {
// check is the parentgroup is a webgroup
return isWebgroup(m_userDriver.readGroup(parentId));
}
}
} catch (CmsException e) {
throw e;
}
return true;
}
/**
* Checks if one of the resources VFS links (except the resource itself) resides in a "labeled" site folder.<p>
*
* This method is used when creating a new sibling (use the newResource parameter & action = 1) or deleting/importing a resource (call with action = 2).<p>
*
* @param context the current request context
* @param resource the resource
* @param newResource absolute path for a resource sibling which will be created
* @param action the action which has to be performed (1 = create VFS link, 2 all other actions)
* @return true if the flag should be set for the resource, otherwise false
* @throws CmsException if something goes wrong
*/
public boolean labelResource(CmsRequestContext context, CmsResource resource, String newResource, int action) throws CmsException {
// get the list of labeled site folders from the runtime property
List labeledSites = OpenCms.getWorkplaceManager().getLabelSiteFolders();
if (action == 1) {
// CASE 1: a new resource is created, check the sites
if (!resource.isLabeled()) {
// source isn't labeled yet, so check!
boolean linkInside = false;
boolean sourceInside = false;
Iterator i = labeledSites.iterator();
while (i.hasNext()) {
String curSite = (String)i.next();
if (newResource.startsWith(curSite)) {
// the link lies in a labeled site
linkInside = true;
}
if (resource.getRootPath().startsWith(curSite)) {
// the source lies in a labeled site
sourceInside = true;
}
}
// return true when either source or link is in labeled site, otherwise false
return (linkInside != sourceInside);
}
// resource is already labeled
return false;
} else {
// CASE 2: the resource will be deleted or created (import)
// check if at least one of the other siblings resides inside a "labeled site"
// and if at least one of the other siblings resides outside a "labeled site"
boolean isInside = false;
boolean isOutside = false;
// check if one of the other vfs links lies in a labeled site folder
List vfsLinkList = m_vfsDriver.readSiblings(context.currentProject(), resource, false);
setFullResourceNames(context, vfsLinkList);
Iterator i = vfsLinkList.iterator();
while (i.hasNext() && (!isInside || !isOutside)) {
CmsResource currentResource = (CmsResource)i.next();
if (currentResource.equals(resource)) {
// dont't check the resource itself!
continue;
}
String curPath = currentResource.getRootPath();
boolean curInside = false;
for (int k = 0; k < labeledSites.size(); k++) {
if (curPath.startsWith((String)labeledSites.get(k))) {
// the link is in the labeled site
isInside = true;
curInside = true;
break;
}
}
if (!curInside) {
// the current link was not found in labeled site, so it is outside
isOutside = true;
}
}
// now check the new resource name if present
if (newResource != null) {
boolean curInside = false;
for (int k = 0; k < labeledSites.size(); k++) {
if (newResource.startsWith((String)labeledSites.get(k))) {
// the new resource is in the labeled site
isInside = true;
curInside = true;
break;
}
}
if (!curInside) {
// the new resource was not found in labeled site, so it is outside
isOutside = true;
}
}
return (isInside && isOutside);
}
}
/**
* Returns the user, who had locked the resource.<p>
*
* A user can lock a resource, so he is the only one who can write this
* resource. This methods checks, if a resource was locked.
*
* @param context the current request context
* @param resource the resource
*
* @return the user, who had locked the resource.
*
* @throws CmsException will be thrown, if the user has not the rights for this resource
*/
public CmsUser lockedBy(CmsRequestContext context, CmsResource resource) throws CmsException {
return lockedBy(context, resource.getRootPath());
}
/**
* Returns the user, who had locked the resource.<p>
*
* A user can lock a resource, so he is the only one who can write this
* resource. This methods checks, if a resource was locked.
*
* @param context the current request context
* @param resourcename the complete name of the resource
*
* @return the user, who had locked the resource.
*
* @throws CmsException will be thrown, if the user has not the rights for this resource.
*/
public CmsUser lockedBy(CmsRequestContext context, String resourcename) throws CmsException {
return readUser(m_lockManager.getLock(this, context, resourcename).getUserId());
}
/**
* Locks a resource exclusively.<p>
*
* @param context the current request context
* @param resourcename the resource name that gets locked
* @throws CmsException if something goes wrong
*/
public void lockResource(CmsRequestContext context, String resourcename) throws CmsException {
lockResource(context, resourcename, CmsLock.C_MODE_COMMON);
}
/**
* Locks a resource exclusively.<p>
*
* @param context the current request context
* @param resourcename the resource name that gets locked
* @param mode flag indicating the mode (temporary or common) of a lock
* @throws CmsException if something goes wrong
*/
public void lockResource(CmsRequestContext context, String resourcename, int mode) throws CmsException {
CmsResource resource = readFileHeader(context, resourcename);
// check if the user has write access to the resource
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
if (resource.getState() != I_CmsConstants.C_STATE_UNCHANGED) {
// update the project flag of a modified resource as "modified inside the current project"
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), resource);
}
// add the resource to the lock dispatcher
m_lockManager.addResource(this, context, resource.getRootPath(), context.currentUser().getId(), context.currentProject().getId(), mode);
// update the resource cache
clearResourceCache();
// cw/060104 we must also clear the permission cache
m_permissionCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Attempts to authenticate a user into OpenCms with the given password.<p>
*
* For security reasons, all error / exceptions that occur here are "blocked" and
* a simple security exception is thrown.<p>
*
* @param username the name of the user to be logged in
* @param password the password of the user
* @param remoteAddress the ip address of the request
* @param userType the user type to log in (System user or Web user)
* @return the logged in users name
*
* @throws CmsSecurityException if login was not succesful
*/
public CmsUser loginUser(String username, String password, String remoteAddress, int userType) throws CmsSecurityException {
CmsUser newUser;
try {
// read the user from the driver to avoid the cache
newUser = m_userDriver.readUser(username, password, remoteAddress, userType);
} catch (Throwable t) {
// any error here: throw a security exception
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED, t);
}
// check if the "enabled" flag is set for the user
if (newUser.getFlags() != I_CmsConstants.C_FLAG_ENABLED) {
// user is disabled, throw a securiy exception
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED);
}
// set the last login time to the current time
newUser.setLastlogin(System.currentTimeMillis());
try {
// write the changed user object back to the user driver
m_userDriver.writeUser(newUser);
} catch (Throwable t) {
// any error here: throw a security exception
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED, t);
}
// update cache
putUserInCache(newUser);
// invalidate all user depdent caches
m_accessControlListCache.clear();
m_groupCache.clear();
m_userGroupsCache.clear();
m_resourceListCache.clear();
m_permissionCache.clear();
// return the user object read from the driver
return newUser;
}
/**
* Lookup and read the user or group with the given UUID.<p>
*
* @param principalId the UUID of the principal to lookup
* @return the principal (group or user) if found, otherwise null
*/
public I_CmsPrincipal lookupPrincipal(CmsUUID principalId) {
try {
CmsGroup group = m_userDriver.readGroup(principalId);
if (group != null) {
return (I_CmsPrincipal)group;
}
} catch (Exception e) {
// ignore this exception
}
try {
CmsUser user = readUser(principalId);
if (user != null) {
return (I_CmsPrincipal)user;
}
} catch (Exception e) {
// ignore this exception
}
return null;
}
/**
* Lookup and read the user or group with the given name.<p>
*
* @param principalName the name of the principal to lookup
* @return the principal (group or user) if found, otherwise null
*/
public I_CmsPrincipal lookupPrincipal(String principalName) {
try {
CmsGroup group = m_userDriver.readGroup(principalName);
if (group != null) {
return (I_CmsPrincipal)group;
}
} catch (Exception e) {
// ignore this exception
}
try {
CmsUser user = readUser(principalName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
if (user != null) {
return (I_CmsPrincipal)user;
}
} catch (Exception e) {
// ignore this exception
}
return null;
}
/**
* Moves the file.<p>
*
* This operation includes a copy and a delete operation. These operations
* are done with their security-checks.
*
* @param context the current request context
* @param sourceName the complete name of the sourcefile
* @param destinationName The complete m_path of the destinationfile
*
* @throws CmsException will be thrown, if the file couldn't be moved.
* The CmsException will also be thrown, if the user has not the rights
* for this resource.
*/
public void moveResource(CmsRequestContext context, String sourceName, String destinationName) throws CmsException {
// read the source file
CmsResource source = readFileHeader(context, sourceName);
if (source.isFile()) {
// file is copied as link
copyFile(context, sourceName, destinationName, true, true, I_CmsConstants.C_COPY_AS_SIBLING);
deleteFile(context, sourceName, I_CmsConstants.C_DELETE_OPTION_PRESERVE_SIBLINGS);
} else {
// folder is copied as link
copyFolder(context, sourceName, destinationName, true, true);
deleteFolder(context, sourceName);
}
// read the moved file
CmsResource destination = readFileHeader(context, destinationName);
// since the resource was copied as link, we have to update the date/user lastmodified
// its sufficient to use source instead of dest, since there is only one resource
destination.setDateLastModified(System.currentTimeMillis());
destination.setUserLastModified(context.currentUser().getId());
m_vfsDriver.writeResourceState(context.currentProject(), destination, C_UPDATE_STRUCTURE);
// lock the new resource
lockResource(context, destinationName);
/*
List modifiedResources = (List) new ArrayList();
modifiedResources.add(source);
modifiedResources.add(destination);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCES_MODIFIED, Collections.singletonMap("resources", modifiedResources)));
*/
}
/**
* Gets a new driver instance.<p>
*
* @param configuration the configurations
* @param driverName the driver name
* @param successiveDrivers the list of successive drivers
* @return the driver object
* @throws CmsException if something goes wrong
*/
public Object newDriverInstance(ExtendedProperties configuration, String driverName, List successiveDrivers) throws CmsException {
Class initParamClasses[] = {ExtendedProperties.class, List.class, CmsDriverManager.class };
Object initParams[] = {configuration, successiveDrivers, this };
Class driverClass = null;
Object driver = null;
try {
// try to get the class
driverClass = Class.forName(driverName);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : starting " + driverName);
}
// try to create a instance
driver = driverClass.newInstance();
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : initializing " + driverName);
}
// invoke the init-method of this access class
driver.getClass().getMethod("init", initParamClasses).invoke(driver, initParams);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : ok, finished");
}
} catch (Exception exc) {
String message = "Critical error while initializing " + driverName;
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("[CmsDriverManager] " + message);
}
exc.printStackTrace(System.err);
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
return driver;
}
/**
* Method to create a new instance of a driver.<p>
*
* @param configuration the configurations from the propertyfile
* @param driverName the class name of the driver
* @param driverPoolUrl the pool url for the driver
* @return an initialized instance of the driver
* @throws CmsException if something goes wrong
*/
public Object newDriverInstance(ExtendedProperties configuration, String driverName, String driverPoolUrl) throws CmsException {
Class initParamClasses[] = {ExtendedProperties.class, String.class, CmsDriverManager.class };
Object initParams[] = {configuration, driverPoolUrl, this };
Class driverClass = null;
Object driver = null;
try {
// try to get the class
driverClass = Class.forName(driverName);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : starting " + driverName);
}
// try to create a instance
driver = driverClass.newInstance();
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : initializing " + driverName);
}
// invoke the init-method of this access class
driver.getClass().getMethod("init", initParamClasses).invoke(driver, initParams);
if (OpenCms.getLog(CmsLog.CHANNEL_INIT).isInfoEnabled()) {
OpenCms.getLog(CmsLog.CHANNEL_INIT).info(". Driver init : finished, assigned pool " + driverPoolUrl);
}
} catch (Exception exc) {
String message = "Critical error while initializing " + driverName;
if (OpenCms.getLog(this).isFatalEnabled()) {
OpenCms.getLog(this).fatal(message, exc);
}
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
return driver;
}
/**
* Method to create a new instance of a pool.<p>
*
* @param configurations the configurations from the propertyfile
* @param poolName the configuration name of the pool
* @return the pool url
* @throws CmsException if something goes wrong
*/
public String newPoolInstance(ExtendedProperties configurations, String poolName) throws CmsException {
String poolUrl = null;
try {
poolUrl = CmsDbPool.createDriverManagerConnectionPool(configurations, poolName);
} catch (Exception exc) {
String message = "Critical error while initializing resource pool " + poolName;
if (OpenCms.getLog(this).isFatalEnabled()) {
OpenCms.getLog(this).fatal(message, exc);
}
throw new CmsException(message, CmsException.C_RB_INIT_ERROR, exc);
}
return poolUrl;
}
/**
* Returns the online project object.<p>
*
* @return the online project object
* @throws CmsException if something goes wrong
*
* @deprecated use readProject(I_CmsConstants.C_PROJECT_ONLINE_ID) instead
*/
public CmsProject onlineProject() throws CmsException {
return readProject(I_CmsConstants.C_PROJECT_ONLINE_ID);
}
/**
* Publishes a project.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param cms the current CmsObject
* @param context the current request context
* @param report a report object to provide the loggin messages
* @param publishList a Cms publish list
* @throws Exception if something goes wrong
* @see #getPublishList(CmsRequestContext, CmsResource, boolean, I_CmsReport)
*/
public synchronized void publishProject(CmsObject cms, CmsRequestContext context, CmsPublishList publishList, I_CmsReport report) throws Exception {
Vector changedResources = new Vector();
Vector changedModuleMasters = new Vector();
int publishProjectId = context.currentProject().getId();
boolean backupEnabled = OpenCms.getSystemInfo().isVersionHistoryEnabled();
int tagId = 0;
CmsResource directPublishResource = null;
// boolean flag whether the current user has permissions to publish the current project/direct published resource
boolean hasPublishPermissions = false;
// to publish a project/resource...
// the current user either has to be a member of the administrators group
hasPublishPermissions |= isAdmin(context);
// or he has to be a member of the project managers group
hasPublishPermissions |= isManagerOfProject(context);
if (publishList.isDirectPublish()) {
directPublishResource = readFileHeader(context, publishList.getDirectPublishResourceName(), true);
// or he has the explicit permission to direct publish a resource
hasPublishPermissions |= hasPermissions(context, directPublishResource, I_CmsConstants.C_DIRECT_PUBLISH, false);
}
// and the current project must be different from the online project
hasPublishPermissions &= (publishProjectId != I_CmsConstants.C_PROJECT_ONLINE_ID);
// and the project flags have to be set to zero
hasPublishPermissions &= (context.currentProject().getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED);
if (hasPublishPermissions) {
try {
if (backupEnabled) {
tagId = getBackupTagId();
} else {
tagId = 0;
}
int maxVersions = OpenCms.getSystemInfo().getVersionHistoryMaxCount();
// if we direct publish a file, check if all parent folders are already published
if (publishList.isDirectPublish()) {
CmsUUID parentID = publishList.getDirectPublishParentStructureId();
try {
getVfsDriver().readFolder(I_CmsConstants.C_PROJECT_ONLINE_ID, parentID);
} catch (CmsException e) {
report.println("Parent folder not published for resource " + publishList.getDirectPublishResourceName(), I_CmsReport.C_FORMAT_ERROR);
return;
}
}
m_projectDriver.publishProject(context, report, readProject(I_CmsConstants.C_PROJECT_ONLINE_ID), publishList, OpenCms.getSystemInfo().isVersionHistoryEnabled(), tagId, maxVersions);
// don't publish COS module data if a file/folder gets published directly
if (!publishList.isDirectPublish()) {
// now publish the module masters
Vector publishModules = new Vector();
cms.getRegistry().getModulePublishables(publishModules, null);
long publishDate = System.currentTimeMillis();
if (backupEnabled) {
try {
publishDate = m_backupDriver.readBackupProject(tagId).getPublishingDate();
} catch (CmsException e) {
// nothing to do
}
if (publishDate == 0) {
publishDate = System.currentTimeMillis();
}
}
for (int i = 0; i < publishModules.size(); i++) {
// call the publishProject method of the class with parameters:
// cms, m_enableHistory, project_id, version_id, publishDate, subId,
// the vector changedResources and the vector changedModuleMasters
try {
// The changed masters are added to the vector changedModuleMasters, so after the last module
// was published the vector contains the changed masters of all published modules
Class.forName((String) publishModules.elementAt(i)).getMethod("publishProject", new Class[] {CmsObject.class, Boolean.class, Integer.class, Integer.class, Long.class, Vector.class, Vector.class}).invoke(null, new Object[] {cms, new Boolean(OpenCms.getSystemInfo().isVersionHistoryEnabled()), new Integer(publishProjectId), new Integer(tagId), new Long(publishDate), changedResources, changedModuleMasters});
} catch (ClassNotFoundException ec) {
report.println(report.key("report.publish_class_for_module_does_not_exist_1") + (String) publishModules.elementAt(i) + report.key("report.publish_class_for_module_does_not_exist_2"), I_CmsReport.C_FORMAT_WARNING);
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error calling publish class of module " + (String) publishModules.elementAt(i), ec);
}
} catch (Exception ex) {
report.println(ex);
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error while publishing data of module " + (String) publishModules.elementAt(i), ex);
}
}
}
Iterator i = changedModuleMasters.iterator();
while (i.hasNext()) {
CmsPublishedResource currentCosResource = (CmsPublishedResource) i.next();
m_projectDriver.writePublishHistory(context.currentProject(), publishList.getPublishHistoryId(), tagId, currentCosResource.getContentDefinitionName(), currentCosResource.getMasterId(), currentCosResource.getType(), currentCosResource.getState());
}
}
} catch (CmsException e) {
throw e;
} finally {
this.clearResourceCache();
// the project was stored in the backuptables for history
//new projectmechanism: the project can be still used after publishing
// it will be deleted if the project_flag = C_PROJECT_STATE_TEMP
if (context.currentProject().getType() == I_CmsConstants.C_PROJECT_TYPE_TEMPORARY) {
m_projectDriver.deleteProject(context.currentProject());
try {
m_projectCache.remove(new Integer(publishProjectId));
} catch (Exception e) {
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn("Could not remove project " + publishProjectId + " from cache");
}
}
if (publishProjectId == context.currentProject().getId()) {
cms.getRequestContext().setCurrentProject(cms.readProject(I_CmsConstants.C_PROJECT_ONLINE_ID));
}
}
// finally set the refresh signal to another server if necessary
if (m_refresh.length() > 0) {
try {
URL url = new URL(m_refresh);
URLConnection con = url.openConnection();
con.connect();
InputStream in = con.getInputStream();
in.close();
//System.err.println(in.toString());
} catch (Exception ex) {
throw new CmsException(0, ex);
}
}
}
} else if (publishProjectId == I_CmsConstants.C_PROJECT_ONLINE_ID) {
throw new CmsSecurityException("[" + getClass().getName() + "] could not publish project " + publishProjectId, CmsSecurityException.C_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT);
} else if (!isAdmin(context) && !isManagerOfProject(context)) {
throw new CmsSecurityException("[" + getClass().getName() + "] could not publish project " + publishProjectId, CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
} else {
throw new CmsSecurityException("[" + getClass().getName() + "] could not publish project " + publishProjectId, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Stores a user in the user cache.<p>
*
* @param user the user to be stored in the cache
*/
private void putUserInCache(CmsUser user) {
m_userCache.put(getUserCacheKey(user.getName(), user.getType()), user);
m_userCache.put(getUserCacheKey(user.getId()), user);
}
/**
* Reads an access control entry from the cms.<p>
*
* The access control entries of a resource are readable by everyone.
*
* @param context the current request context
* @param resource the resource
* @param principal the id of a group or a user any other entity
* @return an access control entry that defines the permissions of the entity for the given resource
* @throws CmsException if something goes wrong
*/
public CmsAccessControlEntry readAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsUUID principal) throws CmsException {
return m_userDriver.readAccessControlEntry(context.currentProject(), resource.getResourceId(), principal);
}
/**
* Reads the agent of a task from the OpenCms.<p>
*
* @param task the task to read the agent from
* @return the owner of a task
* @throws CmsException if something goes wrong
*/
public CmsUser readAgent(CmsTask task) throws CmsException {
return readUser(task.getAgentUser());
}
/**
* Reads all file headers of a file in the OpenCms.<p>
*
* This method returns a vector with the histroy of all file headers, i.e.
* the file headers of a file, independent of the project they were attached to.<br>
* The reading excludes the filecontent.
* Access is granted, if:
* <ul>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @return vector of file headers read from the Cms
* @throws CmsException if operation was not succesful
*/
public List readAllBackupFileHeaders(CmsRequestContext context, String filename) throws CmsException {
CmsResource cmsFile = readFileHeader(context, filename);
// check if the user has read access
checkPermissions(context, cmsFile, I_CmsConstants.C_READ_ACCESS);
// access to all subfolders was granted - return the file-history (newest version first)
List backupFileHeaders = m_backupDriver.readBackupFileHeaders(cmsFile.getResourceId());
if (backupFileHeaders != null && backupFileHeaders.size() > 1) {
// change the order of the list
Collections.reverse(backupFileHeaders);
}
setFullResourceNames(context, backupFileHeaders);
return backupFileHeaders;
}
/**
* Select all projectResources from an given project.<p>
*
* @param context the current request context
* @param projectId the project in which the resource is used
* @return vector of all resources in the project
* @throws CmsException if operation was not succesful
*/
public Vector readAllProjectResources(CmsRequestContext context, int projectId) throws CmsException {
CmsProject project = m_projectDriver.readProject(projectId);
List result = setFullResourceNames(context, m_projectDriver.readProjectResources(project));
return new Vector(result);
}
/**
* Reads all property definitions of a given resourcetype.<p>
*
* @param context the current request context
* @param resourceType the resource type to read all property defnitions from
* @return vector of property defintions
* @throws CmsException if operation was not succesful
*/
private Vector readAllPropertydefinitions(CmsRequestContext context, I_CmsResourceType resourceType) throws CmsException {
Vector returnValue = m_vfsDriver.readPropertyDefinitions(context.currentProject().getId(), resourceType);
Collections.sort(returnValue);
return returnValue;
}
/**
* Reads all propertydefinitions for the given resource type.<p>
*
* All users are granted.
*
* @param context the current request context
* @param resourceType te resource type to read the propertydefinitions for
* @return propertydefinitions a Vector with propertydefefinitions for the resource type. The Vector is maybe empty.
* @throws CmsException if something goes wrong
*/
public Vector readAllPropertydefinitions(CmsRequestContext context, int resourceType) throws CmsException {
I_CmsResourceType resType = getResourceType(resourceType);
return readAllPropertydefinitions(context, resType);
}
/**
* Reads all propertydefinitions for the given resource type.<p>
*
* All users are granted.
*
* @param context the current request context
* @param resourcetype the name of the resource type to read the propertydefinitions for
* @return propertydefinitions a Vector with propertydefefinitions for the resource type. The Vector is maybe empty.
* @throws CmsException if something goes wrong.
*/
public Vector readAllPropertydefinitions(CmsRequestContext context, String resourcetype) throws CmsException {
I_CmsResourceType resType = getResourceType(resourcetype);
return readAllPropertydefinitions(context, resType);
}
/**
* Reads all sub-resources (including deleted resources) of a specified folder
* by traversing the sub-tree in a depth first search.<p>
*
* The specified folder is not included in the result list.
*
* @param context the current request context
* @param resourcename the resource name
* @param resourceType <0 if files and folders should be read, 0 if only folders should be read, >0 if only files should be read
* @return a list with all sub-resources
* @throws CmsException if something goes wrong
*/
public List readAllSubResourcesInDfs(CmsRequestContext context, String resourcename, int resourceType) throws CmsException {
List result = (List)new ArrayList();
Vector unvisited = new Vector();
CmsFolder currentFolder = null;
Enumeration unvisitedFolders = null;
boolean isFirst = true;
currentFolder = readFolder(context, resourcename, true);
unvisited.add(currentFolder);
while (unvisited.size() > 0) {
// visit all unvisited folders
unvisitedFolders = unvisited.elements();
while (unvisitedFolders.hasMoreElements()) {
currentFolder = (CmsFolder)unvisitedFolders.nextElement();
// remove the current folder from the list of unvisited folders
unvisited.remove(currentFolder);
if (!isFirst && resourceType <= CmsResourceTypeFolder.C_RESOURCE_TYPE_ID) {
// add the current folder to the result list
result.add(currentFolder);
}
if (resourceType != CmsResourceTypeFolder.C_RESOURCE_TYPE_ID) {
// add all sub-files in the current folder to the result list
result.addAll(getSubFiles(context, currentFolder.getRootPath(), true));
}
// add all sub-folders in the current folder to the list of unvisited folders
// to visit them in the next iteration
unvisited.addAll(getSubFolders(context, currentFolder.getRootPath(), true));
if (isFirst) {
isFirst = false;
}
}
}
// TODO the calculated resource list should be cached
return result;
}
/**
* Reads a file from the history of the Cms.<p>
*
* The reading includes the filecontent. <
* A file is read from the backup resources.
*
* @param context the current request context
* @param tagId the id of the tag of the file
* @param filename the name of the file to be read
* @return the file read from the Cms.
* @throws CmsException if operation was not succesful
*/
public CmsBackupResource readBackupFile(CmsRequestContext context, int tagId, String filename) throws CmsException {
CmsBackupResource backupResource = null;
try {
List path = readPath(context, filename, false);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
backupResource = m_backupDriver.readBackupFile(tagId, resource.getResourceId());
backupResource.setFullResourceName(filename);
} catch (CmsException exc) {
throw exc;
}
updateContextDates(context, backupResource);
return backupResource;
}
/**
* Reads a file header from the history of the Cms.<p>
*
* The reading excludes the filecontent.
* A file header is read from the backup resources.
*
* @param context the current request context
* @param tagId the id of the tag revisiton of the file
* @param filename the name of the file to be read
* @return the file read from the Cms.
* @throws CmsException if operation was not succesful
*/
public CmsBackupResource readBackupFileHeader(CmsRequestContext context, int tagId, String filename) throws CmsException {
CmsResource cmsFile = readFileHeader(context, filename);
CmsBackupResource resource = null;
try {
resource = m_backupDriver.readBackupFileHeader(tagId, cmsFile.getResourceId());
resource.setFullResourceName(filename);
} catch (CmsException exc) {
throw exc;
}
updateContextDates(context, resource);
return resource;
}
/**
* Reads the backupinformation of a project from the Cms.<p>
*
* @param tagId the tagId of the project
* @return the backup project
* @throws CmsException if something goes wrong
*/
public CmsBackupProject readBackupProject(int tagId) throws CmsException {
return m_backupDriver.readBackupProject(tagId);
}
/**
* Reads all resources that are inside and changed in a specified project.<p>
*
* @param context the current request context
* @param projectId the ID of the project
* @param resourceType <0 if files and folders should be read, 0 if only folders should be read, >0 if only files should be read
* @return a List with all resources inside the specified project
* @throws CmsException if somethong goes wrong
*/
public List readChangedResourcesInsideProject(CmsRequestContext context, int projectId, int resourceType) throws CmsException {
List projectResources = readProjectResources(readProject(projectId));
List result = (List)new ArrayList();
String currentProjectResource = null;
List resources = (List)new ArrayList();
CmsResource currentResource = null;
CmsLock currentLock = null;
for (int i = 0; i < projectResources.size(); i++) {
// read all resources that are inside the project by visiting each project resource
currentProjectResource = (String)projectResources.get(i);
try {
currentResource = readFileHeader(context, currentProjectResource, true);
if (currentResource.isFolder()) {
resources.addAll(readAllSubResourcesInDfs(context, currentProjectResource, resourceType));
} else {
resources.add(currentResource);
}
} catch (CmsException e) {
// the project resource probably doesnt exist (anymore)...
if (e.getType() != CmsException.C_NOT_FOUND) {
throw e;
}
}
}
for (int j = 0; j < resources.size(); j++) {
currentResource = (CmsResource)resources.get(j);
currentLock = getLock(context, currentResource.getRootPath());
if (currentResource.getState() != I_CmsConstants.C_STATE_UNCHANGED) {
if ((currentLock.isNullLock() && currentResource.getProjectLastModified() == projectId) || (currentLock.getUserId().equals(context.currentUser().getId()) && currentLock.getProjectId() == projectId)) {
// add only resources that are
// - inside the project,
// - changed in the project,
// - either unlocked, or locked for the current user in the project
result.add(currentResource);
}
}
}
resources.clear();
resources = null;
// TODO the calculated resource lists should be cached
return result;
}
/**
* Gets the Crontable.<p>
*
* All users are garnted.
*
* @return the crontable
* @throws CmsException if something goes wrong
*/
public String readCronTable() throws CmsException {
String retValue = (String)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_CRONTABLE);
if (retValue == null) {
return "";
} else {
return retValue;
}
}
/**
* Reads a file from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @return the file read from the VFS
* @throws CmsException if operation was not succesful
*/
public CmsFile readFile(CmsRequestContext context, String filename) throws CmsException {
return readFile(context, filename, false);
}
/**
* Reads a file from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @param includeDeleted flag to include deleted resources
* @return the file read from the VFS
* @throws CmsException if operation was not succesful
*/
public CmsFile readFile(CmsRequestContext context, String filename, boolean includeDeleted) throws CmsException {
CmsFile file = null;
try {
List path = readPath(context, filename, false);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
file = m_vfsDriver.readFile(context.currentProject().getId(), includeDeleted, resource.getStructureId());
if (file.isFolder() && (filename.charAt(filename.length() - 1) != '/')) {
filename += "/";
}
file.setFullResourceName(filename);
} catch (CmsException exc) {
// the resource was not readable
throw exc;
}
// check if the user has read access to the file
checkPermissions(context, file, I_CmsConstants.C_READ_ACCESS);
// update date info in context
updateContextDates(context, file);
// access to all subfolders was granted - return the file.
return file;
}
/**
* Gets the known file extensions (=suffixes).<p>
*
* All users are granted access.<p>
*
* @return Hashtable with file extensions as Strings
* @throws CmsException if operation was not succesful
*/
public Hashtable readFileExtensions() throws CmsException {
Hashtable res = (Hashtable)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS);
return ((res != null) ? res : new Hashtable());
}
/**
* Reads a file header from the Cms.<p>
*
* The reading excludes the filecontent.
* A file header can be read from an offline project or the online project.
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @return the file read from the Cms
* @throws CmsException if operation was not succesful
*/
public CmsResource readFileHeader(CmsRequestContext context, String filename) throws CmsException {
return readFileHeader(context, filename, false);
}
/**
* Reads a file header of another project of the Cms.<p>
*
* The reading excludes the filecontent.
* A file header can be read from an offline project or the online project.
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param projectId the id of the project to read the file from
* @param filename the name of the file to be read
* @param includeDeleted flag to include the deleted resources
* @return the file read from the Cms
* @throws CmsException if operation was not succesful
*/
public CmsResource readFileHeaderInProject(int projectId, String filename, boolean includeDeleted) throws CmsException {
if (filename == null) {
return null;
}
if (CmsResource.isFolder(filename)) {
return readFolderInProject(projectId, filename);
}
List path = readPathInProject(projectId, filename, includeDeleted);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
List projectResources = readProjectResources(readProject(projectId));
// set full resource name
resource.setFullResourceName(filename);
if (CmsProject.isInsideProject(projectResources, resource)) {
return resource;
}
throw new CmsResourceNotFoundException("File " + filename + " is not inside project with ID " + projectId);
}
/**
* Reads a file from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
* @param context the context (user/project) of this request
* @param projectId the id of the project to read the file from
* @param structureId the structure id of the file
* @param includeDeleted already deleted resources are found, too
* @return the file read from the VFS
* @throws CmsException if operation was not succesful
*/
public CmsFile readFileInProject(CmsRequestContext context, int projectId, CmsUUID structureId, boolean includeDeleted) throws CmsException {
CmsFile cmsFile = null;
try {
cmsFile = m_vfsDriver.readFile(projectId, includeDeleted, structureId);
cmsFile.setFullResourceName(readPathInProject(projectId, cmsFile, includeDeleted));
} catch (CmsException exc) {
// the resource was not readable
throw exc;
}
// check if the user has read access to the file
checkPermissions(context, cmsFile, I_CmsConstants.C_READ_ACCESS);
// access to all subfolders was granted - return the file.
return cmsFile;
}
/**
* Reads all files from the Cms, that are of the given type.<p>
*
* @param context the context (user/project) of this request
* @param projectId A project id for reading online or offline resources
* @param resourcetype the type of the files
* @return a Vector of files
* @throws CmsException if operation was not succesful
*/
public Vector readFilesByType(CmsRequestContext context, int projectId, int resourcetype) throws CmsException {
Vector resources = new Vector();
resources = m_vfsDriver.readFiles(projectId, resourcetype);
Vector retValue = new Vector(resources.size());
// check if the user has view access
Enumeration e = resources.elements();
while (e.hasMoreElements()) {
CmsFile res = (CmsFile)e.nextElement();
if (hasPermissions(context, res, I_CmsConstants.C_VIEW_ACCESS, false)) {
res.setFullResourceName(readPath(context, res, true));
retValue.addElement(res);
updateContextDates(context, res);
}
}
return retValue;
}
/**
* Reads a folder from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param folderId the id of the folder to be read
* @param includeDeleted include the folder it it is marked as deleted
* @return folder the read folder.
* @throws CmsException if the folder couldn't be read. The CmsException will also be thrown, if the user has not the rights for this resource.
*/
public CmsFolder readFolder(CmsRequestContext context, CmsUUID folderId, boolean includeDeleted) throws CmsException {
CmsFolder folder = null;
try {
folder = m_vfsDriver.readFolder(context.currentProject().getId(), folderId);
folder.setFullResourceName(readPath(context, folder, includeDeleted));
} catch (CmsException exc) {
throw exc;
}
// check if the user has write access to the folder
checkPermissions(context, folder, I_CmsConstants.C_READ_ACCESS);
// update date info in context
updateContextDates(context, folder);
// access was granted - return the folder.
if ((folder.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted)) {
throw new CmsException("[" + getClass().getName() + "]" + context.removeSiteRoot(readPath(context, folder, includeDeleted)), CmsException.C_RESOURCE_DELETED);
} else {
return folder;
}
}
/**
* Reads a folder from the Cms.<p>
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param foldername the complete m_path of the folder to be read
* @return folder the read folder
* @throws CmsException if the folder couldn't be read. The CmsException will also be thrown, if the user has not the rights for this resource.
*/
public CmsFolder readFolder(CmsRequestContext context, String foldername) throws CmsException {
return readFolder(context, foldername, false);
}
/**
* Reads a file header from the Cms.<p>
*
* The reading excludes the filecontent.
* A file header can be read from an offline project or the online project.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param filename the name of the file to be read
* @param includeDeleted flag to include the deleted resources
* @return the file read from the Cms
* @throws CmsException if operation was not succesful
*/
public CmsResource readFileHeader(CmsRequestContext context, String filename, boolean includeDeleted) throws CmsException {
List path = readPath(context, filename, includeDeleted);
CmsResource resource = (CmsResource)path.get(path.size() - 1);
// check if the user has read access to the file
checkPermissions(context, resource, I_CmsConstants.C_READ_OR_VIEW_ACCESS);
// set full resource name
if (resource.isFolder()) {
if ((resource.getState() == I_CmsConstants.C_STATE_DELETED) && (!includeDeleted)) {
// resource was deleted
throw new CmsException("[" + this.getClass().getName() + "]" + context.removeSiteRoot(readPath(context, resource, includeDeleted)), CmsException.C_RESOURCE_DELETED);
}
// resource.setFullResourceName(filename + I_CmsConstants.C_FOLDER_SEPARATOR);
resource = new CmsFolder(resource);
resource.setFullResourceName(filename);
} else {
resource.setFullResourceName(filename);
}
// update date info in context
updateContextDates(context, resource);
// access was granted - return the file-header.
return resource;
}
/**
* Reads a folder from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param context the current request context
* @param foldername the complete m_path of the folder to be read
* @param includeDeleted include the folder it it is marked as deleted
* @return folder the read folder
* @throws CmsException if the folder couldn't be read. The CmsException will also be thrown, if the user has not the rights for this resource.
*/
public CmsFolder readFolder(CmsRequestContext context, String foldername, boolean includeDeleted) throws CmsException {
return (CmsFolder)readFileHeader(context, foldername, includeDeleted);
}
/**
* Reads a folder from the Cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can read the resource</li>
* </ul>
*
* @param projectId the project to read the folder from
* @param foldername the complete m_path of the folder to be read
* @return folder the read folder.
* @throws CmsException if the folder couldn't be read. The CmsException will also be thrown, if the user has not the rights for this resource
*/
protected CmsFolder readFolderInProject(int projectId, String foldername) throws CmsException {
if (foldername == null) {
return null;
}
if (!CmsResource.isFolder(foldername)) {
foldername += "/";
}
List path = readPathInProject(projectId, foldername, false);
CmsFolder folder = (CmsFolder)path.get(path.size() - 1);
List projectResources = readProjectResources(readProject(projectId));
// now set the full resource name
folder.setFullResourceName(foldername);
if (CmsProject.isInsideProject(projectResources, folder)) {
return folder;
}
throw new CmsResourceNotFoundException("Folder " + foldername + " is not inside project with ID " + projectId);
}
/**
* Reads all given tasks from a user for a project.<p>
*
* @param projectId the id of the Project in which the tasks are defined
* @param ownerName owner of the task
* @param taskType task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW.
* @param orderBy chooses, how to order the tasks
* @param sort sorting of the tasks
* @return vector of tasks
* @throws CmsException if something goes wrong
*/
public Vector readGivenTasks(int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException {
CmsProject project = null;
CmsUser owner = null;
if (ownerName != null) {
owner = readUser(ownerName);
}
if (projectId != I_CmsConstants.C_UNKNOWN_ID) {
project = readProject(projectId);
}
return m_workflowDriver.readTasks(project, null, owner, null, taskType, orderBy, sort);
}
/**
* Reads the group of a project from the OpenCms.<p>
*
* @param project the project to read from
* @return the group of a resource
*/
public CmsGroup readGroup(CmsProject project) {
// try to read group form cache
CmsGroup group = (CmsGroup)m_groupCache.get(new CacheId(project.getGroupId()));
if (group == null) {
try {
group = m_userDriver.readGroup(project.getGroupId());
} catch (CmsException exc) {
if (exc.getType() == CmsException.C_NO_GROUP) {
// the group does not exist any more - return a dummy-group
return new CmsGroup(CmsUUID.getNullUUID(), CmsUUID.getNullUUID(), project.getGroupId() + "", "deleted group", 0);
}
}
m_groupCache.put(new CacheId(group), group);
}
return group;
}
/**
* Reads the group (role) of a task from the OpenCms.<p>
*
* @param task the task to read from
* @return the group of a resource
* @throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(CmsTask task) throws CmsException {
return m_userDriver.readGroup(task.getRole());
}
/**
* Returns a group object.<p>
*
* @param groupname the name of the group that is to be read
* @return the requested group
* @throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(String groupname) throws CmsException {
CmsGroup group = null;
// try to read group form cache
group = (CmsGroup)m_groupCache.get(new CacheId(groupname));
if (group == null) {
group = m_userDriver.readGroup(groupname);
m_groupCache.put(new CacheId(group), group);
}
return group;
}
/**
* Returns a group object.<p>
*
* All users are granted.
*
* @param groupId the id of the group that is to be read
* @return the requested group
* @throws CmsException if operation was not succesful
*/
public CmsGroup readGroup(CmsUUID groupId) throws CmsException {
return m_userDriver.readGroup(groupId);
}
/**
* Gets the Linkchecktable.<p>
*
* All users are garnted
*
* @return the linkchecktable.
* @throws CmsException if operation was not succesful
*/
public Hashtable readLinkCheckTable() throws CmsException {
Hashtable retValue = (Hashtable)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_LINKCHECKTABLE);
if (retValue == null) {
return new Hashtable();
} else {
return retValue;
}
}
/**
* Reads the manager group of a project from the OpenCms.<p>
*
* All users are granted.
*
* @param project the project to read from
* @return the group of a resource
*/
public CmsGroup readManagerGroup(CmsProject project) {
CmsGroup group = null;
// try to read group form cache
group = (CmsGroup)m_groupCache.get(new CacheId(project.getManagerGroupId()));
if (group == null) {
try {
group = m_userDriver.readGroup(project.getManagerGroupId());
} catch (CmsException exc) {
if (exc.getType() == CmsException.C_NO_GROUP) {
// the group does not exist any more - return a dummy-group
return new CmsGroup(CmsUUID.getNullUUID(), CmsUUID.getNullUUID(), project.getManagerGroupId() + "", "deleted group", 0);
}
}
m_groupCache.put(new CacheId(group), group);
}
return group;
}
/**
* Reads the original agent of a task from the OpenCms.<p>
*
* @param task the task to read the original agent from
* @return the owner of a task
* @throws CmsException if something goes wrong
*/
public CmsUser readOriginalAgent(CmsTask task) throws CmsException {
return readUser(task.getOriginalUser());
}
/**
* Reads the owner of a project from the OpenCms.<p>
*
* @param project the project to get the owner from
* @return the owner of a resource
* @throws CmsException if something goes wrong
*/
public CmsUser readOwner(CmsProject project) throws CmsException {
return readUser(project.getOwnerId());
}
/**
* Reads the owner (initiator) of a task from the OpenCms.<p>
*
* @param task the task to read the owner from
* @return the owner of a task
* @throws CmsException if something goes wrong
*/
public CmsUser readOwner(CmsTask task) throws CmsException {
return readUser(task.getInitiatorUser());
}
/**
* Reads the owner of a tasklog from the OpenCms.<p>
*
* @param log the tasklog
* @return the owner of a resource
* @throws CmsException if something goes wrong
*/
public CmsUser readOwner(CmsTaskLog log) throws CmsException {
return readUser(log.getUser());
}
/**
* Reads the package path of the system.<p>
* This path is used for db-export and db-import and all module packages.
*
* @return the package path
* @throws CmsException if operation was not successful
*/
public String readPackagePath() throws CmsException {
return (String)m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_PACKAGEPATH);
}
/**
* Builds the path for a given CmsResource including the site root, e.g. <code>/default/vfs/some_folder/index.html</code>.<p>
*
* This is done by climbing up the path to the root folder by using the resource parent-ID's.
* Use this method with caution! Results are cached but reading path's increases runtime costs.
*
* @param context the context (user/project) of the request
* @param resource the resource
* @param includeDeleted include resources that are marked as deleted
* @return String the path of the resource
* @throws CmsException if something goes wrong
*/
public String readPath(CmsRequestContext context, CmsResource resource, boolean includeDeleted) throws CmsException {
return readPathInProject(context.currentProject().getId(), resource, includeDeleted);
}
/**
* Builds a list of resources for a given path.<p>
*
* Use this method if you want to select a resource given by it's full filename and path.
* This is done by climbing down the path from the root folder using the parent-ID's and
* resource names. Use this method with caution! Results are cached but reading path's
* inevitably increases runtime costs.
*
* @param context the context (user/project) of the request
* @param path the requested path
* @param includeDeleted include resources that are marked as deleted
* @return List of CmsResource's
* @throws CmsException if something goes wrong
*/
public List readPath(CmsRequestContext context, String path, boolean includeDeleted) throws CmsException {
return readPathInProject(context.currentProject().getId(), path, includeDeleted);
}
/**
* Builds the path for a given CmsResource including the site root, e.g. <code>/default/vfs/some_folder/index.html</code>.<p>
*
* This is done by climbing up the path to the root folder by using the resource parent-ID's.
* Use this method with caution! Results are cached but reading path's increases runtime costs.<p>
*
* @param projectId the project to lookup the resource
* @param resource the resource
* @param includeDeleted include resources that are marked as deleted
* @return String the path of the resource
* @throws CmsException if something goes wrong
*/
public String readPathInProject(int projectId, CmsResource resource, boolean includeDeleted) throws CmsException {
if (resource.hasFullResourceName()) {
// we did already what we want to do- no further operations required here!
return resource.getRootPath();
}
// the current resource
CmsResource currentResource = resource;
// the path of an already cached parent-ID
String cachedPath = null;
// the current path
String path = "";
// the current parent-ID
CmsUUID currentParentId = null;
// the initial parent-ID is used as a cache key
CmsUUID parentId = currentResource.getParentStructureId();
// key to get a cached parent resource
String resourceCacheKey = null;
// key to get a cached path
String pathCacheKey = null;
// the path + resourceName is the full resource name
String resourceName = currentResource.getName();
// add an optional / to the path if the resource is a folder
boolean isFolder = currentResource.getType() == CmsResourceTypeFolder.C_RESOURCE_TYPE_ID;
while (!(currentParentId = currentResource.getParentStructureId()).equals(CmsUUID.getNullUUID())) {
// see if we can find an already cached path for the current parent-ID
pathCacheKey = getCacheKey("path", projectId, currentParentId.toString());
if ((cachedPath = (String)m_resourceCache.get(pathCacheKey)) != null) {
path = cachedPath + path;
break;
}
// see if we can find a cached parent-resource for the current parent-ID
resourceCacheKey = getCacheKey("parent", projectId, currentParentId.toString());
if ((currentResource = (CmsResource)m_resourceCache.get(resourceCacheKey)) == null) {
currentResource = m_vfsDriver.readFileHeader(projectId, currentParentId, includeDeleted);
m_resourceCache.put(resourceCacheKey, currentResource);
}
if (!currentResource.getParentStructureId().equals(CmsUUID.getNullUUID())) {
// add a folder different from the root folder
path = currentResource.getName() + I_CmsConstants.C_FOLDER_SEPARATOR + path;
} else {
// add the root folder
path = currentResource.getName() + path;
}
}
// cache the calculated path
pathCacheKey = getCacheKey("path", projectId, parentId.toString());
m_resourceCache.put(pathCacheKey, path);
// build the full path of the resource
resourceName = path + resourceName;
if (isFolder && !resourceName.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
resourceName += I_CmsConstants.C_FOLDER_SEPARATOR;
}
// set the calculated path in the calling resource
resource.setFullResourceName(resourceName);
return resourceName;
}
/**
* Builds a list of resources for a given path.<p>
*
* Use this method if you want to select a resource given by it's full filename and path.
* This is done by climbing down the path from the root folder using the parent-ID's and
* resource names. Use this method with caution! Results are cached but reading path's
* inevitably increases runtime costs.<p>
*
* @param projectId the project to lookup the resource
* @param path the requested path
* @param includeDeleted include resources that are marked as deleted
* @return List of CmsResource's
* @throws CmsException if something goes wrong
*/
public List readPathInProject(int projectId, String path, boolean includeDeleted) throws CmsException {
// splits the path into folder and filename tokens
StringTokenizer tokens = null;
// # of folders in the path
int folderCount = 0;
// true if the path doesn't end with a folder
boolean lastResourceIsFile = false;
// holds the CmsResource instances in the path
List pathList = null;
// the current path token
String currentResourceName = null;
// the current path
String currentPath = null;
// the current resource
CmsResource currentResource = null;
// this is a comment. i love comments!
int i = 0, count = 0;
// key to cache the resources
String cacheKey = null;
// the parent resource of the current resource
CmsResource lastParent = null;
tokens = new StringTokenizer(path, I_CmsConstants.C_FOLDER_SEPARATOR);
// the root folder is no token in the path but a resource which has to be added to the path
count = tokens.countTokens() + 1;
pathList = (List)new ArrayList(count);
folderCount = count;
if (!path.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
folderCount--;
lastResourceIsFile = true;
}
// read the root folder, coz it's ID is required to read any sub-resources
currentResourceName = I_CmsConstants.C_ROOT;
currentPath = I_CmsConstants.C_ROOT;
cacheKey = getCacheKey(null, projectId, currentPath);
if ((currentResource = (CmsResource)m_resourceCache.get(cacheKey)) == null) {
currentResource = m_vfsDriver.readFolder(projectId, CmsUUID.getNullUUID(), currentResourceName);
currentResource.setFullResourceName(currentPath);
m_resourceCache.put(cacheKey, currentResource);
}
pathList.add(0, currentResource);
lastParent = currentResource;
if (count == 1) {
// the root folder was requested- no further operations required
return pathList;
}
currentResourceName = tokens.nextToken();
// read the folder resources in the path /a/b/c/
for (i = 1; i < folderCount; i++) {
currentPath += currentResourceName + I_CmsConstants.C_FOLDER_SEPARATOR;
// read the folder
cacheKey = getCacheKey(null, projectId, currentPath);
if ((currentResource = (CmsResource)m_resourceCache.get(cacheKey)) == null) {
currentResource = m_vfsDriver.readFolder(projectId, lastParent.getStructureId(), currentResourceName);
currentResource.setFullResourceName(currentPath);
m_resourceCache.put(cacheKey, currentResource);
}
pathList.add(i, currentResource);
lastParent = currentResource;
if (i < folderCount - 1) {
currentResourceName = tokens.nextToken();
}
}
// read the (optional) last file resource in the path /x.html
if (lastResourceIsFile) {
if (tokens.hasMoreTokens()) {
// this will only be false if a resource in the
// top level root folder (e.g. "/index.html") was requested
currentResourceName = tokens.nextToken();
}
currentPath += currentResourceName;
// read the file
cacheKey = getCacheKey(null, projectId, currentPath);
if ((currentResource = (CmsResource)m_resourceCache.get(cacheKey)) == null) {
currentResource = m_vfsDriver.readFileHeader(projectId, lastParent.getStructureId(), currentResourceName, includeDeleted);
currentResource.setFullResourceName(currentPath);
m_resourceCache.put(cacheKey, currentResource);
}
pathList.add(i, currentResource);
}
return pathList;
}
/**
* Reads a project from the Cms.<p>
*
* @param task the task to read the project of
* @return the project read from the cms
* @throws CmsException if something goes wrong
*/
public CmsProject readProject(CmsTask task) throws CmsException {
// read the parent of the task, until it has no parents.
while (task.getParent() != 0) {
task = readTask(task.getParent());
}
return m_projectDriver.readProject(task);
}
/**
* Reads a project from the Cms.<p>
*
* @param id the id of the project
* @return the project read from the cms
* @throws CmsException if something goes wrong.
*/
public CmsProject readProject(int id) throws CmsException {
CmsProject project = null;
project = (CmsProject)m_projectCache.get(new Integer(id));
if (project == null) {
project = m_projectDriver.readProject(id);
m_projectCache.put(new Integer(id), project);
}
return project;
}
/**
* Reads a project from the Cms.<p>
*
* @param name the name of the project
* @return the project read from the cms
* @throws CmsException if something goes wrong.
*/
public CmsProject readProject(String name) throws CmsException {
CmsProject project = null;
project = (CmsProject)m_projectCache.get(name);
if (project == null) {
project = m_projectDriver.readProject(name);
m_projectCache.put(name, project);
}
return project;
}
/**
* Reads log entries for a project.<p>
*
* @param projectId the id of the projec for tasklog to read
* @return a Vector of new TaskLog objects
* @throws CmsException if something goes wrong.
*/
public Vector readProjectLogs(int projectId) throws CmsException {
return m_projectDriver.readProjectLogs(projectId);
}
/**
* Returns the list of all resource names that define the "view" of the given project.<p>
*
* @param project the project to get the project resources for
* @return the list of all resource names that define the "view" of the given project
* @throws CmsException if something goes wrong
*/
public List readProjectResources(CmsProject project) throws CmsException {
return m_projectDriver.readProjectResources(project);
}
/**
* Reads all either new, changed, deleted or locked resources that are changed
* and inside a specified project.<p>
*
* @param context the current request context
* @param projectId the project ID
* @param filter specifies which resources inside the project should be read, {all|new|changed|deleted|locked}
* @return a Vector with the selected resources
* @throws CmsException if something goes wrong
*/
public Vector readProjectView(CmsRequestContext context, int projectId, String filter) throws CmsException {
Vector retValue = new Vector();
List resources = null;
CmsResource currentResource = null;
CmsLock currentLock = null;
// first get the correct status mode
int state=-1;
if (filter.equals("new")) {
state=I_CmsConstants.C_STATE_NEW;
} else if (filter.equals("changed")) {
state=I_CmsConstants.C_STATE_CHANGED;
} else if (filter.equals("deleted")) {
state=I_CmsConstants.C_STATE_DELETED;
} else if (filter.equals("all")) {
state=I_CmsConstants.C_STATE_UNCHANGED;
} else {
// this method was called with an unknown filter key
// filter all changed/new/deleted resources
state=I_CmsConstants.C_STATE_UNCHANGED;
}
// depending on the selected filter, we must use different methods to get the required
// resources
// if the "lock" filter was selected, we must handle the DB access different since
// lock information aren ot sotred in the DB anymore
if (filter.equals("locked")) {
resources=m_vfsDriver.readResources(projectId, state, I_CmsConstants.C_READMODE_IGNORESTATE);
} else {
if ((state == I_CmsConstants.C_STATE_NEW) || (state == I_CmsConstants.C_STATE_CHANGED)
|| (state == I_CmsConstants.C_STATE_DELETED)) {
resources=m_vfsDriver.readResources(projectId, state, I_CmsConstants.C_READMODE_MATCHSTATE);
// get all resources form the database which match to the selected state
} else if (state == I_CmsConstants.C_STATE_UNCHANGED) {
// get all resources form the database which are not unchanged
resources=m_vfsDriver.readResources(projectId, state, I_CmsConstants.C_READMODE_UNMATCHSTATE);
}
}
Iterator i = resources.iterator();
while (i.hasNext()) {
currentResource = (CmsResource)i.next();
if (hasPermissions(context, currentResource, I_CmsConstants.C_READ_ACCESS, false)) {
if (filter.equals("locked")) {
currentLock = getLock(context, currentResource);
if (!currentLock.isNullLock()) {
retValue.addElement(currentResource);
}
} else {
retValue.addElement(currentResource);
}
}
}
resources.clear();
resources = null;
return retValue;
}
/**
* Reads a definition for the given resource type.<p>
*
* All users are granted.
*
* @param context the current request context
* @param name the name of the propertydefinition to read
* @param resourcetype the name of the resource type for which the propertydefinition is valid.
* @return the propertydefinition that corresponds to the overgiven arguments - or null if there is no valid propertydefinition.
* @throws CmsException if something goes wrong
*/
public CmsPropertydefinition readPropertydefinition(CmsRequestContext context, String name, int resourcetype) throws CmsException {
return m_vfsDriver.readPropertyDefinition(name, context.currentProject().getId(), resourcetype);
}
/**
* Reads all project resources that belong to a given view. <p>
*
* A view can be "new", "changed" and "deleted" and contains those resources in the project whose
* state is equal to the selevted view.
*
* @param context the current request context
* @param projectId the preoject to read from
* @param filter the view filter, can be "new", "changed" or "deleted"
* @return vector of CmsResources
* @throws CmsException if something goes wrong
*/
public Vector readPublishProjectView(CmsRequestContext context, int projectId, String filter) throws CmsException {
Vector retValue = new Vector();
List resources = m_projectDriver.readProjectView(projectId, filter);
boolean onlyLocked = false;
// check if only locked resources should be displayed
if ("locked".equalsIgnoreCase(filter)) {
onlyLocked = true;
}
// check the security
Iterator i = resources.iterator();
while (i.hasNext()) {
CmsResource currentResource = (CmsResource)i.next();
if (hasPermissions(context, currentResource, I_CmsConstants.C_READ_ACCESS, false)) {
if (onlyLocked) {
// check if resource is locked
CmsLock lock = getLock(context, currentResource);
if (!lock.isNullLock()) {
retValue.addElement(currentResource);
}
} else {
// add all resources with correct permissions
retValue.addElement(currentResource);
}
}
}
return retValue;
}
/**
* Reads all siblings that point to the resource record of a specified resource name.<p>
*
* @param context the request context
* @param resourcename the name of the specified resource
* @param readAllSiblings true if the specified resource should be included in the result; false, if the specified resource should be excluded from the result
* @param includeDeleted true if deleted siblings should be included in the result List
* @return a List of CmsResources
* @throws CmsException if something goes wrong
*/
public List readSiblings(CmsRequestContext context, String resourcename, boolean readAllSiblings, boolean includeDeleted) throws CmsException {
if (resourcename == null || "".equals(resourcename)) {
return Collections.EMPTY_LIST;
}
CmsResource resource = readFileHeader(context, resourcename, includeDeleted);
List siblings = m_vfsDriver.readSiblings(context.currentProject(), resource, includeDeleted);
int n = siblings.size();
for (int i = 0; i < n; i++) {
CmsResource currentResource = (CmsResource)siblings.get(i);
if (!readAllSiblings && currentResource.getStructureId().equals(resource.getStructureId())) {
siblings.remove(i);
n--;
}
}
setFullResourceNames(context, siblings);
return siblings;
}
/**
* Returns a list of all template resources which must be processed during a static export.<p>
*
* @param context the current request context
* @param parameterResources flag for reading resources with parameters (1) or without (0)
* @param timestamp for reading the data from the db
* @return List of template resources
* @throws CmsException if something goes wrong
*/
public List readStaticExportResources(CmsRequestContext context, int parameterResources, long timestamp) throws CmsException {
return m_projectDriver.readStaticExportResources(context.currentProject(), parameterResources, timestamp);
}
/**
* Returns the parameters of a resource in the table of all published template resources.<p>
*
* @param context the current request context
* @param rfsName the rfs name of the resource
* @return the paramter string of the requested resource
* @throws CmsException if something goes wrong
*/
public String readStaticExportPublishedResourceParamters(CmsRequestContext context, String rfsName) throws CmsException {
return m_projectDriver.readStaticExportPublishedResourceParamters(context.currentProject(), rfsName);
}
/**
* Read a task by id.<p>
*
* @param id the id for the task to read
* @return a task
* @throws CmsException if something goes wrong
*/
public CmsTask readTask(int id) throws CmsException {
return m_workflowDriver.readTask(id);
}
/**
* Reads log entries for a task.<p>
*
* @param taskid the task for the tasklog to read
* @return a Vector of new TaskLog objects
* @throws CmsException if something goes wrong
*/
public Vector readTaskLogs(int taskid) throws CmsException {
return m_workflowDriver.readTaskLogs(taskid);
}
/**
* Reads all tasks for a project.<p>
*
* All users are granted.
*
* @param projectId the id of the Project in which the tasks are defined. Can be null for all tasks
* @param tasktype task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW
* @param orderBy chooses, how to order the tasks
* @param sort sort order C_SORT_ASC, C_SORT_DESC, or null
* @return a vector of tasks
* @throws CmsException if something goes wrong
*/
public Vector readTasksForProject(int projectId, int tasktype, String orderBy, String sort) throws CmsException {
CmsProject project = null;
if (projectId != I_CmsConstants.C_UNKNOWN_ID) {
project = readProject(projectId);
}
return m_workflowDriver.readTasks(project, null, null, null, tasktype, orderBy, sort);
}
/**
* Reads all tasks for a role in a project.<p>
*
* @param projectId the id of the Project in which the tasks are defined
* @param roleName the user who has to process the task
* @param tasktype task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW
* @param orderBy chooses, how to order the tasks
* @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null
* @return a vector of tasks
* @throws CmsException if something goes wrong
*/
public Vector readTasksForRole(int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException {
CmsProject project = null;
CmsGroup role = null;
if (roleName != null) {
role = readGroup(roleName);
}
if (projectId != I_CmsConstants.C_UNKNOWN_ID) {
project = readProject(projectId);
}
return m_workflowDriver.readTasks(project, null, null, role, tasktype, orderBy, sort);
}
/**
* Reads all tasks for a user in a project.<p>
*
* @param projectId the id of the Project in which the tasks are defined
* @param userName the user who has to process the task
* @param taskType task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW
* @param orderBy chooses, how to order the tasks
* @param sort sort order C_SORT_ASC, C_SORT_DESC, or null
* @return a vector of tasks
* @throws CmsException if something goes wrong
*/
public Vector readTasksForUser(int projectId, String userName, int taskType, String orderBy, String sort) throws CmsException {
CmsUser user = readUser(userName, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
CmsProject project = null;
// try to read the project, if projectId == -1 we must return the tasks of all projects
if (projectId != I_CmsConstants.C_UNKNOWN_ID) {
project = m_projectDriver.readProject(projectId);
}
return m_workflowDriver.readTasks(project, user, null, null, taskType, orderBy, sort);
}
/**
* Returns a user object based on the id of a user.<p>
*
* All users are granted.
*
* @param id the id of the user to read
* @return the user read
* @throws CmsException if something goes wrong
*/
public CmsUser readUser(CmsUUID id) throws CmsException {
CmsUser user = null;
user = getUserFromCache(id);
if (user == null) {
user = m_userDriver.readUser(id);
putUserInCache(user);
}
return user;
// old implementation:
// try {
// user = getUserFromCache(id);
// if (user == null) {
// user = m_userDriver.readUser(id);
// putUserInCache(user);
// }
// } catch (CmsException ex) {
// return new CmsUser(CmsUUID.getNullUUID(), id + "", "deleted user");
// }
// return user;
}
/**
* Returns a user object.<p>
*
* All users are granted.
*
* @param username the name of the user that is to be read
* @return user read form the cms
* @throws CmsException if operation was not succesful
*/
public CmsUser readUser(String username) throws CmsException {
return readUser(username, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
}
/**
* Returns a user object.<p>
*
* All users are granted.
*
* @param username the name of the user that is to be read
* @param type the type of the user
* @return user read form the cms
* @throws CmsException if operation was not succesful
*/
public CmsUser readUser(String username, int type) throws CmsException {
CmsUser user = getUserFromCache(username, type);
if (user == null) {
user = m_userDriver.readUser(username, type);
putUserInCache(user);
}
return user;
}
/**
* Returns a user object if the password for the user is correct.<p>
*
* All users are granted.
*
* @param username the username of the user that is to be read
* @param password the password of the user that is to be read
* @return user read form the cms
* @throws CmsException if operation was not succesful
*/
public CmsUser readUser(String username, String password) throws CmsException {
// don't read user from cache here because password may have changed
CmsUser user = m_userDriver.readUser(username, password, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
putUserInCache(user);
return user;
}
/**
* Read a web user from the database.<p>
*
* @param username the web user to read
* @return the read web user
* @throws CmsException if the user could not be read
*/
public CmsUser readWebUser(String username) throws CmsException {
return readUser(username, I_CmsConstants.C_USER_TYPE_WEBUSER);
}
/**
* Returns a user object if the password for the user is correct.<p>
*
* All users are granted.
*
* @param username the username of the user that is to be read
* @param password the password of the user that is to be read
* @return user read form the cms
* @throws CmsException if operation was not succesful
*/
public CmsUser readWebUser(String username, String password) throws CmsException {
// don't read user from cache here because password may have changed
CmsUser user = m_userDriver.readUser(username, password, I_CmsConstants.C_USER_TYPE_WEBUSER);
putUserInCache(user);
return user;
}
/**
* Reaktivates a task from the Cms.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task to accept
* @throws CmsException if something goes wrong
*/
public void reaktivateTask(CmsRequestContext context, int taskId) throws CmsException {
CmsTask task = m_workflowDriver.readTask(taskId);
task.setState(I_CmsConstants.C_TASK_STATE_STARTED);
task.setPercentage(0);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Task was reactivated from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Sets a new password if the given recovery password is correct.<p>
*
* @param username the name of the user
* @param recoveryPassword the recovery password
* @param newPassword the new password
* @throws CmsException if operation was not succesfull.
*/
public void recoverPassword(String username, String recoveryPassword, String newPassword) throws CmsException {
// check the new password
validatePassword(newPassword);
// recover the password
m_userDriver.writePassword(username, recoveryPassword, newPassword);
}
/**
* Recovers a resource from the online project back to the offline project as an unchanged resource.<p>
*
* @param context the current request context
* @param resourcename the name of the resource which is recovered
* @return the recovered resource in the offline project
* @throws CmsException if somethong goes wrong
*/
public CmsResource recoverResource(CmsRequestContext context, String resourcename) throws CmsException {
CmsFile onlineFile = null;
byte[] contents = null;
List properties = null;
CmsFile newFile = null;
CmsFolder newFolder = null;
CmsResource newResource = null;
CmsFolder parentFolder = null;
CmsFolder onlineFolder = null;
CmsProject oldProject = null;
try {
parentFolder = readFolder(context, CmsResource.getFolderPath(resourcename));
// switch to the online project
oldProject = context.currentProject();
context.setCurrentProject(readProject(I_CmsConstants.C_PROJECT_ONLINE_ID));
if (!resourcename.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
// read the file content plus properties in the online project
onlineFile = readFile(context, resourcename);
contents = onlineFile.getContents();
properties = readPropertyObjects(context, resourcename, context.getAdjustedSiteRoot(resourcename), false);
} else {
// contents and properties for a folder
onlineFolder = readFolder(context, resourcename);
contents = new byte[0];
properties = readPropertyObjects(context, resourcename, context.getAdjustedSiteRoot(resourcename), false);
}
// switch back to the previous project
context.setCurrentProject(oldProject);
if (!resourcename.endsWith(I_CmsConstants.C_FOLDER_SEPARATOR)) {
// create the file in the offline project
newFile = new CmsFile(onlineFile.getStructureId(), onlineFile.getResourceId(), parentFolder.getStructureId(), onlineFile.getFileId(), CmsResource.getName(resourcename), onlineFile.getType(), onlineFile.getFlags(), 0, org.opencms.main.I_CmsConstants.C_STATE_UNCHANGED, getResourceType(onlineFile.getType()).getLoaderId(), 0, context.currentUser().getId(), 0, context.currentUser().getId(), contents.length, 1, contents);
newResource = m_vfsDriver.createFile(context.currentProject(), newFile, context.currentUser().getId(), parentFolder.getStructureId(), CmsResource.getName(resourcename));
} else {
// create the folder in the offline project
newFolder = new CmsFolder(onlineFolder.getStructureId(), onlineFolder.getResourceId(), parentFolder.getStructureId(), CmsUUID.getNullUUID(), CmsResource.getName(resourcename), CmsResourceTypeFolder.C_RESOURCE_TYPE_ID, onlineFolder.getFlags(), 0, org.opencms.main.I_CmsConstants.C_STATE_UNCHANGED, 0, context.currentUser().getId(), 0, context.currentUser().getId(), 1);
newResource = m_vfsDriver.createFolder(context.currentProject(), newFolder, parentFolder.getStructureId());
}
// write the properties of the recovered resource
writePropertyObjects(context, resourcename, properties);
// set the resource state to unchanged coz the resource exists online
newResource.setState(I_CmsConstants.C_STATE_UNCHANGED);
m_vfsDriver.writeResourceState(context.currentProject(), newResource, C_UPDATE_ALL);
} catch (CmsException e) {
// the exception is caught just to have a finally clause to switch back to the
// previous project. the exception should be handled in the upper app. layer.
throw e;
} finally {
// switch back to the previous project
context.setCurrentProject(oldProject);
clearResourceCache();
}
newResource.setFullResourceName(resourcename);
contents = null;
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", newResource)));
return newResource;
}
/**
* Removes an access control entry for a given resource and principal.<p>
*
* Access is granted, if:
* <ul>
* <li>the current user has control permission on the resource
* </ul>
*
* @param context the current request context
* @param resource the resource
* @param principal the id of a group or user to identify the access control entry
* @throws CmsException if something goes wrong
*/
public void removeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsUUID principal) throws CmsException {
// get the old values
long dateLastModified = resource.getDateLastModified();
CmsUUID userLastModified = resource.getUserLastModified();
checkPermissions(context, resource, I_CmsConstants.C_CONTROL_ACCESS);
m_userDriver.removeAccessControlEntry(context.currentProject(), resource.getResourceId(), principal);
clearAccessControlListCache();
touchResource(context, resource, dateLastModified, userLastModified);
}
/**
* Removes user from Cache.<p>
*
* @param user the user to remove
*/
private void removeUserFromCache(CmsUser user) {
m_userCache.remove(getUserCacheKey(user.getName(), user.getType()));
m_userCache.remove(getUserCacheKey(user.getId()));
}
/**
* Removes a user from a group.<p>
*
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param username the name of the user that is to be removed from the group
* @param groupname the name of the group
* @throws CmsException if operation was not succesful
*/
public void removeUserFromGroup(CmsRequestContext context, String username, String groupname) throws CmsException {
// test if this user is existing in the group
if (!userInGroup(context, username, groupname)) {
// user already there, throw exception
throw new CmsException("[" + getClass().getName() + "] remove " + username + " from " + groupname, CmsException.C_NO_USER);
}
if (isAdmin(context)) {
CmsUser user;
CmsGroup group;
user = readUser(username);
//check if the user exists
if (user != null) {
group = readGroup(groupname);
//check if group exists
if (group != null) {
// do not remmove the user from its default group
if (user.getDefaultGroupId() != group.getId()) {
//remove this user from the group
m_userDriver.deleteUserInGroup(user.getId(), group.getId());
m_userGroupsCache.clear();
} else {
throw new CmsException("[" + getClass().getName() + "]", CmsException.C_NO_DEFAULT_GROUP);
}
} else {
throw new CmsException("[" + getClass().getName() + "]" + groupname, CmsException.C_NO_GROUP);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] removeUserFromGroup()", CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] removeUserFromGroup()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Renames the file to a new name.<p>
*
* Rename can only be done in an offline project. To rename a file, the following
* steps have to be done:
* <ul>
* <li> Copy the file with the oldname to a file with the new name, the state
* of the new file is set to NEW (2).
* <ul>
* <li> If the state of the original file is UNCHANGED (0), the file content of the
* file is read from the online project. </li>
* <li> If the state of the original file is CHANGED (1) or NEW (2) the file content
* of the file is read from the offline project. </li>
* </ul>
* </li>
* <li> Set the state of the old file to DELETED (3). </li>
* </ul>
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param oldname the complete path to the resource which will be renamed
* @param newname the new name of the resource
* @throws CmsException if operation was not succesful
*/
public void renameResource(CmsRequestContext context, String oldname, String newname) throws CmsException {
String destination = oldname.substring(0, oldname.lastIndexOf("/") + 1);
this.moveResource(context, oldname, destination + newname);
}
/**
* Replaces the content and properties of an existing resource.<p>
*
* @param context the current request context
* @param resourceName the resource name
* @param newResourceType the new resource type
* @param newResourceProperties the new resource properties
* @param newResourceContent the new resource content
* @return CmsResource the resource with replaced content and properties
* @throws CmsException if something goes wrong
*/
public CmsResource replaceResource(CmsRequestContext context, String resourceName, int newResourceType, List newResourceProperties, byte[] newResourceContent) throws CmsException {
CmsResource resource = null;
// clear the cache
clearResourceCache();
// read the existing resource
resource = readFileHeader(context, resourceName, false);
// check if the user has write access
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
// replace the existing with the new file content
m_vfsDriver.replaceResource(context.currentUser(), context.currentProject(), resource, newResourceContent, newResourceType, getResourceType(newResourceType).getLoaderId());
// write the properties
m_vfsDriver.writePropertyObjects(context.currentProject(), resource, newResourceProperties);
m_propertyCache.clear();
// update the resource state
if (resource.getState() == I_CmsConstants.C_STATE_UNCHANGED) {
resource.setState(I_CmsConstants.C_STATE_CHANGED);
}
resource.setUserLastModified(context.currentUser().getId());
touch(context, resourceName, System.currentTimeMillis(), context.currentUser().getId());
m_vfsDriver.writeResourceState(context.currentProject(), resource, C_UPDATE_RESOURCE);
// clear the cache
clearResourceCache();
newResourceContent = null;
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
return resource;
}
/**
* Restores a file in the current project with a version in the backup.<p>
*
* @param context the current request context
* @param tagId the tag id of the resource
* @param filename the name of the file to restore
* @throws CmsException if operation was not succesful
*/
public void restoreResource(CmsRequestContext context, int tagId, String filename) throws CmsException {
if (context.currentProject().isOnlineProject()) {
// this is the onlineproject
throw new CmsSecurityException("Can't write to the online project", CmsSecurityException.C_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT);
}
CmsFile offlineFile = readFile(context, filename);
// check if the user has write access
checkPermissions(context, offlineFile, I_CmsConstants.C_WRITE_ACCESS);
int state = I_CmsConstants.C_STATE_CHANGED;
CmsBackupResource backupFile = readBackupFile(context, tagId, filename);
if (offlineFile.getState() == I_CmsConstants.C_STATE_NEW) {
state = I_CmsConstants.C_STATE_NEW;
}
if (backupFile != null && offlineFile != null) {
// get the backed up flags
int flags = backupFile.getFlags();
if (offlineFile.isLabeled()) {
// set the flag for labeled links on the restored file
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
}
CmsFile newFile = new CmsFile(offlineFile.getStructureId(), offlineFile.getResourceId(), offlineFile.getParentStructureId(), offlineFile.getFileId(), offlineFile.getName(), backupFile.getType(), flags, context.currentProject().getId(), state, backupFile.getLoaderId(), offlineFile.getDateCreated(), backupFile.getUserCreated(), offlineFile.getDateLastModified(), context.currentUser().getId(), backupFile.getLength(), backupFile.getLinkCount(), backupFile.getContents());
writeFile(context, newFile);
// now read the backup properties
List backupProperties = m_backupDriver.readBackupProperties(backupFile);
//and write them to the curent resource
writePropertyObjects(context, filename, backupProperties);
clearResourceCache();
}
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", offlineFile)));
}
/**
* Adds the full resourcename to each resource in a list of CmsResources.<p>
*
* @param context the current request context
* @param resourceList a list of CmsResources
* @return list of CmsResources added with full resource name
* @throws CmsException if something goes wrong
*/
public List setFullResourceNames(CmsRequestContext context, List resourceList) throws CmsException {
Iterator i = resourceList.iterator();
while (i.hasNext()) {
CmsResource res = (CmsResource)i.next();
if (!res.hasFullResourceName()) {
res.setFullResourceName(readPath(context, res, true));
}
updateContextDates(context, res);
}
return resourceList;
}
/**
* Set a new name for a task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task to set the percentage
* @param name the new name value
* @throws CmsException if something goes wrong
*/
public void setName(CmsRequestContext context, int taskId, String name) throws CmsException {
if ((name == null) || name.length() == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
CmsTask task = m_workflowDriver.readTask(taskId);
task.setName(name);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Name was set to " + name + "% from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Sets a new parent-group for an already existing group in the Cms.<p>
*
* Only the admin can do this.
*
* @param context the current request context
* @param groupName the name of the group that should be written to the Cms
* @param parentGroupName the name of the parentGroup to set, or null if the parent group should be deleted
* @throws CmsException if operation was not succesfull
*/
public void setParentGroup(CmsRequestContext context, String groupName, String parentGroupName) throws CmsException {
// Check the security
if (isAdmin(context)) {
CmsGroup group = readGroup(groupName);
CmsUUID parentGroupId = CmsUUID.getNullUUID();
// if the group exists, use its id, else set to unknown.
if (parentGroupName != null) {
parentGroupId = readGroup(parentGroupName).getId();
}
group.setParentId(parentGroupId);
// write the changes to the cms
writeGroup(context, group);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] setParentGroup() " + groupName, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Sets the password for a user.<p>
*
* Only users in the group "Administrators" are granted.<p>
*
* @param context the current request context
* @param username the name of the user
* @param newPassword the new password
* @throws CmsException if operation was not succesfull.
*/
public void setPassword(CmsRequestContext context, String username, String newPassword) throws CmsException {
// check the password
validatePassword(newPassword);
if (isAdmin(context)) {
m_userDriver.writePassword(username, newPassword);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] setPassword() " + username, CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Resets the password for a specified user.<p>
*
* @param username the name of the user
* @param oldPassword the old password
* @param newPassword the new password
* @throws CmsException if the user data could not be read from the database
* @throws CmsSecurityException if the specified username and old password could not be verified
*/
public void resetPassword(String username, String oldPassword, String newPassword) throws CmsException, CmsSecurityException {
boolean noSystemUser = false;
boolean noWebUser = false;
boolean unknownException = false;
CmsUser user = null;
// read the user as a system to verify that the specified old password is correct
try {
user = m_userDriver.readUser(username, oldPassword, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
} catch (CmsException e) {
if (e.getType() == CmsException.C_NO_USER) {
noSystemUser = true;
} else {
unknownException = true;
}
}
// dito as a web user
if (user == null) {
try {
user = m_userDriver.readUser(username, oldPassword, I_CmsConstants.C_USER_TYPE_WEBUSER);
} catch (CmsException e) {
if (e.getType() == CmsException.C_NO_USER) {
noWebUser = true;
} else {
unknownException = true;
}
}
}
if (noSystemUser && noWebUser) {
// the specified username + old password don't match
throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED);
} else if (unknownException) {
// we caught exceptions different from CmsException.C_NO_USER -> a general error?!
throw new CmsException("[" + getClass().getName() + "] Error resetting password for user '" + username + "'", CmsException.C_UNKNOWN_EXCEPTION);
} else if (user != null) {
// the specified old password was successful verified
validatePassword(newPassword);
m_userDriver.writePassword(username, newPassword);
}
}
/**
* Set priority of a task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task to set the percentage
* @param priority the priority value
* @throws CmsException if something goes wrong
*/
public void setPriority(CmsRequestContext context, int taskId, int priority) throws CmsException {
CmsTask task = m_workflowDriver.readTask(taskId);
task.setPriority(priority);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Priority was set to " + priority + " from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Sets the recovery password for a user.<p>
*
* Users, which are in the group "Administrators" are granted.
* A user can change his own password.<p>
*
* @param username the name of the user
* @param password the password of the user
* @param newPassword the new recoveryPassword to be set
* @throws CmsException if operation was not succesfull
*/
public void setRecoveryPassword(String username, String password, String newPassword) throws CmsException {
// check the password
validatePassword(newPassword);
// read the user in order to ensure that the password is correct
CmsUser user = null;
try {
user = m_userDriver.readUser(username, password, I_CmsConstants.C_USER_TYPE_SYSTEMUSER);
} catch (CmsException exc) {
// user will be null
}
if (user == null) {
try {
user = m_userDriver.readUser(username, password, I_CmsConstants.C_USER_TYPE_WEBUSER);
} catch (CmsException e) {
// TODO: Check what happens if this is caught
}
}
m_userDriver.writeRecoveryPassword(username, newPassword);
}
/**
* Set a Parameter for a task.<p>
*
* @param taskId the Id of the task
* @param parName name of the parameter
* @param parValue value if the parameter
* @throws CmsException if something goes wrong.
*/
public void setTaskPar(int taskId, String parName, String parValue) throws CmsException {
m_workflowDriver.writeTaskParameter(taskId, parName, parValue);
}
/**
* Set timeout of a task.<p>
*
* @param context the current request context
* @param taskId the Id of the task to set the percentage
* @param timeout new timeout value
* @throws CmsException if something goes wrong
*/
public void setTimeout(CmsRequestContext context, int taskId, long timeout) throws CmsException {
CmsTask task = m_workflowDriver.readTask(taskId);
java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout);
task.setTimeOut(timestamp);
task = m_workflowDriver.writeTask(task);
m_workflowDriver.writeSystemTaskLog(taskId, "Timeout was set to " + timeout + " from " + context.currentUser().getFirstname() + " " + context.currentUser().getLastname() + ".");
}
/**
* Access the driver underneath to change the timestamp of a resource.<p>
*
* @param context the current request context
* @param resourceName the name of the resource to change
* @param timestamp timestamp the new timestamp of the changed resource
* @param user the user who is inserted as userladtmodified
* @throws CmsException if something goes wrong
*/
public void touch(CmsRequestContext context, String resourceName, long timestamp, CmsUUID user) throws CmsException {
CmsResource resource = readFileHeader(context, resourceName);
touchResource(context, resource, timestamp, user);
}
/**
* Access the driver underneath to change the timestamp of a resource.<p>
*
* @param context the current request context
* @param res the resource to change
* @param timestamp timestamp the new timestamp of the changed resource
* @param user the user who is inserted as userladtmodified
* @throws CmsException if something goes wrong
*/
private void touchResource(CmsRequestContext context, CmsResource res, long timestamp, CmsUUID user) throws CmsException {
// NOTE: this is the new way to update the state !
// if (res.getState() < I_CmsConstants.C_STATE_CHANGED)
res.setState(I_CmsConstants.C_STATE_CHANGED);
res.setDateLastModified(timestamp);
res.setUserLastModified(user);
m_vfsDriver.writeResourceState(context.currentProject(), res, C_UPDATE_RESOURCE);
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", res)));
}
/**
* Undeletes a file in the Cms.<p>
*
* A file can only be undeleted in an offline project.
* A file is undeleted by setting its state to CHANGED (1).
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callinUser</li>
* </ul>
*
* @param context the current request context
* @param filename the complete m_path of the file
* @throws CmsException if operation was not succesful
*/
public void undeleteResource(CmsRequestContext context, String filename) throws CmsException {
// try to trad the resource
CmsResource resource = readFileHeader(context, filename, true);
// this resource must be marked as deleted
if (resource.getState() == I_CmsConstants.C_STATE_DELETED) {
undoChanges(context, filename);
} else {
throw new CmsException("Resource already exists. Remove the existing blue resource before undeleting.", CmsException.C_FILE_EXISTS);
}
}
/**
* Undo all changes in the resource, restore the online file.<p>
*
* @param context the current request context
* @param resourceName the name of the resource to be restored
* @throws CmsException if something goes wrong
*/
public void undoChanges(CmsRequestContext context, String resourceName) throws CmsException {
if (context.currentProject().isOnlineProject()) {
// this is the onlineproject
throw new CmsSecurityException("Can't undo changes to the online project", CmsSecurityException.C_SECURITY_NO_MODIFY_IN_ONLINE_PROJECT);
}
CmsProject onlineProject = readProject(I_CmsConstants.C_PROJECT_ONLINE_ID);
CmsResource resource = readFileHeader(context, resourceName, true);
// check if the user has write access
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
// change folder or file?
if (resource.isFolder()) {
// read the resource from the online project
CmsFolder onlineFolder = readFolderInProject(I_CmsConstants.C_PROJECT_ONLINE_ID, resourceName);
//we must ensure that the resource contains it full resource name as this is required for the
// property operations
readPath(context, onlineFolder, true);
CmsFolder restoredFolder = new CmsFolder(resource.getStructureId(), resource.getResourceId(), resource.getParentStructureId(), resource.getFileId(), resource.getName(), onlineFolder.getType(), onlineFolder.getFlags(), context.currentProject().getId(), I_CmsConstants.C_STATE_UNCHANGED, onlineFolder.getDateCreated(), onlineFolder.getUserCreated(), onlineFolder.getDateLastModified(), onlineFolder.getUserLastModified(), resource.getLinkCount());
// write the file in the offline project
// this sets a flag so that the file date is not set to the current time
restoredFolder.setDateLastModified(onlineFolder.getDateLastModified());
// write the folder without setting state = changed
m_vfsDriver.writeFolder(context.currentProject(), restoredFolder, C_NOTHING_CHANGED, restoredFolder.getUserLastModified());
// restore the properties in the offline project
readPath(context, restoredFolder, true);
m_vfsDriver.deleteProperties(context.currentProject().getId(), restoredFolder);
List propertyInfos = m_vfsDriver.readPropertyObjects(onlineProject, onlineFolder);
m_vfsDriver.writePropertyObjects(context.currentProject(), restoredFolder, propertyInfos);
} else {
// read the file from the online project
CmsFile onlineFile = readFileInProject(context, I_CmsConstants.C_PROJECT_ONLINE_ID, resource.getStructureId(), false);
//(context, resourceName);
readPath(context, onlineFile, true);
// get flags of the deleted file
int flags = onlineFile.getFlags();
if (resource.isLabeled()) {
// set the flag for labeled links on the restored file
flags |= I_CmsConstants.C_RESOURCEFLAG_LABELLINK;
}
CmsFile restoredFile = new CmsFile(resource.getStructureId(), resource.getResourceId(), resource.getParentStructureId(), resource.getFileId(), resource.getName(), onlineFile.getType(), flags, context.currentProject().getId(), I_CmsConstants.C_STATE_UNCHANGED, onlineFile.getLoaderId(), onlineFile.getDateCreated(), onlineFile.getUserCreated(), onlineFile.getDateLastModified(), onlineFile.getUserLastModified(), onlineFile.getLength(), resource.getLinkCount(), onlineFile.getContents());
// write the file in the offline project
// this sets a flag so that the file date is not set to the current time
restoredFile.setDateLastModified(onlineFile.getDateLastModified());
// write-acces was granted - write the file without setting state = changed
//m_vfsDriver.writeFile(context.currentProject(), restoredFile, C_NOTHING_CHANGED, restoredFile.getUserLastModified());
m_vfsDriver.writeFileHeader(context.currentProject(), restoredFile, C_NOTHING_CHANGED, restoredFile.getUserLastModified());
m_vfsDriver.writeFileContent(restoredFile.getFileId(), restoredFile.getContents(), context.currentProject().getId(), false);
// restore the properties in the offline project
readPath(context, restoredFile, true);
m_vfsDriver.deleteProperties(context.currentProject().getId(), restoredFile);
List propertyInfos = m_vfsDriver.readPropertyObjects(onlineProject, onlineFile);
m_vfsDriver.writePropertyObjects(context.currentProject(), restoredFile, propertyInfos);
}
m_userDriver.removeAccessControlEntries(context.currentProject(), resource.getResourceId());
// copy the access control entries
ListIterator aceList = m_userDriver.readAccessControlEntries(onlineProject, resource.getResourceId(), false).listIterator();
while (aceList.hasNext()) {
CmsAccessControlEntry ace = (CmsAccessControlEntry)aceList.next();
m_userDriver.createAccessControlEntry(context.currentProject(), resource.getResourceId(), ace.getPrincipal(), ace.getPermissions().getAllowedPermissions(), ace.getPermissions().getDeniedPermissions(), ace.getFlags());
}
// update the cache
clearResourceCache();
m_propertyCache.clear();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Unlocks all resources in this project.<p>
*
* Only the admin or the owner of the project can do this.
*
* @param context the current request context
* @param projectId the id of the project to be published
* @throws CmsException if something goes wrong
*/
public void unlockProject(CmsRequestContext context, int projectId) throws CmsException {
// read the project
CmsProject project = readProject(projectId);
// check the security
if ((isAdmin(context) || isManagerOfProject(context)) && (project.getFlags() == I_CmsConstants.C_PROJECT_STATE_UNLOCKED)) {
// unlock all resources in the project
m_lockManager.removeResourcesInProject(projectId);
clearResourceCache();
m_projectCache.clear();
// we must also clear the permission cache
m_permissionCache.clear();
} else if (!isAdmin(context) && !isManagerOfProject(context)) {
throw new CmsSecurityException("[" + this.getClass().getName() + "] unlockProject() " + projectId, CmsSecurityException.C_SECURITY_PROJECTMANAGER_PRIVILEGES_REQUIRED);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] unlockProject() " + projectId, CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Unlocks a resource by removing the exclusive lock on the exclusive locked sibling.<p>
*
* @param context the current request context
* @param resourcename the resource name that gets locked
* @return the removed lock
* @throws CmsException if something goes wrong
*/
public CmsLock unlockResource(CmsRequestContext context, String resourcename) throws CmsException {
CmsLock oldLock = m_lockManager.removeResource(this, context, resourcename, false);
clearResourceCache();
// cw/060104 we must also clear the permission cache
m_permissionCache.clear();
CmsResource resource = readFileHeader(context, resourcename);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
return oldLock;
}
/**
* Checks if a user is member of a group.<p>
*
* All users are granted, except the anonymous user.
*
* @param context the current request context
* @param username the name of the user to check
* @param groupname the name of the group to check
* @return true or false
* @throws CmsException if operation was not succesful
*/
public boolean userInGroup(CmsRequestContext context, String username, String groupname) throws CmsException {
Vector groups = getGroupsOfUser(context, username);
CmsGroup group;
for (int z = 0; z < groups.size(); z++) {
group = (CmsGroup)groups.elementAt(z);
if (groupname.equals(group.getName())) {
return true;
}
}
return false;
}
/**
* This method checks if a new password follows the rules for
* new passwords, which are defined by a Class configured in opencms.properties.<p>
*
* If this method throws no exception the password is valid.
*
* @param password the new password that has to be checked
* @throws CmsSecurityException if the password is not valid
*/
public void validatePassword(String password) throws CmsSecurityException {
if (m_passwordValidationClass == null) {
synchronized (this) {
String className = OpenCms.getPasswordValidatingClass();
try {
m_passwordValidationClass = (I_CmsPasswordValidation)Class.forName(className).getConstructor(new Class[] {}).newInstance(new Class[] {});
} catch (Exception e) {
throw new RuntimeException("Error generating password validation class instance");
}
}
}
m_passwordValidationClass.validatePassword(password);
}
/**
* Checks if characters in a String are allowed for filenames.<p>
*
* @param filename String to check
* @throws CmsException C_BAD_NAME if the check fails
*/
public void validFilename(String filename) throws CmsException {
if (filename == null) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME);
}
int l = filename.length();
// if (l == 0 || filename.startsWith(".")) {
if (l == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME);
}
for (int i = 0; i < l; i++) {
char c = filename.charAt(i);
if (((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') && (c != '$')) {
throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME);
}
}
}
/**
* Checks if characters in a String are allowed for names.<p>
*
* @param name String to check
* @param blank flag to allow blanks
* @throws CmsException C_BAD_NAME if the check fails
*/
protected void validName(String name, boolean blank) throws CmsException {
if (name == null || name.length() == 0 || name.trim().length() == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
// throw exception if no blanks are allowed
if (!blank) {
int l = name.length();
for (int i = 0; i < l; i++) {
char c = name.charAt(i);
if (c == ' ') {
throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME);
}
}
}
/*
for (int i=0; i<l; i++) {
char c = name.charAt(i);
if (
((c < 'a') || (c > 'z')) &&
((c < '0') || (c > '9')) &&
((c < 'A') || (c > 'Z')) &&
(c != '-') && (c != '.') &&
(c != '_') && (c != '~')
) {
throw new CmsException("[" + this.getClass().getName() + "] " + name,
CmsException.C_BAD_NAME);
}
}
*/
}
/**
* Checks if characters in a String are allowed for filenames.<p>
*
* @param taskname String to check
* @throws CmsException C_BAD_NAME if the check fails
*/
protected void validTaskname(String taskname) throws CmsException {
if (taskname == null) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME);
}
int l = taskname.length();
if (l == 0) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME);
}
for (int i = 0; i < l; i++) {
char c = taskname.charAt(i);
if (((c < '?') || (c > '?')) && ((c < '?') || (c > '?')) && ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '_') && (c != '~') && (c != ' ') && (c != '?') && (c != '/') && (c != '(') && (c != ')') && (c != '\'') && (c != '#') && (c != '&') && (c != ';')) {
throw new CmsException("[" + this.getClass().getName() + "] " + taskname, CmsException.C_BAD_NAME);
}
}
}
/**
* Writes an access control entry to the cms.<p>
*
* Access is granted, if:
* <ul>
* <li>the current user has control permission on the resource
* </ul>
*
* @param context the current request context
* @param resource the resource
* @param acEntry the entry to write
* @throws CmsException if something goes wrong
*/
public void writeAccessControlEntry(CmsRequestContext context, CmsResource resource, CmsAccessControlEntry acEntry) throws CmsException {
// get the old values
long dateLastModified = resource.getDateLastModified();
CmsUUID userLastModified = resource.getUserLastModified();
checkPermissions(context, resource, I_CmsConstants.C_CONTROL_ACCESS);
m_userDriver.writeAccessControlEntry(context.currentProject(), acEntry);
clearAccessControlListCache();
touchResource(context, resource, dateLastModified, userLastModified);
}
/**
* Writes the Crontable.<p>
*
* Only a administrator can do this.
*
* @param context the current request context
* @param crontable the creontable
* @throws CmsException if something goes wrong
*/
public void writeCronTable(CmsRequestContext context, String crontable) throws CmsException {
if (isAdmin(context)) {
if (m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_CRONTABLE) == null) {
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_CRONTABLE, crontable);
} else {
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_CRONTABLE, crontable);
}
// TODO enable the cron manager
//OpenCms.getCronManager().writeCronTab(crontable);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeCronTable()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Writes a file to the Cms.<p>
*
* A file can only be written to an offline project.
* The state of the resource is set to CHANGED (1). The file content of the file
* is either updated (if it is already existing in the offline project), or created
* in the offline project (if it is not available there).
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param file the name of the file to write
* @throws CmsException if operation was not succesful
*/
public void writeFile(CmsRequestContext context, CmsFile file) throws CmsException {
// check if the user has write access
checkPermissions(context, file, I_CmsConstants.C_WRITE_ACCESS);
// write-acces was granted - write the file.
//m_vfsDriver.writeFile(context.currentProject(), file, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
m_vfsDriver.writeFileHeader(context.currentProject(), file, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
m_vfsDriver.writeFileContent(file.getFileId(), file.getContents(), context.currentProject().getId(), false);
if (file.getState() == I_CmsConstants.C_STATE_UNCHANGED) {
file.setState(I_CmsConstants.C_STATE_CHANGED);
}
// update the cache
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", file)));
}
/**
* Writes the file extensions.<p>
*
* Users, which are in the group for administrators are authorized.
*
* @param context the current request context
* @param extensions holds extensions as keys and resourcetypes (Stings) as values
* @throws CmsException if operation was not succesful
*/
public void writeFileExtensions(CmsRequestContext context, Hashtable extensions) throws CmsException {
if (extensions != null) {
if (isAdmin(context)) {
Enumeration enu = extensions.keys();
while (enu.hasMoreElements()) {
String key = (String)enu.nextElement();
validFilename(key);
}
if (m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS) == null) {
// the property wasn't set before.
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS, extensions);
} else {
// overwrite the property.
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_EXTENSIONS, extensions);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeFileExtensions() ", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
}
/**
* Writes a fileheader to the Cms.<p>
*
* A file can only be written to an offline project.
* The state of the resource is set to CHANGED (1). The file content of the file
* is either updated (if it is already existing in the offline project), or created
* in the offline project (if it is not available there).
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* </ul>
*
* @param context the current request context
* @param file the file to write
*
* @throws CmsException if operation was not succesful
*/
public void writeFileHeader(CmsRequestContext context, CmsFile file) throws CmsException {
// check if the user has write access
checkPermissions(context, file, I_CmsConstants.C_WRITE_ACCESS);
// write-acces was granted - write the file.
m_vfsDriver.writeFileHeader(context.currentProject(), file, C_UPDATE_STRUCTURE_STATE, context.currentUser().getId());
if (file.getState() == I_CmsConstants.C_STATE_UNCHANGED) {
file.setState(I_CmsConstants.C_STATE_CHANGED);
}
// update the cache
//clearResourceCache(file.getResourceName(), context.currentProject(), context.currentUser());
clearResourceCache();
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", file)));
}
/**
* Writes an already existing group in the Cms.<p>
*
* Only the admin can do this.
*
* @param context the current request context
* @param group the group that should be written to the Cms
* @throws CmsException if operation was not succesfull
*/
public void writeGroup(CmsRequestContext context, CmsGroup group) throws CmsException {
// Check the security
if (isAdmin(context)) {
m_userDriver.writeGroup(group);
m_groupCache.put(new CacheId(group), group);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeGroup() " + group.getName(), CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Writes the Linkchecktable.<p>
*
* Only a administrator can do this.
*
* @param context the current request context
* @param linkchecktable the hashtable that contains the links that were not reachable
* @throws CmsException if operation was not succesfull
*/
public void writeLinkCheckTable(CmsRequestContext context, Hashtable linkchecktable) throws CmsException {
if (isAdmin(context)) {
if (m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_LINKCHECKTABLE) == null) {
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_LINKCHECKTABLE, linkchecktable);
} else {
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_LINKCHECKTABLE, linkchecktable);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeLinkCheckTable()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Writes the package for the system.<p>
*
* This path is used for db-export and db-import as well as module packages.
*
* @param context the current request context
* @param path the package path
* @throws CmsException if operation ws not successful
*/
public void writePackagePath(CmsRequestContext context, String path) throws CmsException {
// check the security
if (isAdmin(context)) {
// security is ok - write the exportpath.
if (m_projectDriver.readSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_PACKAGEPATH) == null) {
// the property wasn't set before.
m_projectDriver.createSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_PACKAGEPATH, path);
} else {
// overwrite the property.
m_projectDriver.writeSystemProperty(I_CmsConstants.C_SYSTEMPROPERTY_PACKAGEPATH, path);
}
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writePackagePath()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Writes a resource and its properties to the Cms.<p>
*
* A resource can only be written to an offline project.
* The state of the resource is set to CHANGED (1). The file content of the file
* is either updated (if it is already existing in the offline project), or created
* in the offline project (if it is not available there).
*
* Access is granted, if:
* <ul>
* <li>the user has access to the project</li>
* <li>the user can write the resource</li>
* <li>the resource is locked by the callingUser</li>
* <li>the user is the owner of the resource or administrator<li>
* </ul>
*
* @param context the current request context
* @param resourcename the name of the resource to write
* @param properties the properties of the resource
* @param filecontent the new filecontent of the resource
* @throws CmsException if operation was not succesful
*/
public void writeResource(CmsRequestContext context, String resourcename, List properties, byte[] filecontent) throws CmsException {
CmsResource resource = readFileHeader(context, resourcename, true);
// check if the user has write access
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
m_vfsDriver.writeResource(context.currentProject(), resource, filecontent, C_UPDATE_STRUCTURE_STATE, context.currentUser().getId());
// mark the resource as modified in the current project
m_vfsDriver.writeLastModifiedProjectId(context.currentProject(), context.currentProject().getId(), resource);
if (resource.getState() == I_CmsConstants.C_STATE_UNCHANGED) {
resource.setState(I_CmsConstants.C_STATE_CHANGED);
}
// write the properties
m_vfsDriver.writePropertyObjects(context.currentProject(), resource, properties);
// update the cache
//clearResourceCache(resource.getResourceName(), context.currentProject(), context.currentUser());
clearResourceCache();
filecontent = null;
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_MODIFIED, Collections.singletonMap("resource", resource)));
}
/**
* Inserts an entry in the published resource table.<p>
*
* This is done during static export.
* @param context the current request context
* @param resourceName The name of the resource to be added to the static export
* @param linkType the type of resource exported (0= non-paramter, 1=parameter)
* @param linkParameter the parameters added to the resource
* @param timestamp a timestamp for writing the data into the db
* @throws CmsException if something goes wrong
*/
public void writeStaticExportPublishedResource(CmsRequestContext context, String resourceName, int linkType, String linkParameter, long timestamp) throws CmsException {
m_projectDriver.writeStaticExportPublishedResource(context.currentProject(), resourceName, linkType, linkParameter, timestamp);
}
/**
* Writes a new user tasklog for a task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskid the Id of the task
* @param comment description for the log
* @throws CmsException if something goes wrong
*/
public void writeTaskLog(CmsRequestContext context, int taskid, String comment) throws CmsException {
m_workflowDriver.writeTaskLog(taskid, context.currentUser().getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, I_CmsConstants.C_TASKLOG_USER);
}
/**
* Writes a new user tasklog for a task.<p>
*
* All users are granted.
*
* @param context the current request context
* @param taskId the Id of the task
* @param comment description for the log
* @param type type of the tasklog. User tasktypes must be greater then 100
* @throws CmsException something goes wrong
*/
public void writeTaskLog(CmsRequestContext context, int taskId, String comment, int type) throws CmsException {
m_workflowDriver.writeTaskLog(taskId, context.currentUser().getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, type);
}
/**
* Updates the user information.<p>
*
* Only users, which are in the group "administrators" are granted.
*
* @param context the current request context
* @param user The user to be updated
*
* @throws CmsException if operation was not succesful
*/
public void writeUser(CmsRequestContext context, CmsUser user) throws CmsException {
// Check the security
if (isAdmin(context) || (context.currentUser().equals(user))) {
// prevent the admin to be set disabled!
if (isAdmin(context)) {
user.setEnabled();
}
m_userDriver.writeUser(user);
// update the cache
clearUserCache(user);
putUserInCache(user);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeUser() " + user.getName(), CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED);
}
}
/**
* Updates the user information of a web user.<p>
*
* Only users of the user type webuser can be updated this way.<p>
*
* @param user the user to be updated
*
* @throws CmsException if operation was not succesful
*/
public void writeWebUser(CmsUser user) throws CmsException {
// Check the security
if (user.isWebUser()) {
m_userDriver.writeUser(user);
// update the cache
clearUserCache(user);
putUserInCache(user);
} else {
throw new CmsSecurityException("[" + this.getClass().getName() + "] writeWebUser() " + user.getName(), CmsSecurityException.C_SECURITY_NO_PERMISSIONS);
}
}
/**
* Reads the resources that were published in a publish task for a given publish history ID.<p>
*
* @param context the current request context
* @param publishHistoryId unique int ID to identify each publish task in the publish history
* @return a List of CmsPublishedResource objects
* @throws CmsException if something goes wrong
*/
public List readPublishedResources(CmsRequestContext context, CmsUUID publishHistoryId) throws CmsException {
return getProjectDriver().readPublishedResources(context.currentProject().getId(), publishHistoryId);
}
/**
* Update the export points.<p>
*
* All files and folders "inside" an export point are written.<p>
*
* @param context the current request context
* @param report an I_CmsReport instance to print output message, or null to write messages to the log file
*/
public void updateExportPoints(CmsRequestContext context, I_CmsReport report) {
Set exportPoints = null;
String currentExportPoint = null;
List resources = (List) new ArrayList();
Iterator i = null;
CmsResource currentResource = null;
CmsExportPointDriver exportPointDriver = null;
CmsProject oldProject = null;
try {
// save the current project before we switch to the online project
oldProject = context.currentProject();
context.setCurrentProject(readProject(I_CmsConstants.C_PROJECT_ONLINE_ID));
// read the export points and return immediately if there are no export points at all
exportPoints = OpenCms.getExportPoints();
if (exportPoints.size() == 0) {
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn("No export points configured at all.");
}
return;
}
// the report may be null if the export points indicated by an event on a remote server
if (report == null) {
report = (I_CmsReport) new CmsLogReport();
}
// create a disc driver to write exports
exportPointDriver = new CmsExportPointDriver(exportPoints);
// the export point hash table contains RFS export paths keyed by their internal VFS paths
i = exportPointDriver.getExportPointPaths().iterator();
while (i.hasNext()) {
currentExportPoint = (String) i.next();
// print some report messages
if (OpenCms.getLog(this).isInfoEnabled()) {
OpenCms.getLog(this).info("Writing export point " + currentExportPoint);
}
try {
resources = readAllSubResourcesInDfs(context, currentExportPoint, -1);
setFullResourceNames(context, resources);
Iterator j = resources.iterator();
while (j.hasNext()) {
currentResource = (CmsResource) j.next();
if (currentResource.getType() == CmsResourceTypeFolder.C_RESOURCE_TYPE_ID) {
// export the folder
exportPointDriver.createFolder(currentResource.getRootPath(), currentExportPoint);
} else {
// try to create the exportpoint folder
exportPointDriver.createFolder(currentExportPoint, currentExportPoint);
// export the file content online
CmsFile file = getVfsDriver().readFile(I_CmsConstants.C_PROJECT_ONLINE_ID, false, currentResource.getStructureId());
file.setFullResourceName(currentResource.getRootPath());
writeExportPoint(context, exportPointDriver, currentExportPoint, file);
}
}
} catch (CmsException e) {
// there might exist export points without corresponding resources in the VFS
// -> ingore exceptions which are not "resource not found" exception quiet here
if (e.getType() != CmsException.C_NOT_FOUND) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error updating export points", e);
}
}
}
}
} catch (CmsException e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error updating export points", e);
}
} finally {
context.setCurrentProject(oldProject);
}
}
/**
* Writes all export points into the file system for a publish task
* specified by its publish history ID.<p>
*
* @param context the current request context
* @param report an I_CmsReport instance to print output message, or null to write messages to the log file
* @param publishHistoryId unique int ID to identify each publish task in the publish history
*/
public void writeExportPoints(CmsRequestContext context, I_CmsReport report, CmsUUID publishHistoryId) {
Set exportPoints = null;
CmsExportPointDriver exportPointDriver = null;
List publishedResources = null;
CmsPublishedResource currentPublishedResource = null;
String currentExportKey = null;
boolean printReportHeaders = false;
try {
// read the export points and return immediately if there are no export points at all
exportPoints = OpenCms.getExportPoints();
if (exportPoints.size() == 0) {
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn("No export points configured at all.");
}
return;
}
// the report may be null if the export points indicated by an event on a remote server
if (report == null) {
report = (I_CmsReport) new CmsLogReport();
}
// read the "published resources" for the specified publish history ID
publishedResources = getProjectDriver().readPublishedResources(context.currentProject().getId(), publishHistoryId);
if (publishedResources.size() == 0) {
if (OpenCms.getLog(this).isWarnEnabled()) {
OpenCms.getLog(this).warn("No published resources in the publish history for the specified ID " + publishHistoryId + " found.");
}
return;
}
// create a disc driver to write exports
exportPointDriver = new CmsExportPointDriver(exportPoints);
// iterate over all published resources to export them eventually
Iterator i = publishedResources.iterator();
while (i.hasNext()) {
currentPublishedResource = (CmsPublishedResource) i.next();
currentExportKey = exportPointDriver.getExportPoint(currentPublishedResource.getRootPath());
if (currentExportKey != null) {
if (!printReportHeaders) {
report.println(report.key("report.export_points_write_begin"), I_CmsReport.C_FORMAT_HEADLINE);
printReportHeaders = true;
}
if (currentPublishedResource.getType() == CmsResourceTypeFolder.C_RESOURCE_TYPE_ID) {
// export the folder
if (currentPublishedResource.getState() == I_CmsConstants.C_STATE_DELETED) {
exportPointDriver.removeResource(currentPublishedResource.getRootPath(), currentExportKey);
} else {
exportPointDriver.createFolder(currentPublishedResource.getRootPath(), currentExportKey);
}
} else {
// export the file
if (currentPublishedResource.getState() == I_CmsConstants.C_STATE_DELETED) {
exportPointDriver.removeResource(currentPublishedResource.getRootPath(), currentExportKey);
} else {
// read the file content online
CmsFile file = getVfsDriver().readFile(I_CmsConstants.C_PROJECT_ONLINE_ID, false, currentPublishedResource.getStructureId());
file.setFullResourceName(currentPublishedResource.getRootPath());
writeExportPoint(context, exportPointDriver, currentExportKey, file);
}
}
// print some report messages
if (currentPublishedResource.getState() == I_CmsConstants.C_STATE_DELETED) {
report.print(report.key("report.export_points_delete"), I_CmsReport.C_FORMAT_NOTE);
report.print(currentPublishedResource.getRootPath());
report.print(report.key("report.dots"));
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
} else {
report.print(report.key("report.export_points_write"), I_CmsReport.C_FORMAT_NOTE);
report.print(currentPublishedResource.getRootPath());
report.print(report.key("report.dots"));
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
}
}
}
} catch (CmsException e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error writing export points", e);
}
} finally {
if (printReportHeaders) {
report.println(report.key("report.export_points_write_end"), I_CmsReport.C_FORMAT_HEADLINE);
}
}
}
/**
* Exports a specified resource into the local filesystem as an "export point".<p>
*
* @param context the current request context
* @param discAccess the export point driver
* @param exportKey the export key of the export point
* @param file the file that gets exported
* @throws CmsException if something goes wrong
*/
private void writeExportPoint(
CmsRequestContext context,
CmsExportPointDriver discAccess,
String exportKey,
CmsFile file) throws CmsException {
byte[] contents = null;
String encoding = null;
CmsProperty property = null;
try {
// make sure files are written using the correct character encoding
contents = file.getContents();
property = getVfsDriver().readPropertyObject(
I_CmsConstants.C_PROPERTY_CONTENT_ENCODING,
context.currentProject(),
file);
encoding = (property != null) ? property.getValue() : null;
if (encoding != null) {
// only files that have the encodig property set will be encoded,
// other files will be ignored. images etc. are not touched.
try {
contents = (new String(contents, encoding)).getBytes();
} catch (UnsupportedEncodingException e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Unsupported encoding of " + file.toString(), e);
}
throw new CmsException("Unsupported encoding of " + file.toString(), e);
}
}
discAccess.writeFile(file.getRootPath(), exportKey, contents);
} catch (Exception e) {
if (OpenCms.getLog(this).isErrorEnabled()) {
OpenCms.getLog(this).error("Error writing export point of " + file.toString(), e);
}
throw new CmsException("Error writing export point of " + file.toString(), e);
}
contents = null;
}
/**
* Completes all post-publishing tasks for a "directly" published COS resource.<p>
*
* @param context the current request context
* @param publishedBoResource the CmsPublishedResource onject representing the published COS resource
* @param publishId unique int ID to identify each publish task in the publish history
* @param tagId the backup tag revision
* @throws CmsException if something goes wrong
*/
public void postPublishBoResource(CmsRequestContext context, CmsPublishedResource publishedBoResource, CmsUUID publishId, int tagId) throws CmsException {
m_projectDriver.writePublishHistory(context.currentProject(), publishId, tagId, publishedBoResource.getContentDefinitionName(), publishedBoResource.getMasterId(), publishedBoResource.getType(), publishedBoResource.getState());
}
/**
* Returns a Cms publish list object containing the Cms resources that actually get published.<p>
*
* <ul>
* <li>
* <b>Case 1 (publish project)</b>: all new/changed/deleted Cms file resources in the current (offline)
* project are inspected whether they would get published or not.
* </li>
* <li>
* <b>Case 2 (direct publish a resource)</b>: a specified Cms file resource and optionally it's siblings
* are inspected whether they get published.
* </li>
* </ul>
*
* All Cms resources inside the publish ist are equipped with their full resource name including
* the site root.<p>
*
* Please refer to the source code of this method for the rules on how to decide whether a
* new/changed/deleted Cms resource can be published or not.<p>
*
* @param context the current request context
* @param directPublishResource a Cms resource to be published directly (in case 2), or null (in case 1)
* @param directPublishSiblings true, if all eventual siblings of the direct published resource should also get published (in case 2)
* @param report an instance of I_CmsReport to print messages
* @return a publish list with all new/changed/deleted files from the current (offline) project that will be published actually
* @throws CmsException if something goes wrong
* @see org.opencms.db.CmsPublishList
*/
public synchronized CmsPublishList getPublishList(CmsRequestContext context, CmsResource directPublishResource, boolean directPublishSiblings, I_CmsReport report) throws CmsException {
CmsPublishList publishList = null;
List offlineFiles = null;
List siblings = null;
List projectResources = null;
List offlineFolders = null;
List sortedFolderList = null;
Iterator i = null;
Iterator j = null;
Map sortedFolderMap = null;
CmsResource currentSibling = null;
CmsResource currentFileHeader = null;
boolean directPublish = false;
boolean directPublishFile = false;
boolean publishCurrentResource = false;
String currentResourceName = null;
String currentSiblingName = null;
CmsLock currentLock = null;
CmsFolder currentFolder = null;
List deletedFolders = null;
CmsProperty property = null;
try {
report.println(report.key("report.publish_prepare_resources"), I_CmsReport.C_FORMAT_HEADLINE);
////////////////////////////////////////////////////////////////////////////////////////
// read the project resources of the project that gets published
// (= folders that belong to the current project)
report.print(report.key("report.publish_read_projectresources") + report.key("report.dots"));
projectResources = readProjectResources(context.currentProject());
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
////////////////////////////////////////////////////////////////////////////////////////
// construct a publish list
directPublish = directPublishResource != null;
directPublishFile = directPublish && directPublishResource.isFile();
if (directPublishFile) {
// a file resource gets published directly
publishList = new CmsPublishList(directPublishResource, directPublishFile);
} else {
if (directPublish) {
// a folder resource gets published directly
publishList = new CmsPublishList(directPublishResource, directPublishFile);
} else {
// a project gets published directly
publishList = new CmsPublishList();
}
}
////////////////////////////////////////////////////////////////////////////////////////
// identify all new/changed/deleted Cms folder resources to be published
// don't select and sort unpublished folders if a file gets published directly
if (!directPublishFile) {
report.println(report.key("report.publish_prepare_folders"), I_CmsReport.C_FORMAT_HEADLINE);
sortedFolderMap = (Map) new HashMap();
deletedFolders = (List) new ArrayList();
// read all changed/new/deleted folders
report.print(report.key("report.publish_read_projectfolders") + report.key("report.dots"));
offlineFolders = getVfsDriver().readFolders(context.currentProject().getId());
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
// sort out all folders that will not be published
report.print(report.key("report.publish_filter_folders") + report.key("report.dots"));
i = offlineFolders.iterator();
while (i.hasNext()) {
publishCurrentResource = false;
currentFolder = (CmsFolder) i.next();
currentResourceName = readPath(context, currentFolder, true);
currentFolder.setFullResourceName(currentResourceName);
currentLock = getLock(context, currentResourceName);
// the resource must have either a new/deleted state in the link or a new/delete state in the resource record
publishCurrentResource = currentFolder.getState() > I_CmsConstants.C_STATE_UNCHANGED;
if (directPublish) {
// the resource must be a sub resource of the direct-publish-resource in case of a "direct publish"
publishCurrentResource = publishCurrentResource && currentResourceName.startsWith(publishList.getDirectPublishResourceName());
} else {
// the resource must have a changed state and must be changed in the project that is currently published
publishCurrentResource = publishCurrentResource && currentFolder.getProjectLastModified() == context.currentProject().getId();
// the resource must be in one of the paths defined for the project
publishCurrentResource = publishCurrentResource && CmsProject.isInsideProject(projectResources, currentFolder);
}
// the resource must be unlocked
publishCurrentResource = publishCurrentResource && currentLock.isNullLock();
if (publishCurrentResource) {
sortedFolderMap.put(currentResourceName, currentFolder);
}
}
// ensure that the folders appear in the correct (DFS) top-down tree order
sortedFolderList = (List) new ArrayList(sortedFolderMap.keySet());
Collections.sort(sortedFolderList);
// split the folders up into new/changed folders and deleted folders
i = sortedFolderList.iterator();
while (i.hasNext()) {
currentResourceName = (String) i.next();
currentFolder = (CmsFolder) sortedFolderMap.get(currentResourceName);
if (currentFolder.getState() == I_CmsConstants.C_STATE_DELETED) {
deletedFolders.add(currentResourceName);
} else {
publishList.addFolder(currentFolder);
}
}
if (deletedFolders.size() > 0) {
// ensure that the deleted folders appear in the correct (DFS) bottom-up tree order
Collections.sort(deletedFolders);
Collections.reverse(deletedFolders);
i = deletedFolders.iterator();
while (i.hasNext()) {
currentResourceName = (String) i.next();
currentFolder = (CmsFolder) sortedFolderMap.get(currentResourceName);
publishList.addDeletedFolder(currentFolder);
}
}
// clean up any objects that are not needed anymore instantly
if (sortedFolderList != null) {
sortedFolderList.clear();
sortedFolderList = null;
}
if (sortedFolderMap != null) {
sortedFolderMap.clear();
sortedFolderMap = null;
}
if (offlineFolders != null) {
offlineFolders.clear();
offlineFolders = null;
}
if (deletedFolders != null) {
deletedFolders.clear();
deletedFolders = null;
}
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
report.println(report.key("report.publish_prepare_folders_finished"), I_CmsReport.C_FORMAT_HEADLINE);
} else {
// a file gets published directly- the list of unpublished folders remain empty
}
///////////////////////////////////////////////////////////////////////////////////////////
// identify all new/changed/deleted Cms file resources to be published
report.println(report.key("report.publish_prepare_files"), I_CmsReport.C_FORMAT_HEADLINE);
report.print(report.key("report.publish_read_projectfiles") + report.key("report.dots"));
if (directPublishFile) {
// add this resource as a candidate to the unpublished offline file headers
offlineFiles = (List) new ArrayList();
offlineFiles.add(directPublishResource);
if (directPublishSiblings) {
// add optionally all siblings of the direct published resource as candidates
siblings = readSiblings(context, directPublishResource.getRootPath(), false, true);
i = siblings.iterator();
while (i.hasNext()) {
currentSibling = (CmsResource) i.next();
try {
getVfsDriver().readFolder(I_CmsConstants.C_PROJECT_ONLINE_ID, currentSibling.getParentStructureId());
offlineFiles.add(currentSibling);
} catch (CmsException e) {
// the parent folder of the current sibling
// is not yet published- skip this sibling
}
}
}
} else {
// add all unpublished offline file headers as candidates
offlineFiles = getVfsDriver().readFiles(context.currentProject().getId());
}
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
// sort out candidates that will not be published
report.print(report.key("report.publish_filter_files") + report.key("report.dots"));
i = offlineFiles.iterator();
while (i.hasNext()) {
publishCurrentResource = false;
currentFileHeader = (CmsResource) i.next();
currentResourceName = readPath(context, currentFileHeader, true);
currentFileHeader.setFullResourceName(currentResourceName);
currentLock = getLock(context, currentResourceName);
switch (currentFileHeader.getState()) {
// the current resource is deleted
case I_CmsConstants.C_STATE_DELETED :
// it is published, if it was changed to deleted in the current project
property = getVfsDriver().readPropertyObject(I_CmsConstants.C_PROPERTY_INTERNAL, context.currentProject(), currentFileHeader);
String delProject = (property != null) ? property.getValue() : null;
// a project gets published or a folder gets published directly
if (delProject != null && delProject.equals("" + context.currentProject().getId())) {
publishCurrentResource = true;
} else {
publishCurrentResource = false;
}
//}
break;
// the current resource is new
case I_CmsConstants.C_STATE_NEW :
// it is published, if it was created in the current project
// or if it is a new sibling of another resource that is currently not changed in any project
publishCurrentResource = currentFileHeader.getProjectLastModified() == context.currentProject().getId() || currentFileHeader.getProjectLastModified() == 0;
break;
// the current resource is changed
case I_CmsConstants.C_STATE_CHANGED :
// it is published, if it was changed in the current project
publishCurrentResource = currentFileHeader.getProjectLastModified() == context.currentProject().getId();
break;
// the current resource is unchanged
case I_CmsConstants.C_STATE_UNCHANGED :
default :
// so it is not published
publishCurrentResource = false;
break;
}
if (directPublish) {
if (directPublishResource.isFolder()) {
if (directPublishSiblings) {
// a resource must be published if it is inside the folder which was selected
// for direct publishing, or if one of its siblings is inside the folder
if (currentFileHeader.getLinkCount() == 1) {
// this resource has no siblings
// the resource must be a sub resource of the direct-publish-resource in
// case of a "direct publish"
publishCurrentResource = publishCurrentResource && currentResourceName.startsWith(directPublishResource.getRootPath());
} else {
// the resource has some siblings, so check if they are inside the
// folder to be published
siblings = readSiblings(context, currentResourceName, true, true);
j = siblings.iterator();
boolean siblingInside = false;
while (j.hasNext()) {
currentSibling = (CmsResource) j.next();
currentSiblingName = readPath(context, currentSibling, true);
if (currentSiblingName.startsWith(directPublishResource.getRootPath())) {
siblingInside = true;
break;
}
}
publishCurrentResource = publishCurrentResource && siblingInside;
}
} else {
// the resource must be a sub resource of the direct-publish-resource in
// case of a "direct publish"
publishCurrentResource = publishCurrentResource && currentResourceName.startsWith(directPublishResource.getRootPath());
}
}
} else {
// the resource must be in one of the paths defined for the project
publishCurrentResource = publishCurrentResource && CmsProject.isInsideProject(projectResources, currentFileHeader);
}
// do not publish resources that are locked
publishCurrentResource = publishCurrentResource && currentLock.isNullLock();
// NOTE: temporary files are not removed any longer while publishing
if (currentFileHeader.getName().startsWith(I_CmsConstants.C_TEMP_PREFIX)) {
// trash the current resource if it is a temporary file
getVfsDriver().deleteProperties(context.currentProject().getId(), currentFileHeader);
getVfsDriver().removeFile(context.currentProject(), currentFileHeader, true);
}
if (!publishCurrentResource) {
i.remove();
}
}
// add the new/changed/deleted Cms file resources to the publish list
publishList.addFiles(offlineFiles);
// clean up any objects that are not needed anymore instantly
offlineFiles.clear();
offlineFiles = null;
report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
report.println(report.key("report.publish_prepare_files_finished"), I_CmsReport.C_FORMAT_HEADLINE);
////////////////////////////////////////////////////////////////////////////////////////////
report.println(report.key("report.publish_prepare_resources_finished"), I_CmsReport.C_FORMAT_HEADLINE);
} catch (OutOfMemoryError o) {
if (OpenCms.getLog(this).isFatalEnabled()) {
OpenCms.getLog(this).fatal("Out of memory error while publish list is built", o);
}
// clear all caches to reclaim memory
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false));
// force a complete object finalization and garbage collection
System.runFinalization();
Runtime.getRuntime().runFinalization();
System.gc();
Runtime.getRuntime().gc();
throw new CmsException("Out of memory error while publish list is built", o);
}
return publishList;
}
/**
* Returns the HTML link validator.<p>
*
* @return the HTML link validator
* @see CmsHtmlLinkValidator
*/
public CmsHtmlLinkValidator getHtmlLinkValidator() {
return m_htmlLinkValidator;
}
/**
* Validates the Cms resources in a Cms publish list.<p>
*
* @param cms the current user's Cms object
* @param publishList a Cms publish list
* @param report an instance of I_CmsReport to print messages
* @return a map with lists of invalid links keyed by resource names
* @throws Exception if something goes wrong
* @see #getPublishList(CmsRequestContext, CmsResource, boolean, I_CmsReport)
*/
public Map validateHtmlLinks(CmsObject cms, CmsPublishList publishList, I_CmsReport report) throws Exception {
return getHtmlLinkValidator().validateResources(cms, publishList.getFileList(), report);
}
/**
* Updates the date information in the request context.<p>
*
* @param context the context to update
* @param resource the resource to get the date information from
*/
private void updateContextDates(CmsRequestContext context, CmsResource resource) {
CmsFlexRequestContextInfo info = (CmsFlexRequestContextInfo) context.getAttribute(I_CmsConstants.C_HEADER_LAST_MODIFIED);
if (info != null) {
info.updateDateLastModified(resource.getDateLastModified());
}
}
/**
* Writes a property object to the database mapped to a specified resource.<p>
*
* @param context the context of the current request
* @param resourceName the name of resource where the property is mapped to
* @param property a CmsProperty object containing a structure and/or resource value
* @throws CmsException if something goes wrong
*/
public void writePropertyObject(CmsRequestContext context, String resourceName, CmsProperty property) throws CmsException {
CmsResource resource = null;
try {
// read the file header
resource = readFileHeader(context, resourceName);
// check the permissions
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
// write the property
m_vfsDriver.writePropertyObject(context.currentProject(), resource, property);
// update the resource state
if (resource.isFile()) {
m_vfsDriver.writeFileHeader(context.currentProject(), (CmsFile)resource, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
} else {
m_vfsDriver.writeFolder(context.currentProject(), (CmsFolder)resource, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
}
} finally {
// update the driver manager cache
clearResourceCache();
m_propertyCache.clear();
// fire an event that a property of a resource has been modified
Map data = (Map) new HashMap();
data.put("resource", resource);
data.put("property", property);
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROPERTY_MODIFIED, data));
}
}
/**
* Writes a list of property objects to the database mapped to a specified resource.<p>
*
* @param context the context of the current request
* @param resourceName the name of resource where the property is mapped to
* @param properties a list of CmsPropertys object containing a structure and/or resource value
* @throws CmsException if something goes wrong
*/
public void writePropertyObjects(CmsRequestContext context, String resourceName, List properties) throws CmsException {
CmsProperty property = null;
CmsResource resource = null;
try {
// read the file header
resource = readFileHeader(context, resourceName);
// check the permissions
checkPermissions(context, resource, I_CmsConstants.C_WRITE_ACCESS);
for (int i = 0; i < properties.size(); i++) {
// write the property
property = (CmsProperty) properties.get(i);
m_vfsDriver.writePropertyObject(context.currentProject(), resource, property);
}
// update the resource state
if (resource.isFile()) {
m_vfsDriver.writeFileHeader(context.currentProject(), (CmsFile) resource, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
} else {
m_vfsDriver.writeFolder(context.currentProject(), (CmsFolder) resource, C_UPDATE_RESOURCE_STATE, context.currentUser().getId());
}
} finally {
// update the driver manager cache
clearResourceCache();
m_propertyCache.clear();
// fire an event that the properties of a resource have been modified
OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_RESOURCE_AND_PROPERTIES_MODIFIED, Collections.singletonMap("resource", resource)));
}
}
/**
* Reads all property objects mapped to a specified resource from the database.<p>
*
* Returns an empty list if no properties are found at all.<p>
*
* @param context the context of the current request
* @param resourceName the name of resource where the property is mapped to
* @param siteRoot the current site root
* @param search true, if the properties should be searched on all parent folders if not found on the resource
* @return a list of CmsProperty objects containing the structure and/or resource value
* @throws CmsException if something goes wrong
*/
public List readPropertyObjects(CmsRequestContext context, String resourceName, String siteRoot, boolean search) throws CmsException {
// read the file header
CmsResource resource = readFileHeader(context, resourceName);
// check the permissions
checkPermissions(context, resource, I_CmsConstants.C_READ_OR_VIEW_ACCESS);
search = search && (siteRoot != null);
// check if we have the result already cached
String cacheKey = getCacheKey(C_CACHE_ALL_PROPERTIES + search, context.currentProject().getId(), resource.getRootPath());
List value = (List) m_propertyCache.get(cacheKey);
if (value == null) {
// result not cached, let's look it up in the DB
if (search) {
boolean cont;
siteRoot += "/";
value = (List) new ArrayList();
List parentValue;
do {
try {
parentValue = readPropertyObjects(context, resourceName, siteRoot, false);
parentValue.addAll(value);
value.clear();
value.addAll(parentValue);
resourceName = CmsResource.getParentFolder(resource.getRootPath());
cont = (!"/".equals(resourceName));
} catch (CmsSecurityException se) {
// a security exception (probably no read permission) we return the current result
cont = false;
}
} while (cont);
} else {
value = m_vfsDriver.readPropertyObjects(context.currentProject(), resource);
}
// store the result in the cache
m_propertyCache.put(cacheKey, value);
}
return (List) new ArrayList(value);
}
/**
* Reads a property object from the database specified by it's key name mapped to a resource.<p>
*
* Returns null if the property is not found.<p>
*
* @param context the context of the current request
* @param resourceName the name of resource where the property is mapped to
* @param siteRoot the current site root
* @param key the property key name
* @param search true, if the property should be searched on all parent folders if not found on the resource
* @return a CmsProperty object containing the structure and/or resource value
* @throws CmsException if something goes wrong
*/
public CmsProperty readPropertyObject(CmsRequestContext context, String resourceName, String siteRoot, String key, boolean search) throws CmsException {
// read the resource
CmsResource resource = readFileHeader(context, resourceName);
// check the security
checkPermissions(context, resource, I_CmsConstants.C_READ_OR_VIEW_ACCESS);
search = search && (siteRoot != null);
// check if we have the result already cached
String cacheKey = getCacheKey(key + search, context.currentProject().getId(), resource.getRootPath());
CmsProperty value = (CmsProperty) m_propertyCache.get(cacheKey);
if (value == null) {
// check if the map of all properties for this resource is already cached
String cacheKey2 = getCacheKey(C_CACHE_ALL_PROPERTIES + search, context.currentProject().getId(), resource.getRootPath());
List allProperties = (List) m_propertyCache.get(cacheKey2);
if (allProperties != null) {
// list of properties already read, look up value there
// unfortunatly, the list is always case sentitive, but in MySQL
// using readProperty() is not, so to make really sure a property is found
// we must look up all the entries in the map manually, which should be faster
// than a connect to the DB nevertheless
for (int i = 0; i < allProperties.size(); i++) {
CmsProperty property = (CmsProperty) allProperties.get(i);
if (property.getKey().equalsIgnoreCase(key)) {
value = property;
break;
}
}
} else if (search) {
// result not cached, look it up recursivly with search enabled
String cacheKey3 = getCacheKey(key + false, context.currentProject().getId(), resource.getRootPath());
value = (CmsProperty) m_propertyCache.get(cacheKey3);
if ((value == null) || (value == CmsProperty.getNullProperty())) {
boolean cont;
siteRoot += "/";
do {
try {
value = readPropertyObject(context, resourceName, siteRoot, key, false);
cont = ((value == null) && (!"/".equals(resourceName)));
} catch (CmsSecurityException se) {
// a security exception (probably no read permission) we return the current result
cont = false;
}
if (cont) {
resourceName = CmsResource.getParentFolder(resourceName);
}
} while (cont);
}
} else {
// result not cached, look it up in the DB without search
value = m_vfsDriver.readPropertyObject(key, context.currentProject(), resource);
}
if (value == null) {
value = CmsProperty.getNullProperty();
}
// store the result in the cache
m_propertyCache.put(cacheKey, value);
}
return (value == CmsProperty.getNullProperty()) ? null : value;
}
}
| Improved new property method - now an object is always returned, never 'null'
| src/org/opencms/db/CmsDriverManager.java | Improved new property method - now an object is always returned, never 'null' | <ide><path>rc/org/opencms/db/CmsDriverManager.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/db/CmsDriverManager.java,v $
<del> * Date : $Date: 2004/04/02 17:01:11 $
<del> * Version: $Revision: 1.348 $
<add> * Date : $Date: 2004/04/05 05:33:02 $
<add> * Version: $Revision: 1.349 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Mananagement System
<ide> * @author Thomas Weckert ([email protected])
<ide> * @author Carsten Weinholz ([email protected])
<ide> * @author Michael Emmerich ([email protected])
<del> * @version $Revision: 1.348 $ $Date: 2004/04/02 17:01:11 $
<add> * @version $Revision: 1.349 $ $Date: 2004/04/05 05:33:02 $
<ide> * @since 5.1
<ide> */
<ide> public class CmsDriverManager extends Object implements I_CmsEventListener {
<ide> * @throws CmsException if something goes wrong
<ide> */
<ide> public List readPropertyObjects(CmsRequestContext context, String resourceName, String siteRoot, boolean search) throws CmsException {
<add>
<ide> // read the file header
<ide> CmsResource resource = readFileHeader(context, resourceName);
<ide>
<ide> // check the permissions
<ide> checkPermissions(context, resource, I_CmsConstants.C_READ_OR_VIEW_ACCESS);
<ide>
<add> // check if search mode is enabled
<ide> search = search && (siteRoot != null);
<ide>
<ide> // check if we have the result already cached
<ide> String cacheKey = getCacheKey(C_CACHE_ALL_PROPERTIES + search, context.currentProject().getId(), resource.getRootPath());
<del> List value = (List) m_propertyCache.get(cacheKey);
<add> List value = (List)m_propertyCache.get(cacheKey);
<ide>
<ide> if (value == null) {
<ide> // result not cached, let's look it up in the DB
<ide> if (search) {
<ide> boolean cont;
<ide> siteRoot += "/";
<del> value = (List) new ArrayList();
<add> value = (List)new ArrayList();
<ide> List parentValue;
<ide> do {
<ide> try {
<ide> parentValue.addAll(value);
<ide> value.clear();
<ide> value.addAll(parentValue);
<del> resourceName = CmsResource.getParentFolder(resource.getRootPath());
<add> resourceName = CmsResource.getParentFolder(resourceName);
<ide> cont = (!"/".equals(resourceName));
<ide> } catch (CmsSecurityException se) {
<ide> // a security exception (probably no read permission) we return the current result
<ide> * @throws CmsException if something goes wrong
<ide> */
<ide> public CmsProperty readPropertyObject(CmsRequestContext context, String resourceName, String siteRoot, String key, boolean search) throws CmsException {
<add>
<ide> // read the resource
<ide> CmsResource resource = readFileHeader(context, resourceName);
<ide>
<ide> // check the security
<ide> checkPermissions(context, resource, I_CmsConstants.C_READ_OR_VIEW_ACCESS);
<ide>
<add> // check if search mode is enabled
<ide> search = search && (siteRoot != null);
<ide>
<ide> // check if we have the result already cached
<ide>
<ide> if (allProperties != null) {
<ide> // list of properties already read, look up value there
<del> // unfortunatly, the list is always case sentitive, but in MySQL
<del> // using readProperty() is not, so to make really sure a property is found
<del> // we must look up all the entries in the map manually, which should be faster
<del> // than a connect to the DB nevertheless
<ide> for (int i = 0; i < allProperties.size(); i++) {
<ide> CmsProperty property = (CmsProperty) allProperties.get(i);
<del> if (property.getKey().equalsIgnoreCase(key)) {
<add> if (property.getKey().equals(key)) {
<ide> value = property;
<ide> break;
<ide> }
<ide> String cacheKey3 = getCacheKey(key + false, context.currentProject().getId(), resource.getRootPath());
<ide> value = (CmsProperty) m_propertyCache.get(cacheKey3);
<ide>
<del> if ((value == null) || (value == CmsProperty.getNullProperty())) {
<add> if ((value == null) || value.isNullProperty()) {
<ide> boolean cont;
<ide> siteRoot += "/";
<ide> do {
<ide> try {
<ide> value = readPropertyObject(context, resourceName, siteRoot, key, false);
<del> cont = ((value == null) && (!"/".equals(resourceName)));
<add> cont = (value.isNullProperty() && (!"/".equals(resourceName)));
<ide> } catch (CmsSecurityException se) {
<ide> // a security exception (probably no read permission) we return the current result
<ide> cont = false;
<ide> m_propertyCache.put(cacheKey, value);
<ide> }
<ide>
<del> return (value == CmsProperty.getNullProperty()) ? null : value;
<del> }
<del>
<add> return value;
<add> }
<ide> } |
|
JavaScript | mit | c8e48deb33fd4c0713689ed6ad2784504316dd7d | 0 | prometheusresearch/react-forms | /**
* @copyright 2015, Prometheus Research, LLC
*/
import autobind from 'autobind-decorator';
import React, {PropTypes} from 'react';
import * as Stylesheet from 'react-stylesheet';
import Component from './Component';
import Input from './Input';
import ErrorList from './ErrorList';
import Label from './Label';
export default class Field extends Component {
static propTypes = {
...Component.propTypes,
label: PropTypes.string,
children: PropTypes.element,
Input: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
};
static defaultProps = {
Input,
};
static stylesheet = Stylesheet.create({
Root: 'div',
ErrorList: ErrorList,
Label: Label,
InputWrapper: 'div',
});
constructor(props) {
super(props);
this.state = {dirty: false};
}
render() {
let {Input, label, children} = this.props;
let {Root, ErrorList, Label, InputWrapper} = this.props.stylesheet || this.constructor.stylesheet;
let {dirty} = this.state;
let {schema = {}, value, params = {}} = this.formValue;
let showErrors = dirty || params.forceShowErrors;
if (!children) {
children = <Input value={value} onChange={this.onChange} />;
} else {
children = React.cloneElement(
React.Children.only(children),
{value, onChange: this.onChange});
}
return (
<Root onBlur={this.onBlur}>
<Label label={label} schema={schema} />
<InputWrapper>
{children}
</InputWrapper>
{showErrors &&
<ErrorList formValue={this.formValue} />}
</Root>
);
}
@autobind
onBlur() {
this.setState({dirty: true});
}
@autobind
onChange(e) {
let value;
if (e && e.target && e.target.value !== undefined) {
e.stopPropagation();
value = e.target.value;
if (value === '') {
value = null;
}
} else {
value = e;
}
this.formValue.update(value);
this.setState({dirty: true});
}
}
| src/Field.js | /**
* @copyright 2015, Prometheus Research, LLC
*/
import autobind from 'autobind-decorator';
import React, {PropTypes} from 'react';
import * as Stylesheet from 'react-stylesheet';
import Component from './Component';
import Input from './Input';
import ErrorList from './ErrorList';
import Label from './Label';
export default class Field extends Component {
static propTypes = {
...Component.propTypes,
label: PropTypes.string,
children: PropTypes.element,
Input: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
};
static defaultProps = {
Input,
};
static stylesheet = Stylesheet.create({
Root: 'div',
ErrorList: ErrorList,
Label: Label,
InputWrapper: 'div',
});
constructor(props) {
super(props);
this.state = {dirty: false};
}
render() {
let {Input, label, children} = this.props;
let {Root, ErrorList, Label, InputWrapper} = this.props.stylesheet || this.constructor.stylesheet;
let {dirty} = this.state;
let {schema = {}, value, params = {}} = this.formValue;
let showErrors = dirty || params.forceShowErrors;
if (!children) {
children = <Input value={value} onChange={this.onChange} />;
} else {
children = React.cloneElement(
React.Children.only(children),
{value, onChange: this.onChange});
}
return (
<Root onBlur={this.onBlur}>
<Label label={label} schema={schema} />
<InputWrapper>
{children}
</InputWrapper>
{showErrors &&
<ErrorList formValue={this.formValue} />}
</Root>
);
}
@autobind
onBlur() {
this.setState({dirty: true});
}
@autobind
onChange(e) {
let value;
if (e && e.target && e.target.value !== undefined) {
e.stopPropagation();
value = e.target.value;
if (value === '') {
value = undefined;
}
} else {
value = e;
}
this.formValue.update(value);
this.setState({dirty: true});
}
}
| fix(Field): coerce empty string to null
| src/Field.js | fix(Field): coerce empty string to null | <ide><path>rc/Field.js
<ide> e.stopPropagation();
<ide> value = e.target.value;
<ide> if (value === '') {
<del> value = undefined;
<add> value = null;
<ide> }
<ide> } else {
<ide> value = e; |
|
Java | mit | 98bfde110016c696c602bbeb33f9915005522e16 | 0 | rcsir/vk-android-sdk,Vittt2008/vk-android-sdk,Heeby/vk-android-sdk,VKCOM/vk-android-sdk,bossvn/vk-android-sdk,VKCOM/vk-android-sdk,jintoga/vk-android-sdk | //
// Copyright (c) 2014 VK.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.
//
package com.vk.sdk.api.model;
import android.os.Parcel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static com.vk.sdk.api.model.ParseUtils.parseBoolean;
import static com.vk.sdk.api.model.ParseUtils.parseLong;
/**
* Represents full user profile.
*/
@SuppressWarnings("unused")
public class VKApiUserFull extends VKApiUser implements android.os.Parcelable {
/**
* Filed last_seen from VK fields set
*/
public static final String LAST_SEEN = "last_seen";
/**
* Filed bdate from VK fields set
*/
public static final String BDATE = "bdate";
/**
* Filed city from VK fields set
*/
public static final String CITY = "city";
/**
* Filed country from VK fields set
*/
public static final String COUNTRY = "country";
/**
* Filed universities from VK fields set
*/
public static final String UNIVERSITIES = "universities";
/**
* Filed schools from VK fields set
*/
public static final String SCHOOLS = "schools";
/**
* Filed activity from VK fields set
*/
public static final String ACTIVITY = "activity";
/**
* Filed personal from VK fields set
*/
public static final String PERSONAL = "personal";
/**
* Filed sex from VK fields set
*/
public static final String SEX = "sex";
/**
* Filed site from VK fields set
*/
public static final String SITE = "site";
/**
* Filed contacts from VK fields set
*/
public static final String CONTACTS = "contacts";
/**
* Filed can_post from VK fields set
*/
public static final String CAN_POST = "can_post";
/**
* Filed can_see_all_posts from VK fields set
*/
public static final String CAN_SEE_ALL_POSTS = "can_see_all_posts";
/**
* Filed can_write_private_message from VK fields set
*/
public static final String CAN_WRITE_PRIVATE_MESSAGE = "can_write_private_message";
/**
* Filed relation from VK fields set
*/
public static final String RELATION = "relation";
/**
* Filed counters from VK fields set
*/
public static final String COUNTERS = "counters";
/**
* Filed occupation from VK fields set
*/
public static final String OCCUPATION = "occupation";
/**
* Filed activities from VK fields set
*/
public static final String ACTIVITIES = "activities";
/**
* Filed interests from VK fields set
*/
public static final String INTERESTS = "interests";
/**
* Filed movies from VK fields set
*/
public static final String MOVIES = "movies";
/**
* Filed tv from VK fields set
*/
public static final String TV = "tv";
/**
* Filed books from VK fields set
*/
public static final String BOOKS = "books";
/**
* Filed games from VK fields set
*/
public static final String GAMES = "games";
/**
* Filed about from VK fields set
*/
public static final String ABOUT = "about";
/**
* Filed quotes from VK fields set
*/
public static final String QUOTES = "quotes";
/**
* Filed connections from VK fields set
*/
public static final String CONNECTIONS = "connections";
/**
* Filed relatives from VK fields set
*/
public static final String RELATIVES = "relatives";
/**
* Filed wall_default from VK fields set
*/
public static final String WALL_DEFAULT = "wall_default";
/**
* Filed verified from VK fields set
*/
public static final String VERIFIED = "verified";
/**
* Filed screen_name from VK fields set
*/
public static final String SCREEN_NAME = "screen_name";
/**
* Filed blacklisted_by_me from VK fields set
*/
public static final String BLACKLISTED_BY_ME = "blacklisted_by_me";
/**
* Text of user status.
*/
public String activity;
/**
* Audio which broadcasting to status.
*/
public VKApiAudio status_audio;
/**
* User's date of birth. Returned as DD.MM.YYYY or DD.MM (if birth year is hidden).
*/
public String bdate;
/**
* City specified on user's page in "Contacts" section.
*/
public VKApiCity city;
/**
* Country specified on user's page in "Contacts" section.
*/
public VKApiCountry country;
/**
* Last visit date(in Unix time).
*/
public long last_seen;
/**
* List of user's universities
*/
public VKList<VKApiUniversity> universities;
/**
* List of user's schools
*/
public VKList<VKApiSchool> schools;
/**
* Views on smoking.
* @see com.vk.sdk.api.model.VKApiUserFull.Attitude
*/
public int smoking;
/**
* Views on alcohol.
* @see com.vk.sdk.api.model.VKApiUserFull.Attitude
*/
public int alcohol;
/**
* Views on policy.
* @see com.vk.sdk.api.model.VKApiUserFull.Political
*/
public int political;
/**
* Life main stuffs.
* @see com.vk.sdk.api.model.VKApiUserFull.LifeMain
*/
public int life_main;
/**
* People main stuffs.
* @see com.vk.sdk.api.model.VKApiUserFull.PeopleMain
*/
public int people_main;
/**
* Stuffs that inspire the user.
*/
public String inspired_by;
/**
* List of user's languages
*/
public String[] langs;
/**
* Religion of user
*/
public String religion;
/**
* Name of user's account in Facebook
*/
public String facebook;
/**
* ID of user's facebook
*/
public String facebook_name;
/**
* Name of user's account in LiveJournal
*/
public String livejournal;
/**
* Name of user's account in Skype
*/
public String skype;
/**
* URL of user's site
*/
public String site;
/**
* Name of user's account in Twitter
*/
public String twitter;
/**
* Name of user's account in Instagram
*/
public String instagram;
/**
* User's mobile phone number
*/
public String mobile_phone;
/**
* User's home phone number
*/
public String home_phone;
/**
* Page screen name.
*/
public String screen_name;
/**
* Nickname of user.
*/
public String nickname;
/**
* User's activities
*/
public String activities;
/**
* User's interests
*/
public String interests;
/**
* User's favorite movies
*/
public String movies;
/**
* User's favorite TV Shows
*/
public String tv;
/**
* User's favorite books
*/
public String books;
/**
* User's favorite games
*/
public String games;
/**
* User's about information
*/
public String about;
/**
* User's favorite quotes
*/
public String quotes;
/**
* Information whether others can posts on user's wall.
*/
public boolean can_post;
/**
* Information whether others' posts on user's wall can be viewed
*/
public boolean can_see_all_posts;
/**
* Information whether private messages can be sent to this user.
*/
public boolean can_write_private_message;
/**
* Information whether user can comment wall posts.
*/
public boolean wall_comments;
/**
* Information whether the user is banned in VK.
*/
public boolean is_banned;
/**
* Information whether the user is deleted in VK.
*/
public boolean is_deleted;
/**
* Information whether the user's post of wall shows by default.
*/
public boolean wall_default_owner;
/**
* Information whether the user has a verified page in VK
*/
public boolean verified;
/**
* User sex.
* @see com.vk.sdk.api.model.VKApiUserFull.Sex
*/
public int sex;
/**
* Set of user's counters.
*/
public Counters counters;
/**
* Set of user's counters.
*/
public Occupation occupation;
/**
* Relationship status.
* @see com.vk.sdk.api.model.VKApiUserFull.Relation
*/
public int relation;
/**
* List of user's relatives
*/
public VKList<Relative> relatives;
/**
* Information whether the current user has add this user to the blacklist.
*/
public boolean blacklisted_by_me;
public VKApiUserFull(JSONObject from) throws JSONException
{
parse(from);
}
public VKApiUserFull parse(JSONObject user) {
super.parse(user);
// general
last_seen = parseLong(user.optJSONObject(LAST_SEEN), "time");
bdate = user.optString(BDATE);
JSONObject city = user.optJSONObject(CITY);
if(city != null) {
this.city = new VKApiCity().parse(city);
}
JSONObject country = user.optJSONObject(COUNTRY);
if(country != null) {
this.country = new VKApiCountry().parse(country);
}
// education
universities = new VKList<VKApiUniversity>(user.optJSONArray(UNIVERSITIES), VKApiUniversity.class);
schools = new VKList<VKApiSchool>(user.optJSONArray(SCHOOLS), VKApiSchool.class);
// status
activity = user.optString(ACTIVITY);
JSONObject status_audio = user.optJSONObject("status_audio");
if(status_audio != null) this.status_audio = new VKApiAudio().parse(status_audio);
// personal views
JSONObject personal = user.optJSONObject(PERSONAL);
if (personal != null) {
smoking = personal.optInt("smoking");
alcohol = personal.optInt("alcohol");
political = personal.optInt("political");
life_main = personal.optInt("life_main");
people_main = personal.optInt("people_main");
inspired_by = personal.optString("inspired_by");
religion = personal.optString("religion");
if (personal.has("langs")) {
JSONArray langs = personal.optJSONArray("langs");
if (langs != null) {
this.langs = new String[langs.length()];
for (int i = 0; i < langs.length(); i++) {
this.langs[i] = langs.optString(i);
}
}
}
}
// contacts
facebook = user.optString("facebook");
facebook_name = user.optString("facebook_name");
livejournal = user.optString("livejournal");
site = user.optString(SITE);
screen_name = user.optString("screen_name", "id" + id);
skype = user.optString("skype");
mobile_phone = user.optString("mobile_phone");
home_phone = user.optString("home_phone");
twitter = user.optString("twitter");
instagram = user.optString("instagram");
// personal info
about = user.optString(ABOUT);
activities = user.optString(ACTIVITIES);
books = user.optString(BOOKS);
games = user.optString(GAMES);
interests = user.optString(INTERESTS);
movies = user.optString(MOVIES);
quotes = user.optString(QUOTES);
tv = user.optString(TV);
// settings
nickname = user.optString("nickname", null);
can_post = parseBoolean(user, CAN_POST);
can_see_all_posts = parseBoolean(user, CAN_SEE_ALL_POSTS);
blacklisted_by_me = parseBoolean(user, BLACKLISTED_BY_ME);
can_write_private_message = parseBoolean(user, CAN_WRITE_PRIVATE_MESSAGE);
wall_comments = parseBoolean(user, WALL_DEFAULT);
String deactivated = user.optString("deactivated");
is_deleted = "deleted".equals(deactivated);
is_banned = "banned".equals(deactivated);
wall_default_owner = "owner".equals(user.optString(WALL_DEFAULT));
verified = parseBoolean(user, VERIFIED);
// other
sex = user.optInt(SEX);
JSONObject counters = user.optJSONObject(COUNTERS);
if (counters != null) this.counters = new Counters(counters);
JSONObject occupation = user.optJSONObject(OCCUPATION);
if (occupation != null) this.occupation = new Occupation(occupation);
relation = user.optInt(RELATION);
if (user.has(RELATIVES)) {
if (relatives == null) {
relatives = new VKList<Relative>();
}
relatives.fill(user.optJSONArray(RELATIVES), Relative.class);
}
return this;
}
public static class Relative extends VKApiModel implements android.os.Parcelable, Identifiable {
public int id;
public String name;
@Override
public int getId() {
return id;
}
@Override
public Relative parse(JSONObject response) {
id = response.optInt("id");
name = response.optString("name");
return this;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.name);
}
private Relative(Parcel in) {
this.id = in.readInt();
this.name = in.readString();
}
public static Creator<Relative> CREATOR = new Creator<Relative>() {
public Relative createFromParcel(Parcel source) {
return new Relative(source);
}
public Relative[] newArray(int size) {
return new Relative[size];
}
};
}
public static class Counters implements android.os.Parcelable {
/**
* Count was not in server response.
*/
public final static int NO_COUNTER = -1;
public int albums = NO_COUNTER;
public int videos = NO_COUNTER;
public int audios = NO_COUNTER;
public int notes = NO_COUNTER;
public int friends = NO_COUNTER;
public int photos = NO_COUNTER;
public int groups = NO_COUNTER;
public int online_friends = NO_COUNTER;
public int mutual_friends = NO_COUNTER;
public int user_videos = NO_COUNTER;
public int followers = NO_COUNTER;
public int subscriptions = NO_COUNTER;
public int pages = NO_COUNTER;
Counters(JSONObject counters) {
albums = counters.optInt("albums", albums);
audios = counters.optInt("audios", audios);
followers = counters.optInt("followers", followers);
photos = counters.optInt("photos", photos);
friends = counters.optInt("friends", friends);
groups = counters.optInt("groups", groups);
mutual_friends = counters.optInt("mutual_friends", mutual_friends);
notes = counters.optInt("notes", notes);
online_friends = counters.optInt("online_friends", online_friends);
user_videos = counters.optInt("user_videos", user_videos);
videos = counters.optInt("videos", videos);
subscriptions = counters.optInt("subscriptions", subscriptions);
pages = counters.optInt("pages", pages);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.albums);
dest.writeInt(this.videos);
dest.writeInt(this.audios);
dest.writeInt(this.notes);
dest.writeInt(this.friends);
dest.writeInt(this.photos);
dest.writeInt(this.groups);
dest.writeInt(this.online_friends);
dest.writeInt(this.mutual_friends);
dest.writeInt(this.user_videos);
dest.writeInt(this.followers);
dest.writeInt(this.subscriptions);
dest.writeInt(this.pages);
}
private Counters(Parcel in) {
this.albums = in.readInt();
this.videos = in.readInt();
this.audios = in.readInt();
this.notes = in.readInt();
this.friends = in.readInt();
this.photos = in.readInt();
this.groups = in.readInt();
this.online_friends = in.readInt();
this.mutual_friends = in.readInt();
this.user_videos = in.readInt();
this.followers = in.readInt();
this.subscriptions = in.readInt();
this.pages = in.readInt();
}
public static Creator<Counters> CREATOR = new Creator<Counters>() {
public Counters createFromParcel(Parcel source) {
return new Counters(source);
}
public Counters[] newArray(int size) {
return new Counters[size];
}
};
}
public static class Occupation implements android.os.Parcelable {
/**
* Count was not in server response.
*/
public final static int NO_COUNTER = -1;
public String type;
public int id = NO_COUNTER;
public String name;
Occupation(JSONObject occupation) {
type = occupation.optString("type");
id = occupation.optInt("id",id);
name = occupation.optString("name");
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.type);
dest.writeInt(this.id);
dest.writeString(this.name);
}
private Occupation (Parcel in) {
this.type = in.readString();
this.id = in.readInt();
this.name = in.readString();
}
public static Creator<Occupation> CREATOR = new Creator<Occupation>() {
public Occupation createFromParcel(Parcel source) {
return new Occupation(source);
}
public Occupation[] newArray(int size) {
return new Occupation[size];
}
};
}
public static class Sex {
private Sex() {
}
public static final int FEMALE = 1;
public static final int MALE = 2;
}
public static class Relation {
private Relation() {
}
public static final int SINGLE = 1;
public static final int RELATIONSHIP = 2;
public static final int ENGAGED = 3;
public static final int MARRIED = 4;
public static final int COMPLICATED = 5;
public static final int SEARCHING = 6;
public static final int IN_LOVE = 7;
}
public static class Attitude {
private Attitude() {
}
public static final int VERY_NEGATIVE = 1;
public static final int NEGATIVE = 2;
public static final int COMPROMISABLE = 3;
public static final int NEUTRAL = 4;
public static final int POSITIVE = 5;
}
public static class Political {
private Political() {
}
public static final int COMMUNNIST = 1;
public static final int SOCIALIST = 2;
public static final int CENTRIST = 3;
public static final int LIBERAL = 4;
public static final int CONSERVATIVE = 5;
public static final int MONARCHIST = 6;
public static final int ULTRACONSERVATIVE = 7;
public static final int LIBERTARIAN = 8;
public static final int APATHETIC = 9;
}
public static class LifeMain {
private LifeMain() {
}
public static final int FAMILY_AND_CHILDREN = 1;
public static final int CAREER_AND_MONEY = 2;
public static final int ENTERTAINMENT_AND_LEISURE = 3;
public static final int SCIENCE_AND_RESEARCH = 4;
public static final int IMPROOVING_THE_WORLD = 5;
public static final int PERSONAL_DEVELOPMENT = 6;
public static final int BEAUTY_AND_ART = 7;
public static final int FAME_AND_INFLUENCE = 8;
}
public static class PeopleMain {
private PeopleMain() {
}
public static final int INTELLECT_AND_CREATIVITY = 1;
public static final int KINDNESS_AND_HONESTLY = 2;
public static final int HEALTH_AND_BEAUTY = 3;
public static final int WEALTH_AND_POWER = 4;
public static final int COURAGE_AND_PERSISTENCE = 5;
public static final int HUMOR_AND_LOVE_FOR_LIFE = 6;
}
public static class RelativeType {
private RelativeType() {
}
public static final String PARTNER = "partner";
public static final String GRANDCHILD = "grandchild";
public static final String GRANDPARENT = "grandparent";
public static final String CHILD = "child";
public static final String SUBLING = "sibling";
public static final String PARENT = "parent";
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(this.activity);
dest.writeParcelable(this.status_audio, flags);
dest.writeString(this.bdate);
dest.writeParcelable(this.city, flags);
dest.writeParcelable(this.country, flags);
dest.writeLong(this.last_seen);
dest.writeParcelable(this.universities, flags);
dest.writeParcelable(this.schools, flags);
dest.writeInt(this.smoking);
dest.writeInt(this.alcohol);
dest.writeInt(this.political);
dest.writeInt(this.life_main);
dest.writeInt(this.people_main);
dest.writeString(this.inspired_by);
dest.writeStringArray(this.langs);
dest.writeString(this.religion);
dest.writeString(this.facebook);
dest.writeString(this.facebook_name);
dest.writeString(this.livejournal);
dest.writeString(this.skype);
dest.writeString(this.site);
dest.writeString(this.twitter);
dest.writeString(this.instagram);
dest.writeString(this.mobile_phone);
dest.writeString(this.home_phone);
dest.writeString(this.screen_name);
dest.writeString(this.activities);
dest.writeString(this.interests);
dest.writeString(this.movies);
dest.writeString(this.tv);
dest.writeString(this.books);
dest.writeString(this.games);
dest.writeString(this.about);
dest.writeString(this.quotes);
dest.writeByte(can_post ? (byte) 1 : (byte) 0);
dest.writeByte(can_see_all_posts ? (byte) 1 : (byte) 0);
dest.writeByte(can_write_private_message ? (byte) 1 : (byte) 0);
dest.writeByte(wall_comments ? (byte) 1 : (byte) 0);
dest.writeByte(is_banned ? (byte) 1 : (byte) 0);
dest.writeByte(is_deleted ? (byte) 1 : (byte) 0);
dest.writeByte(wall_default_owner ? (byte) 1 : (byte) 0);
dest.writeByte(verified ? (byte) 1 : (byte) 0);
dest.writeInt(this.sex);
dest.writeParcelable(this.counters, flags);
dest.writeParcelable(this.occupation, flags);
dest.writeInt(this.relation);
dest.writeParcelable(this.relatives, flags);
dest.writeByte(blacklisted_by_me ? (byte) 1 : (byte) 0);
}
public VKApiUserFull() {}
public VKApiUserFull(Parcel in) {
super(in);
this.activity = in.readString();
this.status_audio = in.readParcelable(VKApiAudio.class.getClassLoader());
this.bdate = in.readString();
this.city = in.readParcelable(VKApiCity.class.getClassLoader());
this.country = in.readParcelable(VKApiCountry.class.getClassLoader());
this.last_seen = in.readLong();
this.universities = in.readParcelable(VKList.class.getClassLoader());
this.schools = in.readParcelable(VKList.class.getClassLoader());
this.smoking = in.readInt();
this.alcohol = in.readInt();
this.political = in.readInt();
this.life_main = in.readInt();
this.people_main = in.readInt();
this.inspired_by = in.readString();
this.langs = in.createStringArray();
this.religion = in.readString();
this.facebook = in.readString();
this.facebook_name = in.readString();
this.livejournal = in.readString();
this.skype = in.readString();
this.site = in.readString();
this.twitter = in.readString();
this.instagram = in.readString();
this.mobile_phone = in.readString();
this.home_phone = in.readString();
this.screen_name = in.readString();
this.activities = in.readString();
this.interests = in.readString();
this.movies = in.readString();
this.tv = in.readString();
this.books = in.readString();
this.games = in.readString();
this.about = in.readString();
this.quotes = in.readString();
this.can_post = in.readByte() != 0;
this.can_see_all_posts = in.readByte() != 0;
this.can_write_private_message = in.readByte() != 0;
this.wall_comments = in.readByte() != 0;
this.is_banned = in.readByte() != 0;
this.is_deleted = in.readByte() != 0;
this.wall_default_owner = in.readByte() != 0;
this.verified = in.readByte() != 0;
this.sex = in.readInt();
this.counters = in.readParcelable(Counters.class.getClassLoader());
this.occupation = in.readParcelable(Occupation.class.getClassLoader());
this.relation = in.readInt();
this.relatives = in.readParcelable(VKList.class.getClassLoader());
this.blacklisted_by_me = in.readByte() != 0;
}
public static Creator<VKApiUserFull> CREATOR = new Creator<VKApiUserFull>() {
public VKApiUserFull createFromParcel(Parcel source) {
return new VKApiUserFull(source);
}
public VKApiUserFull[] newArray(int size) {
return new VKApiUserFull[size];
}
};
}
| vksdk_library/src/main/java/com/vk/sdk/api/model/VKApiUserFull.java | //
// Copyright (c) 2014 VK.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.
//
package com.vk.sdk.api.model;
import android.os.Parcel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static com.vk.sdk.api.model.ParseUtils.parseBoolean;
import static com.vk.sdk.api.model.ParseUtils.parseLong;
/**
* Represents full user profile.
*/
@SuppressWarnings("unused")
public class VKApiUserFull extends VKApiUser implements android.os.Parcelable {
/**
* Filed last_seen from VK fields set
*/
public static final String LAST_SEEN = "last_seen";
/**
* Filed bdate from VK fields set
*/
public static final String BDATE = "bdate";
/**
* Filed city from VK fields set
*/
public static final String CITY = "city";
/**
* Filed country from VK fields set
*/
public static final String COUNTRY = "country";
/**
* Filed universities from VK fields set
*/
public static final String UNIVERSITIES = "universities";
/**
* Filed schools from VK fields set
*/
public static final String SCHOOLS = "schools";
/**
* Filed activity from VK fields set
*/
public static final String ACTIVITY = "activity";
/**
* Filed personal from VK fields set
*/
public static final String PERSONAL = "personal";
/**
* Filed sex from VK fields set
*/
public static final String SEX = "sex";
/**
* Filed site from VK fields set
*/
public static final String SITE = "site";
/**
* Filed contacts from VK fields set
*/
public static final String CONTACTS = "contacts";
/**
* Filed can_post from VK fields set
*/
public static final String CAN_POST = "can_post";
/**
* Filed can_see_all_posts from VK fields set
*/
public static final String CAN_SEE_ALL_POSTS = "can_see_all_posts";
/**
* Filed can_write_private_message from VK fields set
*/
public static final String CAN_WRITE_PRIVATE_MESSAGE = "can_write_private_message";
/**
* Filed relation from VK fields set
*/
public static final String RELATION = "relation";
/**
* Filed counters from VK fields set
*/
public static final String COUNTERS = "counters";
/**
* Filed activities from VK fields set
*/
public static final String ACTIVITIES = "activities";
/**
* Filed interests from VK fields set
*/
public static final String INTERESTS = "interests";
/**
* Filed movies from VK fields set
*/
public static final String MOVIES = "movies";
/**
* Filed tv from VK fields set
*/
public static final String TV = "tv";
/**
* Filed books from VK fields set
*/
public static final String BOOKS = "books";
/**
* Filed games from VK fields set
*/
public static final String GAMES = "games";
/**
* Filed about from VK fields set
*/
public static final String ABOUT = "about";
/**
* Filed quotes from VK fields set
*/
public static final String QUOTES = "quotes";
/**
* Filed connections from VK fields set
*/
public static final String CONNECTIONS = "connections";
/**
* Filed relatives from VK fields set
*/
public static final String RELATIVES = "relatives";
/**
* Filed wall_default from VK fields set
*/
public static final String WALL_DEFAULT = "wall_default";
/**
* Filed verified from VK fields set
*/
public static final String VERIFIED = "verified";
/**
* Filed screen_name from VK fields set
*/
public static final String SCREEN_NAME = "screen_name";
/**
* Filed blacklisted_by_me from VK fields set
*/
public static final String BLACKLISTED_BY_ME = "blacklisted_by_me";
/**
* Text of user status.
*/
public String activity;
/**
* Audio which broadcasting to status.
*/
public VKApiAudio status_audio;
/**
* User's date of birth. Returned as DD.MM.YYYY or DD.MM (if birth year is hidden).
*/
public String bdate;
/**
* City specified on user's page in "Contacts" section.
*/
public VKApiCity city;
/**
* Country specified on user's page in "Contacts" section.
*/
public VKApiCountry country;
/**
* Last visit date(in Unix time).
*/
public long last_seen;
/**
* List of user's universities
*/
public VKList<VKApiUniversity> universities;
/**
* List of user's schools
*/
public VKList<VKApiSchool> schools;
/**
* Views on smoking.
* @see com.vk.sdk.api.model.VKApiUserFull.Attitude
*/
public int smoking;
/**
* Views on alcohol.
* @see com.vk.sdk.api.model.VKApiUserFull.Attitude
*/
public int alcohol;
/**
* Views on policy.
* @see com.vk.sdk.api.model.VKApiUserFull.Political
*/
public int political;
/**
* Life main stuffs.
* @see com.vk.sdk.api.model.VKApiUserFull.LifeMain
*/
public int life_main;
/**
* People main stuffs.
* @see com.vk.sdk.api.model.VKApiUserFull.PeopleMain
*/
public int people_main;
/**
* Stuffs that inspire the user.
*/
public String inspired_by;
/**
* List of user's languages
*/
public String[] langs;
/**
* Religion of user
*/
public String religion;
/**
* Name of user's account in Facebook
*/
public String facebook;
/**
* ID of user's facebook
*/
public String facebook_name;
/**
* Name of user's account in LiveJournal
*/
public String livejournal;
/**
* Name of user's account in Skype
*/
public String skype;
/**
* URL of user's site
*/
public String site;
/**
* Name of user's account in Twitter
*/
public String twitter;
/**
* Name of user's account in Instagram
*/
public String instagram;
/**
* User's mobile phone number
*/
public String mobile_phone;
/**
* User's home phone number
*/
public String home_phone;
/**
* Page screen name.
*/
public String screen_name;
/**
* Nickname of user.
*/
public String nickname;
/**
* User's activities
*/
public String activities;
/**
* User's interests
*/
public String interests;
/**
* User's favorite movies
*/
public String movies;
/**
* User's favorite TV Shows
*/
public String tv;
/**
* User's favorite books
*/
public String books;
/**
* User's favorite games
*/
public String games;
/**
* User's about information
*/
public String about;
/**
* User's favorite quotes
*/
public String quotes;
/**
* Information whether others can posts on user's wall.
*/
public boolean can_post;
/**
* Information whether others' posts on user's wall can be viewed
*/
public boolean can_see_all_posts;
/**
* Information whether private messages can be sent to this user.
*/
public boolean can_write_private_message;
/**
* Information whether user can comment wall posts.
*/
public boolean wall_comments;
/**
* Information whether the user is banned in VK.
*/
public boolean is_banned;
/**
* Information whether the user is deleted in VK.
*/
public boolean is_deleted;
/**
* Information whether the user's post of wall shows by default.
*/
public boolean wall_default_owner;
/**
* Information whether the user has a verified page in VK
*/
public boolean verified;
/**
* User sex.
* @see com.vk.sdk.api.model.VKApiUserFull.Sex
*/
public int sex;
/**
* Set of user's counters.
*/
public Counters counters;
/**
* Relationship status.
* @see com.vk.sdk.api.model.VKApiUserFull.Relation
*/
public int relation;
/**
* List of user's relatives
*/
public VKList<Relative> relatives;
/**
* Information whether the current user has add this user to the blacklist.
*/
public boolean blacklisted_by_me;
public VKApiUserFull(JSONObject from) throws JSONException
{
parse(from);
}
public VKApiUserFull parse(JSONObject user) {
super.parse(user);
// general
last_seen = parseLong(user.optJSONObject(LAST_SEEN), "time");
bdate = user.optString(BDATE);
JSONObject city = user.optJSONObject(CITY);
if(city != null) {
this.city = new VKApiCity().parse(city);
}
JSONObject country = user.optJSONObject(COUNTRY);
if(country != null) {
this.country = new VKApiCountry().parse(country);
}
// education
universities = new VKList<VKApiUniversity>(user.optJSONArray(UNIVERSITIES), VKApiUniversity.class);
schools = new VKList<VKApiSchool>(user.optJSONArray(SCHOOLS), VKApiSchool.class);
// status
activity = user.optString(ACTIVITY);
JSONObject status_audio = user.optJSONObject("status_audio");
if(status_audio != null) this.status_audio = new VKApiAudio().parse(status_audio);
// personal views
JSONObject personal = user.optJSONObject(PERSONAL);
if (personal != null) {
smoking = personal.optInt("smoking");
alcohol = personal.optInt("alcohol");
political = personal.optInt("political");
life_main = personal.optInt("life_main");
people_main = personal.optInt("people_main");
inspired_by = personal.optString("inspired_by");
religion = personal.optString("religion");
if (personal.has("langs")) {
JSONArray langs = personal.optJSONArray("langs");
if (langs != null) {
this.langs = new String[langs.length()];
for (int i = 0; i < langs.length(); i++) {
this.langs[i] = langs.optString(i);
}
}
}
}
// contacts
facebook = user.optString("facebook");
facebook_name = user.optString("facebook_name");
livejournal = user.optString("livejournal");
site = user.optString(SITE);
screen_name = user.optString("screen_name", "id" + id);
skype = user.optString("skype");
mobile_phone = user.optString("mobile_phone");
home_phone = user.optString("home_phone");
twitter = user.optString("twitter");
instagram = user.optString("instagram");
// personal info
about = user.optString(ABOUT);
activities = user.optString(ACTIVITIES);
books = user.optString(BOOKS);
games = user.optString(GAMES);
interests = user.optString(INTERESTS);
movies = user.optString(MOVIES);
quotes = user.optString(QUOTES);
tv = user.optString(TV);
// settings
nickname = user.optString("nickname", null);
can_post = parseBoolean(user, CAN_POST);
can_see_all_posts = parseBoolean(user, CAN_SEE_ALL_POSTS);
blacklisted_by_me = parseBoolean(user, BLACKLISTED_BY_ME);
can_write_private_message = parseBoolean(user, CAN_WRITE_PRIVATE_MESSAGE);
wall_comments = parseBoolean(user, WALL_DEFAULT);
String deactivated = user.optString("deactivated");
is_deleted = "deleted".equals(deactivated);
is_banned = "banned".equals(deactivated);
wall_default_owner = "owner".equals(user.optString(WALL_DEFAULT));
verified = parseBoolean(user, VERIFIED);
// other
sex = user.optInt(SEX);
JSONObject counters = user.optJSONObject(COUNTERS);
if (counters != null) this.counters = new Counters(counters);
relation = user.optInt(RELATION);
if (user.has(RELATIVES)) {
if (relatives == null) {
relatives = new VKList<Relative>();
}
relatives.fill(user.optJSONArray(RELATIVES), Relative.class);
}
return this;
}
public static class Relative extends VKApiModel implements android.os.Parcelable, Identifiable {
public int id;
public String name;
@Override
public int getId() {
return id;
}
@Override
public Relative parse(JSONObject response) {
id = response.optInt("id");
name = response.optString("name");
return this;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.name);
}
private Relative(Parcel in) {
this.id = in.readInt();
this.name = in.readString();
}
public static Creator<Relative> CREATOR = new Creator<Relative>() {
public Relative createFromParcel(Parcel source) {
return new Relative(source);
}
public Relative[] newArray(int size) {
return new Relative[size];
}
};
}
public static class Counters implements android.os.Parcelable {
/**
* Count was not in server response.
*/
public final static int NO_COUNTER = -1;
public int albums = NO_COUNTER;
public int videos = NO_COUNTER;
public int audios = NO_COUNTER;
public int notes = NO_COUNTER;
public int friends = NO_COUNTER;
public int photos = NO_COUNTER;
public int groups = NO_COUNTER;
public int online_friends = NO_COUNTER;
public int mutual_friends = NO_COUNTER;
public int user_videos = NO_COUNTER;
public int followers = NO_COUNTER;
public int subscriptions = NO_COUNTER;
public int pages = NO_COUNTER;
Counters(JSONObject counters) {
albums = counters.optInt("albums", albums);
audios = counters.optInt("audios", audios);
followers = counters.optInt("followers", followers);
photos = counters.optInt("photos", photos);
friends = counters.optInt("friends", friends);
groups = counters.optInt("groups", groups);
mutual_friends = counters.optInt("mutual_friends", mutual_friends);
notes = counters.optInt("notes", notes);
online_friends = counters.optInt("online_friends", online_friends);
user_videos = counters.optInt("user_videos", user_videos);
videos = counters.optInt("videos", videos);
subscriptions = counters.optInt("subscriptions", subscriptions);
pages = counters.optInt("pages", pages);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.albums);
dest.writeInt(this.videos);
dest.writeInt(this.audios);
dest.writeInt(this.notes);
dest.writeInt(this.friends);
dest.writeInt(this.photos);
dest.writeInt(this.groups);
dest.writeInt(this.online_friends);
dest.writeInt(this.mutual_friends);
dest.writeInt(this.user_videos);
dest.writeInt(this.followers);
dest.writeInt(this.subscriptions);
dest.writeInt(this.pages);
}
private Counters(Parcel in) {
this.albums = in.readInt();
this.videos = in.readInt();
this.audios = in.readInt();
this.notes = in.readInt();
this.friends = in.readInt();
this.photos = in.readInt();
this.groups = in.readInt();
this.online_friends = in.readInt();
this.mutual_friends = in.readInt();
this.user_videos = in.readInt();
this.followers = in.readInt();
this.subscriptions = in.readInt();
this.pages = in.readInt();
}
public static Creator<Counters> CREATOR = new Creator<Counters>() {
public Counters createFromParcel(Parcel source) {
return new Counters(source);
}
public Counters[] newArray(int size) {
return new Counters[size];
}
};
}
public static class Sex {
private Sex() {
}
public static final int FEMALE = 1;
public static final int MALE = 2;
}
public static class Relation {
private Relation() {
}
public static final int SINGLE = 1;
public static final int RELATIONSHIP = 2;
public static final int ENGAGED = 3;
public static final int MARRIED = 4;
public static final int COMPLICATED = 5;
public static final int SEARCHING = 6;
public static final int IN_LOVE = 7;
}
public static class Attitude {
private Attitude() {
}
public static final int VERY_NEGATIVE = 1;
public static final int NEGATIVE = 2;
public static final int COMPROMISABLE = 3;
public static final int NEUTRAL = 4;
public static final int POSITIVE = 5;
}
public static class Political {
private Political() {
}
public static final int COMMUNNIST = 1;
public static final int SOCIALIST = 2;
public static final int CENTRIST = 3;
public static final int LIBERAL = 4;
public static final int CONSERVATIVE = 5;
public static final int MONARCHIST = 6;
public static final int ULTRACONSERVATIVE = 7;
public static final int LIBERTARIAN = 8;
public static final int APATHETIC = 9;
}
public static class LifeMain {
private LifeMain() {
}
public static final int FAMILY_AND_CHILDREN = 1;
public static final int CAREER_AND_MONEY = 2;
public static final int ENTERTAINMENT_AND_LEISURE = 3;
public static final int SCIENCE_AND_RESEARCH = 4;
public static final int IMPROOVING_THE_WORLD = 5;
public static final int PERSONAL_DEVELOPMENT = 6;
public static final int BEAUTY_AND_ART = 7;
public static final int FAME_AND_INFLUENCE = 8;
}
public static class PeopleMain {
private PeopleMain() {
}
public static final int INTELLECT_AND_CREATIVITY = 1;
public static final int KINDNESS_AND_HONESTLY = 2;
public static final int HEALTH_AND_BEAUTY = 3;
public static final int WEALTH_AND_POWER = 4;
public static final int COURAGE_AND_PERSISTENCE = 5;
public static final int HUMOR_AND_LOVE_FOR_LIFE = 6;
}
public static class RelativeType {
private RelativeType() {
}
public static final String PARTNER = "partner";
public static final String GRANDCHILD = "grandchild";
public static final String GRANDPARENT = "grandparent";
public static final String CHILD = "child";
public static final String SUBLING = "sibling";
public static final String PARENT = "parent";
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(this.activity);
dest.writeParcelable(this.status_audio, flags);
dest.writeString(this.bdate);
dest.writeParcelable(this.city, flags);
dest.writeParcelable(this.country, flags);
dest.writeLong(this.last_seen);
dest.writeParcelable(this.universities, flags);
dest.writeParcelable(this.schools, flags);
dest.writeInt(this.smoking);
dest.writeInt(this.alcohol);
dest.writeInt(this.political);
dest.writeInt(this.life_main);
dest.writeInt(this.people_main);
dest.writeString(this.inspired_by);
dest.writeStringArray(this.langs);
dest.writeString(this.religion);
dest.writeString(this.facebook);
dest.writeString(this.facebook_name);
dest.writeString(this.livejournal);
dest.writeString(this.skype);
dest.writeString(this.site);
dest.writeString(this.twitter);
dest.writeString(this.instagram);
dest.writeString(this.mobile_phone);
dest.writeString(this.home_phone);
dest.writeString(this.screen_name);
dest.writeString(this.activities);
dest.writeString(this.interests);
dest.writeString(this.movies);
dest.writeString(this.tv);
dest.writeString(this.books);
dest.writeString(this.games);
dest.writeString(this.about);
dest.writeString(this.quotes);
dest.writeByte(can_post ? (byte) 1 : (byte) 0);
dest.writeByte(can_see_all_posts ? (byte) 1 : (byte) 0);
dest.writeByte(can_write_private_message ? (byte) 1 : (byte) 0);
dest.writeByte(wall_comments ? (byte) 1 : (byte) 0);
dest.writeByte(is_banned ? (byte) 1 : (byte) 0);
dest.writeByte(is_deleted ? (byte) 1 : (byte) 0);
dest.writeByte(wall_default_owner ? (byte) 1 : (byte) 0);
dest.writeByte(verified ? (byte) 1 : (byte) 0);
dest.writeInt(this.sex);
dest.writeParcelable(this.counters, flags);
dest.writeInt(this.relation);
dest.writeParcelable(this.relatives, flags);
dest.writeByte(blacklisted_by_me ? (byte) 1 : (byte) 0);
}
public VKApiUserFull() {}
public VKApiUserFull(Parcel in) {
super(in);
this.activity = in.readString();
this.status_audio = in.readParcelable(VKApiAudio.class.getClassLoader());
this.bdate = in.readString();
this.city = in.readParcelable(VKApiCity.class.getClassLoader());
this.country = in.readParcelable(VKApiCountry.class.getClassLoader());
this.last_seen = in.readLong();
this.universities = in.readParcelable(VKList.class.getClassLoader());
this.schools = in.readParcelable(VKList.class.getClassLoader());
this.smoking = in.readInt();
this.alcohol = in.readInt();
this.political = in.readInt();
this.life_main = in.readInt();
this.people_main = in.readInt();
this.inspired_by = in.readString();
this.langs = in.createStringArray();
this.religion = in.readString();
this.facebook = in.readString();
this.facebook_name = in.readString();
this.livejournal = in.readString();
this.skype = in.readString();
this.site = in.readString();
this.twitter = in.readString();
this.instagram = in.readString();
this.mobile_phone = in.readString();
this.home_phone = in.readString();
this.screen_name = in.readString();
this.activities = in.readString();
this.interests = in.readString();
this.movies = in.readString();
this.tv = in.readString();
this.books = in.readString();
this.games = in.readString();
this.about = in.readString();
this.quotes = in.readString();
this.can_post = in.readByte() != 0;
this.can_see_all_posts = in.readByte() != 0;
this.can_write_private_message = in.readByte() != 0;
this.wall_comments = in.readByte() != 0;
this.is_banned = in.readByte() != 0;
this.is_deleted = in.readByte() != 0;
this.wall_default_owner = in.readByte() != 0;
this.verified = in.readByte() != 0;
this.sex = in.readInt();
this.counters = in.readParcelable(Counters.class.getClassLoader());
this.relation = in.readInt();
this.relatives = in.readParcelable(VKList.class.getClassLoader());
this.blacklisted_by_me = in.readByte() != 0;
}
public static Creator<VKApiUserFull> CREATOR = new Creator<VKApiUserFull>() {
public VKApiUserFull createFromParcel(Parcel source) {
return new VKApiUserFull(source);
}
public VKApiUserFull[] newArray(int size) {
return new VKApiUserFull[size];
}
};
}
| Добавлена сущность occupation
| vksdk_library/src/main/java/com/vk/sdk/api/model/VKApiUserFull.java | Добавлена сущность occupation | <ide><path>ksdk_library/src/main/java/com/vk/sdk/api/model/VKApiUserFull.java
<ide> public static final String COUNTERS = "counters";
<ide>
<ide> /**
<add> * Filed occupation from VK fields set
<add> */
<add> public static final String OCCUPATION = "occupation";
<add>
<add> /**
<ide> * Filed activities from VK fields set
<ide> */
<ide> public static final String ACTIVITIES = "activities";
<ide> * Set of user's counters.
<ide> */
<ide> public Counters counters;
<add>
<add> /**
<add> * Set of user's counters.
<add> */
<add> public Occupation occupation;
<ide>
<ide> /**
<ide> * Relationship status.
<ide>
<ide> // other
<ide> sex = user.optInt(SEX);
<add>
<ide> JSONObject counters = user.optJSONObject(COUNTERS);
<ide> if (counters != null) this.counters = new Counters(counters);
<add>
<add> JSONObject occupation = user.optJSONObject(OCCUPATION);
<add> if (occupation != null) this.occupation = new Occupation(occupation);
<ide>
<ide> relation = user.optInt(RELATION);
<ide>
<ide>
<ide> public Counters[] newArray(int size) {
<ide> return new Counters[size];
<add> }
<add> };
<add> }
<add>
<add> public static class Occupation implements android.os.Parcelable {
<add> /**
<add> * Count was not in server response.
<add> */
<add> public final static int NO_COUNTER = -1;
<add>
<add> public String type;
<add> public int id = NO_COUNTER;
<add> public String name;
<add>
<add> Occupation(JSONObject occupation) {
<add> type = occupation.optString("type");
<add> id = occupation.optInt("id",id);
<add> name = occupation.optString("name");
<add> }
<add>
<add> @Override
<add> public int describeContents() {
<add> return 0;
<add> }
<add>
<add> @Override
<add> public void writeToParcel(Parcel dest, int flags) {
<add> dest.writeString(this.type);
<add> dest.writeInt(this.id);
<add> dest.writeString(this.name);
<add> }
<add>
<add> private Occupation (Parcel in) {
<add> this.type = in.readString();
<add> this.id = in.readInt();
<add> this.name = in.readString();
<add> }
<add>
<add> public static Creator<Occupation> CREATOR = new Creator<Occupation>() {
<add> public Occupation createFromParcel(Parcel source) {
<add> return new Occupation(source);
<add> }
<add>
<add> public Occupation[] newArray(int size) {
<add> return new Occupation[size];
<ide> }
<ide> };
<ide> }
<ide> dest.writeByte(verified ? (byte) 1 : (byte) 0);
<ide> dest.writeInt(this.sex);
<ide> dest.writeParcelable(this.counters, flags);
<add> dest.writeParcelable(this.occupation, flags);
<ide> dest.writeInt(this.relation);
<ide> dest.writeParcelable(this.relatives, flags);
<ide> dest.writeByte(blacklisted_by_me ? (byte) 1 : (byte) 0);
<ide> this.verified = in.readByte() != 0;
<ide> this.sex = in.readInt();
<ide> this.counters = in.readParcelable(Counters.class.getClassLoader());
<add> this.occupation = in.readParcelable(Occupation.class.getClassLoader());
<ide> this.relation = in.readInt();
<ide> this.relatives = in.readParcelable(VKList.class.getClassLoader());
<ide> this.blacklisted_by_me = in.readByte() != 0; |
|
JavaScript | mit | d16b975d7e0b91f34f9e6b9b0e43bca513ce3f8d | 0 | bgrainger/leeroy-pull-request-builder,ddunkin/leeroy-pull-request-builder | #!/usr/bin/env node
'use strict';
var bodyParser = require('body-parser');
var bunyan = require('bunyan');
var express = require('express');
var octokat = require('octokat');
var superagent = require('superagent-promise')(require('superagent'), Promise);
// ignore errors for git's SSL certificate
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
var log = bunyan.createLogger({ name: 'app' });
var app = express();
app.use(bodyParser.json());
var github = new octokat({
token: process.env.GITHUB_TOKEN,
rootURL: 'https://git/api/v3'
})
log.info('Starting');
app.get('/', function (req, res) {
res.send('leeroy-pull-request-builder');
});
app.post('/event_handler', function (req, res) {
var gitHubEvent = req.headers['x-github-event'];
log.info('Received GitHub event: ' + gitHubEvent);
if (gitHubEvent === 'ping') {
res.status(204).send();
} else if (gitHubEvent === 'pull_request') {
if (req.body.action === 'opened' || req.body.action === 'reopened' || req.body.action === 'synchronize') {
var pr = req.body.pull_request;
processPullRequest(pr)
.then(null, function (e) {
log.error(e);
setStatus(pr.base.repo.owner.login, pr.base.repo.name, pr.head.sha, 'error', 'Error creating CI build');
});
res.status(204).send();
}
} else {
res.status(400).send();
}
});
app.post('/jenkins', function (req, res) {
log.info('Received Jenkins notification.');
if (req.body && req.body.build) {
var pr = activeBuilds[req.body.build.parameters.sha1];
if (pr) {
switch (req.body.build.phase) {
case 'STARTED':
setStatus(pr.baseUser, pr.baseRepo, pr.sha, 'pending', 'Building with Jenkins', req.body.build.full_url);
superagent.post(req.body.build.full_url + '/submitDescription')
.type('form')
.send({
description: pr.title,
Submit: 'Submit'
})
.end();
break;
case 'COMPLETED':
setStatus(pr.baseUser, pr.baseRepo, pr.sha,
req.body.build.status == 'SUCCESS' ? 'success' : 'failure',
'Jenkins build status: ' + req.body.build.status,
req.body.build.full_url);
break;
}
}
res.status(204).send();
} else {
res.status(400).send();
}
});
app.listen(3000);
/**
* When a pull_request event is received, creates a new commit in the Build repo that references the
* PR's commit (in a submodule) and starts a build.
*/
function processPullRequest(pullRequest) {
var pr = {
baseUser: pullRequest.base.repo.owner.login,
baseRepo: pullRequest.base.repo.name,
baseBranch: pullRequest.base.ref,
headUser: pullRequest.head.repo.owner.login,
headRepo: pullRequest.head.repo.name,
sha: pullRequest.head.sha,
title: 'PR #' + pullRequest.number + ': ' + pullRequest.title
};
return leeroyBranches.then(function (lb) {
var key = pr.baseUser + '/' + pr.baseRepo + '/' + pr.baseBranch;
log.info('Received pull_request event for ' + key + ': SHA = ' + pr.sha);
if (lb[key]) {
return setStatus(pr.baseUser, pr.baseRepo, pr.sha, 'pending', 'Preparing build')
.then(function () {
return Promise.all(lb[key].map(function (leeroyConfig) {
var buildUserRepo = leeroyConfig.repoUrl.match(buildRepoUrl);
var build = {
config: leeroyConfig,
repo: github.repos(buildUserRepo[1], buildUserRepo[2])
};
return getHeadCommit(pr, build)
.then(function (commit) {
return createNewCommit(pr, build, commit);
})
.then(function (newCommit) {
return createRef(pr, build, newCommit)
.then(function() {
activeBuilds[newCommit.sha] = pr;
return Promise.all(build.config.pullRequestBuildUrls.map(function (prBuildUrl) {
log.info('Starting a build at ' + prBuildUrl);
return superagent
.get(prBuildUrl)
.query({ sha1: newCommit.sha });
}));
});
});
}));
});
}
});
}
/**
* Calls the GitHub Status API to set the state for 'sha'.
* See https://developer.github.com/v3/repos/statuses/#create-a-status for parameter descriptions.
*/
function setStatus(user, repo, sha, state, description, targetUrl) {
return github.repos(user, repo).statuses(sha).create({
state: state,
description: description,
target_url: targetUrl,
context: 'leeroy-pull-request-builder'
});
}
/**
* Returns a promise for the SHA of the head of the build repo branch specified by
* the Leeroy config in 'build.config'.
*/
function getHeadCommit(pr, build) {
return build.repo.git.refs('heads', build.config.branch).fetch()
.then(function (ref) {
log.info('Repo ' + build.config.repoUrl + ' is at commit ' + ref.object.sha);
return build.repo.git.commits(ref.object.sha).fetch();
});
}
/**
* Returns a promise for a new build repo commit that updates the specified 'commit'
* with updated submodules for 'pr'.
*/
function createNewCommit(pr, build, commit) {
return build.repo.git.trees(commit.tree.sha).fetch()
.then(function(tree) {
return createNewTree(pr, build, tree);
})
.then(function (newTree) {
log.info('newTree = ' + newTree.sha);
return build.repo.git.commits.create({
message: pr.title,
tree: newTree.sha,
parents: [ commit.sha ]
});
});
}
/**
* Returns a promise for a new tree that updates .gitmodules and the submodules
* in 'tree' with the updated submodules for 'pr'.
*/
function createNewTree(pr, build, tree) {
// find the submodule that needs to be changed and update its SHA
var newItems = tree.tree.filter(function (treeItem) {
if (treeItem.mode === '160000' && treeItem.path == pr.baseRepo) {
treeItem.sha = pr.sha;
return true;
}
return false;
});
// find the .gitmodules file
var gitmodulesItem = tree.tree.filter(function (treeItem) {
return treeItem.path === '.gitmodules';
})[0];
// get the contents of .gitmodules
return build.repo.git.blobs(gitmodulesItem.sha).fetch()
.then(function (blob) {
// update .gitmodules with the repo URL the PR is coming from (because it has the commit we need)
var gitmodules = new Buffer(blob.content, 'base64').toString('utf-8')
.replace('git@git:' + pr.baseUser + '/' + pr.baseRepo + '.git', 'git@git:' + pr.headUser + '/' + pr.headRepo + '.git');
return build.repo.git.blobs.create({
content: gitmodules
});
})
.then(function (newBlob) {
// create a new tree with updated submodules and .gitmodules
gitmodulesItem.sha = newBlob.sha;
newItems.push(gitmodulesItem);
return build.repo.git.trees.create({
base_tree: tree.sha,
tree: newItems
});
})
}
/**
* Updates the 'lprb' (Leeroy Pull Request Builder) branch in 'build' to point at the specified commit SHA.
*/
function createRef(pr, build, newCommit) {
log.info('New commit is ' + newCommit.sha + '; updating ref.');
var refName = 'heads/lprb';
return build.repo.git.refs(refName).fetch()
.then(function () {
return build.repo.git.refs(refName).update({
sha: newCommit.sha,
force: true
});
}, function() {
return build.repo.git.refs.create({
ref: 'refs/' + refName,
sha: newCommit.sha
});
});
}
/**
* Gets all the repos+branches that have pullRequestBuildUrls set in their Leeroy configs.
*/
function getLeeroyBranches() {
return github.repos('Build', 'Configuration').contents.fetch()
.then(function (contents) {
log.info('Contents has ' + contents.length + ' files');
var jsonFiles = contents.filter(function (elem) {
return elem.path.indexOf('.json') === elem.path.length - 5;
});
return Promise.all(jsonFiles.map(function (elem) {
return github.repos('Build', 'Configuration').contents(elem.path).read()
.then(function (contents) {
try {
return JSON.parse(contents);
}
catch (e) {
return null;
}
});
}));
})
.then(function (files) {
var enabledFiles = files.filter(function (f) {
return f && !f.disabled && f.submodules && f.pullRequestBuildUrls && buildRepoUrl.test(f.repoUrl);
});
log.info('there are ' + enabledFiles.length + ' enabled files with submodules and PR build URLs.');
var repos = { };
enabledFiles.forEach(function (file) {
for (var submodule in file.submodules) {
var key = submodule + '/' + file.submodules[submodule];
repos[key] = repos[key] || [];
repos[key].push(file);
}
});
return repos;
})
.then(null, function(err) {
log.error(err);
});
}
var leeroyBranches = getLeeroyBranches();
var activeBuilds = {};
var buildRepoUrl = /^git@git:([^/]+)\/([^.]+).git$/;
| bin/server.js | #!/usr/bin/env node
'use strict';
var bodyParser = require('body-parser');
var bunyan = require('bunyan');
var express = require('express');
var octokat = require('octokat');
var superagent = require('superagent-promise')(require('superagent'), Promise);
// ignore errors for git's SSL certificate
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
var log = bunyan.createLogger({ name: 'app' });
var app = express();
app.use(bodyParser.json());
var github = new octokat({
token: process.env.GITHUB_TOKEN,
rootURL: 'https://git/api/v3'
})
log.info('Starting');
app.get('/', function (req, res) {
res.send('leeroy-pull-request-builder');
});
app.post('/event_handler', function (req, res) {
var gitHubEvent = req.headers['x-github-event'];
log.info('Received GitHub event: ' + gitHubEvent);
if (gitHubEvent === 'ping') {
res.status(204).send();
} else if (gitHubEvent === 'pull_request') {
if (req.body.action === 'opened' || req.body.action === 'reopened' || req.body.action === 'synchronize') {
var pr = req.body.pull_request;
processPullRequest(pr)
.then(null, function (e) {
log.error(e);
setStatus(pr.base.repo.owner.login, pr.base.repo.name, pr.head.sha, 'error', 'Error creating CI build');
});
res.status(204).send();
}
} else {
res.status(400).send();
}
});
app.post('/jenkins', function (req, res) {
log.info('Received Jenkins notification.');
if (req.body && req.body.build) {
var pr = activeBuilds[req.body.build.parameters.sha1];
if (pr) {
switch (req.body.build.phase) {
case 'STARTED':
setStatus(pr.baseUser, pr.baseRepo, pr.sha, 'pending', 'Building with Jenkins', req.body.build.full_url);
break;
case 'COMPLETED':
setStatus(pr.baseUser, pr.baseRepo, pr.sha,
req.body.build.status == 'SUCCESS' ? 'success' : 'failure',
'Jenkins build status: ' + req.body.build.status,
req.body.build.full_url);
break;
}
}
res.status(204).send();
} else {
res.status(400).send();
}
});
app.listen(3000);
/**
* When a pull_request event is received, creates a new commit in the Build repo that references the
* PR's commit (in a submodule) and starts a build.
*/
function processPullRequest(pullRequest) {
var pr = {
baseUser: pullRequest.base.repo.owner.login,
baseRepo: pullRequest.base.repo.name,
baseBranch: pullRequest.base.ref,
headUser: pullRequest.head.repo.owner.login,
headRepo: pullRequest.head.repo.name,
sha: pullRequest.head.sha,
title: 'PR #' + pullRequest.number + ': ' + pullRequest.title
};
return leeroyBranches.then(function (lb) {
var key = pr.baseUser + '/' + pr.baseRepo + '/' + pr.baseBranch;
log.info('Received pull_request event for ' + key + ': SHA = ' + pr.sha);
if (lb[key]) {
return setStatus(pr.baseUser, pr.baseRepo, pr.sha, 'pending', 'Preparing build')
.then(function () {
return Promise.all(lb[key].map(function (leeroyConfig) {
var buildUserRepo = leeroyConfig.repoUrl.match(buildRepoUrl);
var build = {
config: leeroyConfig,
repo: github.repos(buildUserRepo[1], buildUserRepo[2])
};
return getHeadCommit(pr, build)
.then(function (commit) {
return createNewCommit(pr, build, commit);
})
.then(function (newCommit) {
return createRef(pr, build, newCommit)
.then(function() {
activeBuilds[newCommit.sha] = pr;
return Promise.all(build.config.pullRequestBuildUrls.map(function (prBuildUrl) {
log.info('Starting a build at ' + prBuildUrl);
return superagent
.get(prBuildUrl)
.query({ sha1: newCommit.sha });
}));
});
});
}));
});
}
});
}
/**
* Calls the GitHub Status API to set the state for 'sha'.
* See https://developer.github.com/v3/repos/statuses/#create-a-status for parameter descriptions.
*/
function setStatus(user, repo, sha, state, description, targetUrl) {
return github.repos(user, repo).statuses(sha).create({
state: state,
description: description,
target_url: targetUrl,
context: 'leeroy-pull-request-builder'
});
}
/**
* Returns a promise for the SHA of the head of the build repo branch specified by
* the Leeroy config in 'build.config'.
*/
function getHeadCommit(pr, build) {
return build.repo.git.refs('heads', build.config.branch).fetch()
.then(function (ref) {
log.info('Repo ' + build.config.repoUrl + ' is at commit ' + ref.object.sha);
return build.repo.git.commits(ref.object.sha).fetch();
});
}
/**
* Returns a promise for a new build repo commit that updates the specified 'commit'
* with updated submodules for 'pr'.
*/
function createNewCommit(pr, build, commit) {
return build.repo.git.trees(commit.tree.sha).fetch()
.then(function(tree) {
return createNewTree(pr, build, tree);
})
.then(function (newTree) {
log.info('newTree = ' + newTree.sha);
return build.repo.git.commits.create({
message: pr.title,
tree: newTree.sha,
parents: [ commit.sha ]
});
});
}
/**
* Returns a promise for a new tree that updates .gitmodules and the submodules
* in 'tree' with the updated submodules for 'pr'.
*/
function createNewTree(pr, build, tree) {
// find the submodule that needs to be changed and update its SHA
var newItems = tree.tree.filter(function (treeItem) {
if (treeItem.mode === '160000' && treeItem.path == pr.baseRepo) {
treeItem.sha = pr.sha;
return true;
}
return false;
});
// find the .gitmodules file
var gitmodulesItem = tree.tree.filter(function (treeItem) {
return treeItem.path === '.gitmodules';
})[0];
// get the contents of .gitmodules
return build.repo.git.blobs(gitmodulesItem.sha).fetch()
.then(function (blob) {
// update .gitmodules with the repo URL the PR is coming from (because it has the commit we need)
var gitmodules = new Buffer(blob.content, 'base64').toString('utf-8')
.replace('git@git:' + pr.baseUser + '/' + pr.baseRepo + '.git', 'git@git:' + pr.headUser + '/' + pr.headRepo + '.git');
return build.repo.git.blobs.create({
content: gitmodules
});
})
.then(function (newBlob) {
// create a new tree with updated submodules and .gitmodules
gitmodulesItem.sha = newBlob.sha;
newItems.push(gitmodulesItem);
return build.repo.git.trees.create({
base_tree: tree.sha,
tree: newItems
});
})
}
/**
* Updates the 'lprb' (Leeroy Pull Request Builder) branch in 'build' to point at the specified commit SHA.
*/
function createRef(pr, build, newCommit) {
log.info('New commit is ' + newCommit.sha + '; updating ref.');
var refName = 'heads/lprb';
return build.repo.git.refs(refName).fetch()
.then(function () {
return build.repo.git.refs(refName).update({
sha: newCommit.sha,
force: true
});
}, function() {
return build.repo.git.refs.create({
ref: 'refs/' + refName,
sha: newCommit.sha
});
});
}
/**
* Gets all the repos+branches that have pullRequestBuildUrls set in their Leeroy configs.
*/
function getLeeroyBranches() {
return github.repos('Build', 'Configuration').contents.fetch()
.then(function (contents) {
log.info('Contents has ' + contents.length + ' files');
var jsonFiles = contents.filter(function (elem) {
return elem.path.indexOf('.json') === elem.path.length - 5;
});
return Promise.all(jsonFiles.map(function (elem) {
return github.repos('Build', 'Configuration').contents(elem.path).read()
.then(function (contents) {
try {
return JSON.parse(contents);
}
catch (e) {
return null;
}
});
}));
})
.then(function (files) {
var enabledFiles = files.filter(function (f) {
return f && !f.disabled && f.submodules && f.pullRequestBuildUrls && buildRepoUrl.test(f.repoUrl);
});
log.info('there are ' + enabledFiles.length + ' enabled files with submodules and PR build URLs.');
var repos = { };
enabledFiles.forEach(function (file) {
for (var submodule in file.submodules) {
var key = submodule + '/' + file.submodules[submodule];
repos[key] = repos[key] || [];
repos[key].push(file);
}
});
return repos;
})
.then(null, function(err) {
log.error(err);
});
}
var leeroyBranches = getLeeroyBranches();
var activeBuilds = {};
var buildRepoUrl = /^git@git:([^/]+)\/([^.]+).git$/;
| Set the Jenkins job description.
| bin/server.js | Set the Jenkins job description. | <ide><path>in/server.js
<ide> switch (req.body.build.phase) {
<ide> case 'STARTED':
<ide> setStatus(pr.baseUser, pr.baseRepo, pr.sha, 'pending', 'Building with Jenkins', req.body.build.full_url);
<add> superagent.post(req.body.build.full_url + '/submitDescription')
<add> .type('form')
<add> .send({
<add> description: pr.title,
<add> Submit: 'Submit'
<add> })
<add> .end();
<ide> break;
<ide> case 'COMPLETED':
<ide> setStatus(pr.baseUser, pr.baseRepo, pr.sha, |
|
Java | apache-2.0 | 3a483af490ac0fe6db8d9964c2e0c0dbd216e815 | 0 | vibe13/geronimo,meetdestiny/geronimo-trader,meetdestiny/geronimo-trader,meetdestiny/geronimo-trader,apache/geronimo,apache/geronimo,vibe13/geronimo,apache/geronimo,vibe13/geronimo,apache/geronimo,vibe13/geronimo | modules/security/src/java/org/apache/geronimo/security/jacc/AbstractModuleConfiguration.java | /**
*
* Copyright 2003-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.security.jacc;
import java.util.Collection;
import java.util.HashSet;
import javax.security.jacc.PolicyConfiguration;
import javax.security.jacc.PolicyConfigurationFactory;
import javax.security.jacc.PolicyContextException;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.gbean.GBeanLifecycle;
import org.apache.geronimo.common.GeronimoSecurityException;
/**
* @version $Rev$ $Date$
*/
public abstract class AbstractModuleConfiguration implements ModuleConfiguration, GBeanLifecycle {
public static final String BASE_OBJECT_NAME = "geronimo.security:type=ModuleConfiguration";
private String contextId;
private PolicyConfigurationFactory factory;
private PolicyConfiguration policyConfiguration;
private boolean configured = false;
private HashSet roleNames = new HashSet();
public AbstractModuleConfiguration(String contextId) throws GeronimoSecurityException {
this.contextId = contextId;
try {
factory = PolicyConfigurationFactory.getPolicyConfigurationFactory();
policyConfiguration = factory.getPolicyConfiguration(contextId, false);
} catch (ClassNotFoundException e) {
throw new GeronimoSecurityException("Unable to find PolicyConfigurationFactory", e);
} catch (PolicyContextException e) {
throw new GeronimoSecurityException("Unable to find policy configuration with that id", e);
}
}
/**
* Implement configuration from supplied metadata (dds) in subclasses.
*/
public void doStart() {
}
public void doStop() {
delete();
}
public void doFail() {
}
/**
* This method returns this object's policy context identifier.
*
* @return this module's policy context identifier.
*/
public String getContextID() {
return contextId;
}
/**
* Used to notify the abstract base class that the concrete implementation has completed adding all the role names.
*
* @param configured the state of the configuration
*/
protected void setConfigured(boolean configured) {
this.configured = configured;
}
/**
* This method returns the policy configuration that this bean is configuring.
*
* @return this object's policy configuration, <code>PolicyConfiguration</code>.
*/
protected PolicyConfiguration getPolicyConfiguration() {
return policyConfiguration;
}
/**
* This method returns the module's set of roles.
*
* @return the set of roles that are being used for this module.
*/
public HashSet getRoles() {
return roleNames;
}
/**
* Add a mapping from a module's security roles to physical principals. Mapping principals to the same role twice
* will cause a <code>PolicyContextException</code> to be thrown.
*
* @param role The role that is to be mapped to a set of principals.
* @param principals The set of principals that are to be mapped to to role.
* @throws org.apache.geronimo.security.GeronimoSecurityException if the mapping principals to the same role twice occurs.
*/
public void addRoleMapping(String role, Collection principals) throws GeronimoSecurityException {
if (!configured) throw new GeronimoSecurityException("Must call configure() first");
try {
RoleMappingConfiguration roleMapper = (RoleMappingConfiguration) policyConfiguration;
if (!roleNames.contains(role)) throw new GeronimoSecurityException("Role does not exist in this configuration");
roleMapper.addRoleMapping(role, principals);
} catch (ClassCastException cce) {
throw new GeronimoSecurityException("Policy configuration object does not implement RoleMappingConfiguration", cce.getCause());
} catch (PolicyContextException pe) {
throw new GeronimoSecurityException("Method addRoleMapping threw an exception", pe.getCause());
}
}
/**
* <p>Creates a relationship between this configuration and another such that they share the same principal-to-role
* mappings. <code>PolicyConfigurations</code> are linked to apply a common principal-to-role mapping to multiple
* seperately manageable <code>PolicyConfigurations</code>, as is required when an application is composed of
* multiple modules.</p>
* <p/>
* <p>Note that the policy statements which comprise a role, or comprise the excluded or unchecked policy
* collections in a <code>PolicyConfiguration</code> are unaffected by the configuration being linked to
* another.</p>
*
* @param link a reference to a different PolicyConfiguration than this <code>PolicyConfiguration</code>.
* <p>The relationship formed by this method is symetric, transitive and idempotent. If the argument
* <code>PolicyConfiguration</code> does not have a different Policy context identifier than this
* <code>PolicyConfiguration</code> no relationship is formed, and an exception, as described below, is thrown.
* @throws java.lang.SecurityException if called by an <code>AccessControlContext</code> that has not been granted
* the "setPolicy" <code>SecurityPermission</code>.
* @throws java.lang.UnsupportedOperationException if the state of the policy context whose interface is this
* <code>EjbModuleConfigurationMBean</code> Object is "deleted" or "inService" when this method is called.
* @throws java.lang.IllegalArgumentException if called with an argument <code>EjbModuleConfigurationMBean</code>
* whose Policy context is equivalent to that of this <code>EjbModuleConfigurationMBean</code>.
* @throws org.apache.geronimo.security.GeronimoSecurityException if the implementation throws a checked exception that has not been accounted for by
* the linkConfiguration method signature. The exception thrown by the implementation class will be encapsulated
* (during construction) in the thrown <code>GeronimoSecurityException</code>.
*/
public void linkConfiguration(ModuleConfiguration link) throws GeronimoSecurityException {
PolicyConfiguration other;
try {
other = factory.getPolicyConfiguration(link.getContextID(), false);
} catch (PolicyContextException e) {
throw new GeronimoSecurityException("Unable to find policy configuration with that id", e);
}
if (other != null) {
try {
policyConfiguration.linkConfiguration(other);
} catch (PolicyContextException e) {
throw new GeronimoSecurityException("Unable to link configuration", e.getCause());
}
}
}
/**
* <p>Causes all policy statements to be deleted from this <code>PolicyConfiguration</code> and sets its internal
* state such that calling any method, other than <code>delete</code>, <code>getContextID</code>, or
* <code>inService</code> on the <code>PolicyConfiguration</code> will be rejected and cause an
* <code>UnsupportedOperationException</code> to be thrown.</p>
* <p/>
* <p> This operation has no affect on any linked <code>PolicyConfigurations</code> other than removing any links
* involving the deleted <code>PolicyConfiguration<code>.</p>
*
* @throws java.lang.SecurityException if called by an <code>AccessControlContext</code> that has not been granted
* the "setPolicy" <code>SecurityPermission</code>.
* @throws org.apache.geronimo.security.GeronimoSecurityException if the implementation throws a checked exception that has not been accounted for by
* the delete method signature. The exception thrown by the implementation class will be encapsulated (during
* construction) in the thrown <code>GeronimoSecurityException</code>.
*/
public void delete() throws GeronimoSecurityException {
try {
policyConfiguration.delete();
} catch (PolicyContextException e) {
throw new GeronimoSecurityException("Unable to delete configuration", e.getCause());
}
}
/**
* <p>This method is used to set to "inService" the state of the policy context whose interface is this
* <code>PolicyConfiguration</code> Object. Only those policy contexts whose state is "inService" will be included
* in the policy contexts processed by the <code>Policy.refresh</code> method. A policy context whose state is
* "inService" may be returned to the "open" state by calling the <code>getPolicyConfiguration</code> method of the
* <code>PolicyConfiguration</code> factory with the policy context identifier of the policy context.</p>
* <p/>
* <p> When the state of a policy context is "inService", calling any method other than <code>commit</code>,
* <code>delete</code>, <code>getContextID</code>, or <code>inService</code> on its <code>PolicyConfiguration</code>
* Object will cause an <code>UnsupportedOperationException</code> to be thrown.</p>
*
* @throws java.lang.SecurityException if called by an <code>AccessControlContext</code> that has not been granted
* the "setPolicy" <code>SecurityPermission</code>.
* @throws java.lang.UnsupportedOperationException if the state of the policy context whose interface is this
* <code>PolicyConfiguration</code> Object is "deleted" when this method is called.
* @throws org.apache.geronimo.security.GeronimoSecurityException if the implementation throws a checked exception that has not been accounted for by
* the commit method signature. The exception thrown by the implementation class will be encapsulated (during
* construction) in the thrown <code>GeronimoSecurityException</code>.
*/
public void commit() throws GeronimoSecurityException {
try {
policyConfiguration.commit();
} catch (PolicyContextException e) {
throw new GeronimoSecurityException("Unable to commit configuration", e.getCause());
}
}
/**
* This method is used to determine if the policy context whose interface is this <code>PolicyConfiguration</code>
* Object is in the "inService" state.
*
* @return <code>true</code> if the state of the associated policy context is "inService"; <code>false</code>
* otherwise.
* @throws java.lang.SecurityException if called by an <code>AccessControlContext</code> that has not been granted
* the "setPolicy" <code>SecurityPermission</code>.
* @throws org.apache.geronimo.security.GeronimoSecurityException if the implementation throws a checked exception that has not been accounted for by the
* <code>inService</code> method signature. The exception thrown by the implementation class will be encapsulated
* (during construction) in the thrown <code>GeronimoSecurityException</code>.
*/
public boolean inService() throws GeronimoSecurityException {
try {
return policyConfiguration.inService();
} catch (PolicyContextException e) {
throw new GeronimoSecurityException("Unable to obtain inService state", e.getCause());
}
}
public static final GBeanInfo GBEAN_INFO;
static {
GBeanInfoBuilder infoFactory = new GBeanInfoBuilder(AbstractModuleConfiguration.class);
infoFactory.addAttribute("contextID", String.class, true);
infoFactory.addAttribute("roles", HashSet.class, true); //??persistent
infoFactory.addOperation("addRoleMapping", new Class[]{String.class, Collection.class});
infoFactory.addOperation("linkConfiguration", new Class[]{ModuleConfiguration.class});
infoFactory.addOperation("commit");
infoFactory.addOperation("inService");
GBEAN_INFO = infoFactory.getBeanInfo();
}
public static GBeanInfo getGBeanInfo() {
return GBEAN_INFO;
}
}
| No longer needed.
git-svn-id: d69ffe4ccc4861bf06065bd0072b85c931fba7ed@109643 13f79535-47bb-0310-9956-ffa450edef68
| modules/security/src/java/org/apache/geronimo/security/jacc/AbstractModuleConfiguration.java | No longer needed. | <ide><path>odules/security/src/java/org/apache/geronimo/security/jacc/AbstractModuleConfiguration.java
<del>/**
<del> *
<del> * Copyright 2003-2004 The Apache Software Foundation
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.apache.geronimo.security.jacc;
<del>
<del>import java.util.Collection;
<del>import java.util.HashSet;
<del>import javax.security.jacc.PolicyConfiguration;
<del>import javax.security.jacc.PolicyConfigurationFactory;
<del>import javax.security.jacc.PolicyContextException;
<del>
<del>import org.apache.geronimo.gbean.GBeanInfo;
<del>import org.apache.geronimo.gbean.GBeanInfoBuilder;
<del>import org.apache.geronimo.gbean.GBeanLifecycle;
<del>import org.apache.geronimo.common.GeronimoSecurityException;
<del>
<del>
<del>/**
<del> * @version $Rev$ $Date$
<del> */
<del>public abstract class AbstractModuleConfiguration implements ModuleConfiguration, GBeanLifecycle {
<del> public static final String BASE_OBJECT_NAME = "geronimo.security:type=ModuleConfiguration";
<del>
<del> private String contextId;
<del> private PolicyConfigurationFactory factory;
<del> private PolicyConfiguration policyConfiguration;
<del> private boolean configured = false;
<del> private HashSet roleNames = new HashSet();
<del>
<del> public AbstractModuleConfiguration(String contextId) throws GeronimoSecurityException {
<del> this.contextId = contextId;
<del>
<del> try {
<del> factory = PolicyConfigurationFactory.getPolicyConfigurationFactory();
<del> policyConfiguration = factory.getPolicyConfiguration(contextId, false);
<del> } catch (ClassNotFoundException e) {
<del> throw new GeronimoSecurityException("Unable to find PolicyConfigurationFactory", e);
<del> } catch (PolicyContextException e) {
<del> throw new GeronimoSecurityException("Unable to find policy configuration with that id", e);
<del> }
<del> }
<del>
<del> /**
<del> * Implement configuration from supplied metadata (dds) in subclasses.
<del> */
<del> public void doStart() {
<del>
<del> }
<del>
<del> public void doStop() {
<del> delete();
<del> }
<del>
<del> public void doFail() {
<del>
<del> }
<del>
<del> /**
<del> * This method returns this object's policy context identifier.
<del> *
<del> * @return this module's policy context identifier.
<del> */
<del> public String getContextID() {
<del> return contextId;
<del> }
<del>
<del> /**
<del> * Used to notify the abstract base class that the concrete implementation has completed adding all the role names.
<del> *
<del> * @param configured the state of the configuration
<del> */
<del> protected void setConfigured(boolean configured) {
<del> this.configured = configured;
<del> }
<del>
<del> /**
<del> * This method returns the policy configuration that this bean is configuring.
<del> *
<del> * @return this object's policy configuration, <code>PolicyConfiguration</code>.
<del> */
<del> protected PolicyConfiguration getPolicyConfiguration() {
<del> return policyConfiguration;
<del> }
<del>
<del> /**
<del> * This method returns the module's set of roles.
<del> *
<del> * @return the set of roles that are being used for this module.
<del> */
<del> public HashSet getRoles() {
<del> return roleNames;
<del> }
<del>
<del> /**
<del> * Add a mapping from a module's security roles to physical principals. Mapping principals to the same role twice
<del> * will cause a <code>PolicyContextException</code> to be thrown.
<del> *
<del> * @param role The role that is to be mapped to a set of principals.
<del> * @param principals The set of principals that are to be mapped to to role.
<del> * @throws org.apache.geronimo.security.GeronimoSecurityException if the mapping principals to the same role twice occurs.
<del> */
<del> public void addRoleMapping(String role, Collection principals) throws GeronimoSecurityException {
<del> if (!configured) throw new GeronimoSecurityException("Must call configure() first");
<del>
<del> try {
<del> RoleMappingConfiguration roleMapper = (RoleMappingConfiguration) policyConfiguration;
<del>
<del> if (!roleNames.contains(role)) throw new GeronimoSecurityException("Role does not exist in this configuration");
<del>
<del> roleMapper.addRoleMapping(role, principals);
<del> } catch (ClassCastException cce) {
<del> throw new GeronimoSecurityException("Policy configuration object does not implement RoleMappingConfiguration", cce.getCause());
<del> } catch (PolicyContextException pe) {
<del> throw new GeronimoSecurityException("Method addRoleMapping threw an exception", pe.getCause());
<del> }
<del> }
<del>
<del> /**
<del> * <p>Creates a relationship between this configuration and another such that they share the same principal-to-role
<del> * mappings. <code>PolicyConfigurations</code> are linked to apply a common principal-to-role mapping to multiple
<del> * seperately manageable <code>PolicyConfigurations</code>, as is required when an application is composed of
<del> * multiple modules.</p>
<del> * <p/>
<del> * <p>Note that the policy statements which comprise a role, or comprise the excluded or unchecked policy
<del> * collections in a <code>PolicyConfiguration</code> are unaffected by the configuration being linked to
<del> * another.</p>
<del> *
<del> * @param link a reference to a different PolicyConfiguration than this <code>PolicyConfiguration</code>.
<del> * <p>The relationship formed by this method is symetric, transitive and idempotent. If the argument
<del> * <code>PolicyConfiguration</code> does not have a different Policy context identifier than this
<del> * <code>PolicyConfiguration</code> no relationship is formed, and an exception, as described below, is thrown.
<del> * @throws java.lang.SecurityException if called by an <code>AccessControlContext</code> that has not been granted
<del> * the "setPolicy" <code>SecurityPermission</code>.
<del> * @throws java.lang.UnsupportedOperationException if the state of the policy context whose interface is this
<del> * <code>EjbModuleConfigurationMBean</code> Object is "deleted" or "inService" when this method is called.
<del> * @throws java.lang.IllegalArgumentException if called with an argument <code>EjbModuleConfigurationMBean</code>
<del> * whose Policy context is equivalent to that of this <code>EjbModuleConfigurationMBean</code>.
<del> * @throws org.apache.geronimo.security.GeronimoSecurityException if the implementation throws a checked exception that has not been accounted for by
<del> * the linkConfiguration method signature. The exception thrown by the implementation class will be encapsulated
<del> * (during construction) in the thrown <code>GeronimoSecurityException</code>.
<del> */
<del> public void linkConfiguration(ModuleConfiguration link) throws GeronimoSecurityException {
<del> PolicyConfiguration other;
<del>
<del> try {
<del> other = factory.getPolicyConfiguration(link.getContextID(), false);
<del> } catch (PolicyContextException e) {
<del> throw new GeronimoSecurityException("Unable to find policy configuration with that id", e);
<del> }
<del>
<del> if (other != null) {
<del> try {
<del> policyConfiguration.linkConfiguration(other);
<del> } catch (PolicyContextException e) {
<del> throw new GeronimoSecurityException("Unable to link configuration", e.getCause());
<del> }
<del>
<del> }
<del> }
<del>
<del> /**
<del> * <p>Causes all policy statements to be deleted from this <code>PolicyConfiguration</code> and sets its internal
<del> * state such that calling any method, other than <code>delete</code>, <code>getContextID</code>, or
<del> * <code>inService</code> on the <code>PolicyConfiguration</code> will be rejected and cause an
<del> * <code>UnsupportedOperationException</code> to be thrown.</p>
<del> * <p/>
<del> * <p> This operation has no affect on any linked <code>PolicyConfigurations</code> other than removing any links
<del> * involving the deleted <code>PolicyConfiguration<code>.</p>
<del> *
<del> * @throws java.lang.SecurityException if called by an <code>AccessControlContext</code> that has not been granted
<del> * the "setPolicy" <code>SecurityPermission</code>.
<del> * @throws org.apache.geronimo.security.GeronimoSecurityException if the implementation throws a checked exception that has not been accounted for by
<del> * the delete method signature. The exception thrown by the implementation class will be encapsulated (during
<del> * construction) in the thrown <code>GeronimoSecurityException</code>.
<del> */
<del> public void delete() throws GeronimoSecurityException {
<del> try {
<del> policyConfiguration.delete();
<del> } catch (PolicyContextException e) {
<del> throw new GeronimoSecurityException("Unable to delete configuration", e.getCause());
<del> }
<del> }
<del>
<del> /**
<del> * <p>This method is used to set to "inService" the state of the policy context whose interface is this
<del> * <code>PolicyConfiguration</code> Object. Only those policy contexts whose state is "inService" will be included
<del> * in the policy contexts processed by the <code>Policy.refresh</code> method. A policy context whose state is
<del> * "inService" may be returned to the "open" state by calling the <code>getPolicyConfiguration</code> method of the
<del> * <code>PolicyConfiguration</code> factory with the policy context identifier of the policy context.</p>
<del> * <p/>
<del> * <p> When the state of a policy context is "inService", calling any method other than <code>commit</code>,
<del> * <code>delete</code>, <code>getContextID</code>, or <code>inService</code> on its <code>PolicyConfiguration</code>
<del> * Object will cause an <code>UnsupportedOperationException</code> to be thrown.</p>
<del> *
<del> * @throws java.lang.SecurityException if called by an <code>AccessControlContext</code> that has not been granted
<del> * the "setPolicy" <code>SecurityPermission</code>.
<del> * @throws java.lang.UnsupportedOperationException if the state of the policy context whose interface is this
<del> * <code>PolicyConfiguration</code> Object is "deleted" when this method is called.
<del> * @throws org.apache.geronimo.security.GeronimoSecurityException if the implementation throws a checked exception that has not been accounted for by
<del> * the commit method signature. The exception thrown by the implementation class will be encapsulated (during
<del> * construction) in the thrown <code>GeronimoSecurityException</code>.
<del> */
<del> public void commit() throws GeronimoSecurityException {
<del> try {
<del> policyConfiguration.commit();
<del> } catch (PolicyContextException e) {
<del> throw new GeronimoSecurityException("Unable to commit configuration", e.getCause());
<del> }
<del> }
<del>
<del> /**
<del> * This method is used to determine if the policy context whose interface is this <code>PolicyConfiguration</code>
<del> * Object is in the "inService" state.
<del> *
<del> * @return <code>true</code> if the state of the associated policy context is "inService"; <code>false</code>
<del> * otherwise.
<del> * @throws java.lang.SecurityException if called by an <code>AccessControlContext</code> that has not been granted
<del> * the "setPolicy" <code>SecurityPermission</code>.
<del> * @throws org.apache.geronimo.security.GeronimoSecurityException if the implementation throws a checked exception that has not been accounted for by the
<del> * <code>inService</code> method signature. The exception thrown by the implementation class will be encapsulated
<del> * (during construction) in the thrown <code>GeronimoSecurityException</code>.
<del> */
<del> public boolean inService() throws GeronimoSecurityException {
<del> try {
<del> return policyConfiguration.inService();
<del> } catch (PolicyContextException e) {
<del> throw new GeronimoSecurityException("Unable to obtain inService state", e.getCause());
<del> }
<del> }
<del>
<del> public static final GBeanInfo GBEAN_INFO;
<del>
<del> static {
<del> GBeanInfoBuilder infoFactory = new GBeanInfoBuilder(AbstractModuleConfiguration.class);
<del>
<del> infoFactory.addAttribute("contextID", String.class, true);
<del> infoFactory.addAttribute("roles", HashSet.class, true); //??persistent
<del>
<del> infoFactory.addOperation("addRoleMapping", new Class[]{String.class, Collection.class});
<del> infoFactory.addOperation("linkConfiguration", new Class[]{ModuleConfiguration.class});
<del> infoFactory.addOperation("commit");
<del> infoFactory.addOperation("inService");
<del>
<del> GBEAN_INFO = infoFactory.getBeanInfo();
<del> }
<del>
<del> public static GBeanInfo getGBeanInfo() {
<del> return GBEAN_INFO;
<del> }
<del>
<del>} |
||
Java | agpl-3.0 | c41af241fe4b6427c860fa1f718e853031e5a0d3 | 0 | o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa,o2oa/o2oa | package com.x.processplatform.service.processing.factory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.script.CompiledScript;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.cache.Cache.CacheCategory;
import com.x.base.core.project.cache.Cache.CacheKey;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.script.ScriptFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.processplatform.core.entity.element.Activity;
import com.x.processplatform.core.entity.element.ActivityType;
import com.x.processplatform.core.entity.element.Agent;
import com.x.processplatform.core.entity.element.Begin;
import com.x.processplatform.core.entity.element.Cancel;
import com.x.processplatform.core.entity.element.Choice;
import com.x.processplatform.core.entity.element.Delay;
import com.x.processplatform.core.entity.element.Embed;
import com.x.processplatform.core.entity.element.End;
import com.x.processplatform.core.entity.element.Invoke;
import com.x.processplatform.core.entity.element.Manual;
import com.x.processplatform.core.entity.element.Mapping;
import com.x.processplatform.core.entity.element.Mapping_;
import com.x.processplatform.core.entity.element.Merge;
import com.x.processplatform.core.entity.element.Message;
import com.x.processplatform.core.entity.element.Parallel;
import com.x.processplatform.core.entity.element.Process;
import com.x.processplatform.core.entity.element.Route;
import com.x.processplatform.core.entity.element.Route_;
import com.x.processplatform.core.entity.element.Script;
import com.x.processplatform.core.entity.element.Script_;
import com.x.processplatform.core.entity.element.Service;
import com.x.processplatform.core.entity.element.Split;
import com.x.processplatform.service.processing.AbstractFactory;
import com.x.processplatform.service.processing.Business;
public class ElementFactory extends AbstractFactory {
private static Logger logger = LoggerFactory.getLogger(ElementFactory.class);
public ElementFactory(Business business) throws Exception {
super(business);
}
// 取得属于指定Process 的设计元素
@SuppressWarnings("unchecked")
public <T extends JpaObject> List<T> listWithProcess(Class<T> clz, Process process) throws Exception {
List<T> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(clz);
CacheKey cacheKey = new CacheKey("listWithProcess", process.getId());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<T>) optional.get();
} else {
EntityManager em = this.entityManagerContainer().get(clz);
List<T> os = this.entityManagerContainer().listEqual(clz, Activity.process_FIELDNAME, process.getId());
for (T t : os) {
em.detach(t);
list.add(t);
}
// 将object改为unmodifiable
list = Collections.unmodifiableList(list);
CacheManager.put(cacheCategory, cacheKey, list);
}
return list;
}
@SuppressWarnings("unchecked")
public <T extends JpaObject> T get(String id, Class<T> clz) throws Exception {
CacheCategory cacheCategory = new CacheCategory(clz);
CacheKey cacheKey = new CacheKey(id);
T t = null;
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
t = (T) optional.get();
} else {
t = this.entityManagerContainer().find(id, clz);
if(t != null) {
CacheManager.put(cacheCategory, cacheKey, t);
}
}
return t;
}
public Activity getActivity(String id) throws Exception {
Activity activity = null;
activity = this.get(id, ActivityType.manual);
if (null == activity) {
activity = this.get(id, ActivityType.begin);
if (null == activity) {
activity = this.get(id, ActivityType.cancel);
if (null == activity) {
activity = this.get(id, ActivityType.choice);
if (null == activity) {
activity = this.get(id, ActivityType.delay);
if (null == activity) {
activity = this.get(id, ActivityType.embed);
if (null == activity) {
activity = this.get(id, ActivityType.split);
if (null == activity) {
activity = this.get(id, ActivityType.invoke);
if (null == activity) {
activity = this.get(id, ActivityType.agent);
if (null == activity) {
activity = this.get(id, ActivityType.merge);
if (null == activity) {
activity = this.get(id, ActivityType.message);
if (null == activity) {
activity = this.get(id, ActivityType.parallel);
if (null == activity) {
activity = this.get(id, ActivityType.service);
if (null == activity) {
activity = this.get(id, ActivityType.end);
}
}
}
}
}
}
}
}
}
}
}
}
}
return activity;
}
public Activity get(String id, ActivityType activityType) throws Exception {
switch (activityType) {
case agent:
return this.get(id, Agent.class);
case begin:
return this.get(id, Begin.class);
case cancel:
return this.get(id, Cancel.class);
case choice:
return this.get(id, Choice.class);
case delay:
return this.get(id, Delay.class);
case embed:
return this.get(id, Embed.class);
case end:
return this.get(id, End.class);
case invoke:
return this.get(id, Invoke.class);
case manual:
return this.get(id, Manual.class);
case merge:
return this.get(id, Merge.class);
case message:
return this.get(id, Message.class);
case parallel:
return this.get(id, Parallel.class);
case service:
return this.get(id, Service.class);
case split:
return this.get(id, Split.class);
default:
return null;
}
}
// 用Process的updateTime作为缓存值
public Begin getBeginWithProcess(String id) throws Exception {
Begin begin = null;
CacheCategory cacheCategory = new CacheCategory(Begin.class);
CacheKey cacheKey = new CacheKey("getBeginWithProcess", id);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
begin = (Begin) optional.get();
} else {
begin = this.entityManagerContainer().firstEqual(Begin.class, Activity.process_FIELDNAME, id);
CacheManager.put(cacheCategory, cacheKey, begin);
}
return begin;
}
@SuppressWarnings("unchecked")
public List<Route> listRouteWithChoice(String id) throws Exception {
List<Route> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Route.class);
CacheKey cacheKey = new CacheKey(id, Choice.class.getName());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<Route>) optional.get();
} else {
EntityManager em = this.entityManagerContainer().get(Route.class);
Choice choice = this.get(id, Choice.class);
if (null != choice) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Route> cq = cb.createQuery(Route.class);
Root<Route> root = cq.from(Route.class);
Predicate p = root.get(Route_.id).in(choice.getRouteList());
list = em.createQuery(cq.where(p).orderBy(cb.asc(root.get(Route_.orderNumber)))).getResultList();
CacheManager.put(cacheCategory, cacheKey, list);
}
}
return list;
}
@SuppressWarnings("unchecked")
public List<Route> listRouteWithManual(String id) throws Exception {
List<Route> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Route.class);
CacheKey cacheKey = new CacheKey(id, Manual.class.getName());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<Route>) optional.get();
} else {
EntityManager em = this.entityManagerContainer().get(Route.class);
Manual manual = this.get(id, Manual.class);
if (null != manual) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Route> cq = cb.createQuery(Route.class);
Root<Route> root = cq.from(Route.class);
Predicate p = root.get(Route_.id).in(manual.getRouteList());
list = em.createQuery(cq.where(p).orderBy(cb.asc(root.get(Route_.orderNumber)))).getResultList();
CacheManager.put(cacheCategory, cacheKey, list);
}
}
return list;
}
@SuppressWarnings("unchecked")
public List<Route> listRouteWithParallel(String id) throws Exception {
List<Route> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Route.class);
CacheKey cacheKey = new CacheKey(id, Parallel.class.getName());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<Route>) optional.get();
} else {
EntityManager em = this.entityManagerContainer().get(Route.class);
Parallel parallel = this.get(id, Parallel.class);
if (null != parallel) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Route> cq = cb.createQuery(Route.class);
Root<Route> root = cq.from(Route.class);
Predicate p = root.get(Route_.id).in(parallel.getRouteList());
list = em.createQuery(cq.where(p).orderBy(cb.asc(root.get(Route_.orderNumber)))).getResultList();
CacheManager.put(cacheCategory, cacheKey, list);
}
}
return list;
}
@SuppressWarnings("unchecked")
public List<Script> listScriptNestedWithApplicationWithUniqueName(String applicationId, String uniqueName)
throws Exception {
List<Script> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Script.class);
CacheKey cacheKey = new CacheKey("listScriptNestedWithApplicationWithUniqueName", applicationId, uniqueName);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<Script>) optional.get();
} else {
List<String> names = new ArrayList<>();
names.add(uniqueName);
while (!names.isEmpty()) {
List<String> loops = new ArrayList<>();
for (String name : names) {
Script o = this.getScriptWithApplicationWithUniqueName(applicationId, name);
if ((null != o) && (!list.contains(o))) {
list.add(o);
loops.addAll(o.getDependScriptList());
}
}
names = loops;
}
Collections.reverse(list);
CacheManager.put(cacheCategory, cacheKey, list);
}
return list;
}
private Script getScriptWithApplicationWithUniqueName(String applicationId, String uniqueName) throws Exception {
Script script = null;
EntityManager em = this.entityManagerContainer().get(Script.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Script> cq = cb.createQuery(Script.class);
Root<Script> root = cq.from(Script.class);
Predicate p = cb.equal(root.get(Script_.name), uniqueName);
p = cb.or(p, cb.equal(root.get(Script_.alias), uniqueName));
p = cb.or(p, cb.equal(root.get(Script_.id), uniqueName));
p = cb.and(p, cb.equal(root.get(Script_.application), applicationId));
List<Script> list = em.createQuery(cq.where(p)).setMaxResults(1).getResultList();
if (!list.isEmpty()) {
script = list.get(0);
}
return script;
}
public List<Route> listRouteWithActvity(String id, ActivityType activityType) throws Exception {
List<Route> list = new ArrayList<>();
switch (activityType) {
case agent:
Agent agent = this.get(id, Agent.class);
list.add(this.get(agent.getRoute(), Route.class));
break;
case begin:
Begin begin = this.get(id, Begin.class);
list.add(this.get(begin.getRoute(), Route.class));
break;
case cancel:
break;
case choice:
Choice choice = this.get(id, Choice.class);
for (String str : choice.getRouteList()) {
list.add(this.get(str, Route.class));
}
break;
case delay:
Delay delay = this.get(id, Delay.class);
list.add(this.get(delay.getRoute(), Route.class));
break;
case embed:
Embed embed = this.get(id, Embed.class);
list.add(this.get(embed.getRoute(), Route.class));
break;
case end:
break;
case invoke:
Invoke invoke = this.get(id, Invoke.class);
list.add(this.get(invoke.getRoute(), Route.class));
break;
case manual:
Manual manual = this.get(id, Manual.class);
for (String str : manual.getRouteList()) {
list.add(this.get(str, Route.class));
}
break;
case merge:
Merge merge = this.get(id, Merge.class);
list.add(this.get(merge.getRoute(), Route.class));
break;
case message:
Message message = this.get(id, Message.class);
list.add(this.get(message.getRoute(), Route.class));
break;
case parallel:
Parallel parallel = this.get(id, Parallel.class);
for (String str : parallel.getRouteList()) {
list.add(this.get(str, Route.class));
}
break;
case service:
Service service = this.get(id, Service.class);
list.add(this.get(service.getRoute(), Route.class));
break;
case split:
Split split = this.get(id, Split.class);
list.add(this.get(split.getRoute(), Route.class));
break;
default:
break;
}
return ListTools.trim(list, true, true);
}
public List<String> listFormWithProcess(Process process) throws Exception {
List<String> ids = new ArrayList<>();
this.listWithProcess(Agent.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Begin.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Cancel.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Choice.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Delay.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Embed.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(End.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Invoke.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Manual.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Merge.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Message.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Parallel.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Service.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Split.class, process).forEach(o -> {
ids.add(o.getForm());
});
return ListTools.trim(ids, true, true);
}
@SuppressWarnings("unchecked")
public List<Mapping> listMappingEffectiveWithApplicationAndProcess(String application, String process)
throws Exception {
final List<Mapping> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Mapping.class);
CacheKey cacheKey = new CacheKey("listMappingEffectiveWithApplicationAndProcess", application, process);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list.addAll((List<Mapping>) optional.get());
} else {
EntityManager em = this.entityManagerContainer().get(Mapping.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Mapping> cq = cb.createQuery(Mapping.class);
Root<Mapping> root = cq.from(Mapping.class);
Predicate p = cb.equal(root.get(Mapping_.enable), true);
p = cb.and(p, cb.equal(root.get(Mapping_.application), application));
p = cb.and(p, cb.or(cb.equal(root.get(Mapping_.process), process), cb.equal(root.get(Mapping_.process), ""),
cb.isNull(root.get(Mapping_.process))));
List<Mapping> os = em.createQuery(cq.where(p)).getResultList();
os.stream().collect(Collectors.groupingBy(o -> {
return o.getApplication() + o.getTableName();
})).forEach((k, v) -> {
list.add(v.stream().filter(i -> StringUtils.isNotEmpty(i.getProcess())).findFirst().orElse(v.get(0)));
});
CacheManager.put(cacheCategory, cacheKey, list);
}
return list;
}
public CompiledScript getCompiledScript(String applicationId, Activity o, String event) throws Exception {
CacheCategory cacheCategory = new CacheCategory(o.getClass(), Script.class);
CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
CompiledScript compiledScript = null;
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
String scriptName = null;
String scriptText = null;
switch (event) {
case Business.EVENT_BEFOREARRIVE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeArriveScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeArriveScriptText_FIELDNAME));
break;
case Business.EVENT_AFTERARRIVE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterArriveScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterArriveScriptText_FIELDNAME));
break;
case Business.EVENT_BEFOREEXECUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeExecuteScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeExecuteScriptText_FIELDNAME));
break;
case Business.EVENT_AFTEREXECUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterExecuteScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterExecuteScriptText_FIELDNAME));
break;
case Business.EVENT_BEFOREINQUIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeInquireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeInquireScriptText_FIELDNAME));
break;
case Business.EVENT_AFTERINQUIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterInquireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterInquireScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALTASKEXPIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.taskExpireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.taskExpireScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALTASK:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.taskScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.taskScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALSTAY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualStayScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.manualStayScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALBEFORETASK:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualBeforeTaskScript_FIELDNAME));
scriptText = Objects
.toString(PropertyUtils.getProperty(o, Manual.manualBeforeTaskScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALAFTERTASK:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualAfterTaskScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.manualAfterTaskScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXWSPARAMETER:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsParameterScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsParameterScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXRSPARAMETER:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsParameterScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsParameterScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXWSRESPONSE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsResponseScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsResponseScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXRSRESPONSE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsResponseScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsResponseScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXRSBODY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsBodyScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsBodyScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXRSHEAD:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsHeadScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsHeadScriptText_FIELDNAME));
break;
case Business.EVENT_READ:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.readScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.readScriptText_FIELDNAME));
break;
case Business.EVENT_REVIEW:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.reviewScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.reviewScriptText_FIELDNAME));
break;
case Business.EVENT_AGENT:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Agent.script_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Agent.scriptText_FIELDNAME));
break;
case Business.EVENT_SERVICE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Service.script_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Service.scriptText_FIELDNAME));
break;
case Business.EVENT_AGENTINTERRUPT:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Agent.agentInterruptScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Agent.agentInterruptScriptText_FIELDNAME));
break;
case Business.EVENT_DELAY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Delay.delayScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Delay.delayScriptText_FIELDNAME));
break;
case Business.EVENT_EMBEDTARGETASSIGNDATA:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetAssginDataScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetAssginDataScriptText_FIELDNAME));
break;
case Business.EVENT_EMBEDTARGETIDENTITY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetIdentityScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetIdentityScriptText_FIELDNAME));
break;
case Business.EVENT_EMBEDTARGETTITLE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetTitleScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetTitleScriptText_FIELDNAME));
break;
case Business.EVENT_SPLIT:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Split.script_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Split.scriptText_FIELDNAME));
break;
default:
break;
}
StringBuilder sb = new StringBuilder();
try {
sb.append("(function(){").append(System.lineSeparator());
if (StringUtils.isNotEmpty(scriptName)) {
List<Script> list = listScriptNestedWithApplicationWithUniqueName(applicationId, scriptName);
for (Script script : list) {
sb.append(script.getText()).append(System.lineSeparator());
}
}
if (StringUtils.isNotEmpty(scriptText)) {
sb.append(scriptText).append(System.lineSeparator());
}
sb.append("}).apply(bind);");
compiledScript = ScriptFactory.compile(sb.toString());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
} catch (Exception e) {
logger.error(e);
}
}
return compiledScript;
}
public CompiledScript getCompiledScript(String applicationId, Route o, String event) throws Exception {
CacheCategory cacheCategory = new CacheCategory(Route.class, Script.class);
CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
CompiledScript compiledScript = null;
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
String scriptName = null;
String scriptText = null;
switch (event) {
case Business.EVENT_ROUTEAPPENDTASKIDENTITY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Route.appendTaskIdentityScript_FIELDNAME));
scriptText = Objects
.toString(PropertyUtils.getProperty(o, Route.appendTaskIdentityScriptText_FIELDNAME));
break;
case Business.EVENT_ROUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Route.script_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Route.scriptText_FIELDNAME));
break;
default:
break;
}
StringBuilder sb = new StringBuilder();
try {
sb.append("(function(){").append(System.lineSeparator());
if (StringUtils.isNotEmpty(scriptName)) {
List<Script> list = listScriptNestedWithApplicationWithUniqueName(applicationId, scriptName);
for (Script script : list) {
sb.append(script.getText()).append(System.lineSeparator());
}
}
if (StringUtils.isNotEmpty(scriptText)) {
sb.append(scriptText).append(System.lineSeparator());
}
sb.append("}).apply(bind);");
compiledScript = ScriptFactory.compile(sb.toString());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
} catch (Exception e) {
logger.error(e);
}
}
return compiledScript;
}
public CompiledScript getCompiledScript(String applicationId, Process o, String event) throws Exception {
CacheCategory cacheCategory = new CacheCategory(Process.class, Script.class);
CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
CompiledScript compiledScript = null;
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
String scriptName = null;
String scriptText = null;
switch (event) {
case Business.EVENT_BEFOREARRIVE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeArriveScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeArriveScriptText_FIELDNAME));
break;
case Business.EVENT_AFTERARRIVE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterArriveScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterArriveScriptText_FIELDNAME));
break;
case Business.EVENT_BEFOREEXECUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeExecuteScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeExecuteScriptText_FIELDNAME));
break;
case Business.EVENT_AFTEREXECUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterExecuteScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterExecuteScriptText_FIELDNAME));
break;
case Business.EVENT_BEFOREINQUIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeInquireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeInquireScriptText_FIELDNAME));
break;
case Business.EVENT_AFTERINQUIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterInquireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterInquireScriptText_FIELDNAME));
break;
case Business.EVENT_PROCESSAFTERBEGIN:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterBeginScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterBeginScriptText_FIELDNAME));
break;
case Business.EVENT_PROCESSAFTEREND:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterEndScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterEndScriptText_FIELDNAME));
break;
case Business.EVENT_PROCESSEXPIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.expireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.expireScriptText_FIELDNAME));
break;
default:
break;
}
StringBuilder sb = new StringBuilder();
try {
sb.append("(function(){").append(System.lineSeparator());
if (StringUtils.isNotEmpty(scriptName)) {
List<Script> list = listScriptNestedWithApplicationWithUniqueName(applicationId, scriptName);
for (Script script : list) {
sb.append(script.getText()).append(System.lineSeparator());
}
}
if (StringUtils.isNotEmpty(scriptText)) {
sb.append(scriptText).append(System.lineSeparator());
}
sb.append("}).apply(bind);");
compiledScript = ScriptFactory.compile(sb.toString());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
} catch (Exception e) {
logger.error(e);
}
}
return compiledScript;
}
public CompiledScript getCompiledScript(Activity activity, String event, String name, String code) {
CacheCategory cacheCategory = new CacheCategory(activity.getClass(), Script.class);
CacheKey cacheKey = new CacheKey("getCompiledScript", activity.getId(), event, name, code);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
CompiledScript compiledScript = null;
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
StringBuilder sb = new StringBuilder();
try {
sb.append("(function(){").append(System.lineSeparator());
if (StringUtils.isNotEmpty(code)) {
sb.append(code).append(System.lineSeparator());
}
sb.append("}).apply(bind);");
compiledScript = ScriptFactory.compile(sb.toString());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
} catch (Exception e) {
logger.error(e);
}
}
return compiledScript;
}
}
| o2server/x_processplatform_service_processing/src/main/java/com/x/processplatform/service/processing/factory/ElementFactory.java | package com.x.processplatform.service.processing.factory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.script.CompiledScript;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.cache.Cache.CacheCategory;
import com.x.base.core.project.cache.Cache.CacheKey;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.script.ScriptFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.processplatform.core.entity.element.Activity;
import com.x.processplatform.core.entity.element.ActivityType;
import com.x.processplatform.core.entity.element.Agent;
import com.x.processplatform.core.entity.element.Begin;
import com.x.processplatform.core.entity.element.Cancel;
import com.x.processplatform.core.entity.element.Choice;
import com.x.processplatform.core.entity.element.Delay;
import com.x.processplatform.core.entity.element.Embed;
import com.x.processplatform.core.entity.element.End;
import com.x.processplatform.core.entity.element.Invoke;
import com.x.processplatform.core.entity.element.Manual;
import com.x.processplatform.core.entity.element.Mapping;
import com.x.processplatform.core.entity.element.Mapping_;
import com.x.processplatform.core.entity.element.Merge;
import com.x.processplatform.core.entity.element.Message;
import com.x.processplatform.core.entity.element.Parallel;
import com.x.processplatform.core.entity.element.Process;
import com.x.processplatform.core.entity.element.Route;
import com.x.processplatform.core.entity.element.Route_;
import com.x.processplatform.core.entity.element.Script;
import com.x.processplatform.core.entity.element.Script_;
import com.x.processplatform.core.entity.element.Service;
import com.x.processplatform.core.entity.element.Split;
import com.x.processplatform.service.processing.AbstractFactory;
import com.x.processplatform.service.processing.Business;
public class ElementFactory extends AbstractFactory {
private static Logger logger = LoggerFactory.getLogger(ElementFactory.class);
public ElementFactory(Business business) throws Exception {
super(business);
}
// 取得属于指定Process 的设计元素
@SuppressWarnings("unchecked")
public <T extends JpaObject> List<T> listWithProcess(Class<T> clz, Process process) throws Exception {
List<T> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(clz);
CacheKey cacheKey = new CacheKey("listWithProcess", process.getId());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<T>) optional.get();
} else {
EntityManager em = this.entityManagerContainer().get(clz);
List<T> os = this.entityManagerContainer().listEqual(clz, Activity.process_FIELDNAME, process.getId());
for (T t : os) {
em.detach(t);
list.add(t);
}
// 将object改为unmodifiable
list = Collections.unmodifiableList(list);
CacheManager.put(cacheCategory, cacheKey, list);
}
return list;
}
@SuppressWarnings("unchecked")
public <T extends JpaObject> T get(String id, Class<T> clz) throws Exception {
CacheCategory cacheCategory = new CacheCategory(clz);
CacheKey cacheKey = new CacheKey(id);
T t = null;
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
t = (T) optional.get();
} else {
t = this.entityManagerContainer().find(id, clz);
if(t != null) {
CacheManager.put(cacheCategory, cacheKey, t);
}
}
return t;
}
public Activity getActivity(String id) throws Exception {
Activity activity = null;
activity = this.get(id, ActivityType.manual);
if (null == activity) {
activity = this.get(id, ActivityType.begin);
if (null == activity) {
activity = this.get(id, ActivityType.cancel);
if (null == activity) {
activity = this.get(id, ActivityType.choice);
if (null == activity) {
activity = this.get(id, ActivityType.delay);
if (null == activity) {
activity = this.get(id, ActivityType.embed);
if (null == activity) {
activity = this.get(id, ActivityType.split);
if (null == activity) {
activity = this.get(id, ActivityType.invoke);
if (null == activity) {
activity = this.get(id, ActivityType.agent);
if (null == activity) {
activity = this.get(id, ActivityType.merge);
if (null == activity) {
activity = this.get(id, ActivityType.message);
if (null == activity) {
activity = this.get(id, ActivityType.parallel);
if (null == activity) {
activity = this.get(id, ActivityType.service);
if (null == activity) {
activity = this.get(id, ActivityType.end);
}
}
}
}
}
}
}
}
}
}
}
}
}
return activity;
}
public Activity get(String id, ActivityType activityType) throws Exception {
switch (activityType) {
case agent:
return this.get(id, Agent.class);
case begin:
return this.get(id, Begin.class);
case cancel:
return this.get(id, Cancel.class);
case choice:
return this.get(id, Choice.class);
case delay:
return this.get(id, Delay.class);
case embed:
return this.get(id, Embed.class);
case end:
return this.get(id, End.class);
case invoke:
return this.get(id, Invoke.class);
case manual:
return this.get(id, Manual.class);
case merge:
return this.get(id, Merge.class);
case message:
return this.get(id, Message.class);
case parallel:
return this.get(id, Parallel.class);
case service:
return this.get(id, Service.class);
case split:
return this.get(id, Split.class);
default:
return null;
}
}
// 用Process的updateTime作为缓存值
public Begin getBeginWithProcess(String id) throws Exception {
Begin begin = null;
CacheCategory cacheCategory = new CacheCategory(Begin.class);
CacheKey cacheKey = new CacheKey("getBeginWithProcess", id);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
begin = (Begin) optional.get();
} else {
begin = this.entityManagerContainer().firstEqual(Begin.class, Activity.process_FIELDNAME, id);
CacheManager.put(cacheCategory, cacheKey, begin);
}
return begin;
}
@SuppressWarnings("unchecked")
public List<Route> listRouteWithChoice(String id) throws Exception {
List<Route> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Route.class);
CacheKey cacheKey = new CacheKey(id, Choice.class.getName());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<Route>) optional.get();
} else {
EntityManager em = this.entityManagerContainer().get(Route.class);
Choice choice = this.get(id, Choice.class);
if (null != choice) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Route> cq = cb.createQuery(Route.class);
Root<Route> root = cq.from(Route.class);
Predicate p = root.get(Route_.id).in(choice.getRouteList());
list = em.createQuery(cq.where(p).orderBy(cb.asc(root.get(Route_.orderNumber)))).getResultList();
CacheManager.put(cacheCategory, cacheKey, list);
}
}
return list;
}
@SuppressWarnings("unchecked")
public List<Route> listRouteWithManual(String id) throws Exception {
List<Route> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Route.class);
CacheKey cacheKey = new CacheKey(id, Manual.class.getName());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<Route>) optional.get();
} else {
EntityManager em = this.entityManagerContainer().get(Route.class);
Manual manual = this.get(id, Manual.class);
if (null != manual) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Route> cq = cb.createQuery(Route.class);
Root<Route> root = cq.from(Route.class);
Predicate p = root.get(Route_.id).in(manual.getRouteList());
list = em.createQuery(cq.where(p).orderBy(cb.asc(root.get(Route_.orderNumber)))).getResultList();
CacheManager.put(cacheCategory, cacheKey, list);
}
}
return list;
}
@SuppressWarnings("unchecked")
public List<Route> listRouteWithParallel(String id) throws Exception {
List<Route> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Route.class);
CacheKey cacheKey = new CacheKey(id, Parallel.class.getName());
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<Route>) optional.get();
} else {
EntityManager em = this.entityManagerContainer().get(Route.class);
Parallel parallel = this.get(id, Parallel.class);
if (null != parallel) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Route> cq = cb.createQuery(Route.class);
Root<Route> root = cq.from(Route.class);
Predicate p = root.get(Route_.id).in(parallel.getRouteList());
list = em.createQuery(cq.where(p).orderBy(cb.asc(root.get(Route_.orderNumber)))).getResultList();
CacheManager.put(cacheCategory, cacheKey, list);
}
}
return list;
}
@SuppressWarnings("unchecked")
public List<Script> listScriptNestedWithApplicationWithUniqueName(String applicationId, String uniqueName)
throws Exception {
List<Script> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Script.class);
CacheKey cacheKey = new CacheKey("listScriptNestedWithApplicationWithUniqueName", applicationId, uniqueName);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list = (List<Script>) optional.get();
} else {
List<String> names = new ArrayList<>();
names.add(uniqueName);
while (!names.isEmpty()) {
List<String> loops = new ArrayList<>();
for (String name : names) {
Script o = this.getScriptWithApplicationWithUniqueName(applicationId, name);
if ((null != o) && (!list.contains(o))) {
list.add(o);
loops.addAll(o.getDependScriptList());
}
}
names = loops;
}
Collections.reverse(list);
CacheManager.put(cacheCategory, cacheKey, list);
}
return list;
}
private Script getScriptWithApplicationWithUniqueName(String applicationId, String uniqueName) throws Exception {
Script script = null;
EntityManager em = this.entityManagerContainer().get(Script.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Script> cq = cb.createQuery(Script.class);
Root<Script> root = cq.from(Script.class);
Predicate p = cb.equal(root.get(Script_.name), uniqueName);
p = cb.or(p, cb.equal(root.get(Script_.alias), uniqueName));
p = cb.or(p, cb.equal(root.get(Script_.id), uniqueName));
p = cb.and(p, cb.equal(root.get(Script_.application), applicationId));
List<Script> list = em.createQuery(cq.where(p)).setMaxResults(1).getResultList();
if (!list.isEmpty()) {
script = list.get(0);
}
return script;
}
public List<Route> listRouteWithActvity(String id, ActivityType activityType) throws Exception {
List<Route> list = new ArrayList<>();
switch (activityType) {
case agent:
Agent agent = this.get(id, Agent.class);
list.add(this.get(agent.getRoute(), Route.class));
break;
case begin:
Begin begin = this.get(id, Begin.class);
list.add(this.get(begin.getRoute(), Route.class));
break;
case cancel:
break;
case choice:
Choice choice = this.get(id, Choice.class);
for (String str : choice.getRouteList()) {
list.add(this.get(str, Route.class));
}
break;
case delay:
Delay delay = this.get(id, Delay.class);
list.add(this.get(delay.getRoute(), Route.class));
break;
case embed:
Embed embed = this.get(id, Embed.class);
list.add(this.get(embed.getRoute(), Route.class));
break;
case end:
break;
case invoke:
Invoke invoke = this.get(id, Invoke.class);
list.add(this.get(invoke.getRoute(), Route.class));
break;
case manual:
Manual manual = this.get(id, Manual.class);
for (String str : manual.getRouteList()) {
list.add(this.get(str, Route.class));
}
break;
case merge:
Merge merge = this.get(id, Merge.class);
list.add(this.get(merge.getRoute(), Route.class));
break;
case message:
Message message = this.get(id, Message.class);
list.add(this.get(message.getRoute(), Route.class));
break;
case parallel:
Parallel parallel = this.get(id, Parallel.class);
for (String str : parallel.getRouteList()) {
list.add(this.get(str, Route.class));
}
break;
case service:
Service service = this.get(id, Service.class);
list.add(this.get(service.getRoute(), Route.class));
break;
case split:
Split split = this.get(id, Split.class);
list.add(this.get(split.getRoute(), Route.class));
break;
default:
break;
}
return ListTools.trim(list, true, true);
}
public List<String> listFormWithProcess(Process process) throws Exception {
List<String> ids = new ArrayList<>();
this.listWithProcess(Agent.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Begin.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Cancel.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Choice.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Delay.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Embed.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(End.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Invoke.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Manual.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Merge.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Message.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Parallel.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Service.class, process).forEach(o -> {
ids.add(o.getForm());
});
this.listWithProcess(Split.class, process).forEach(o -> {
ids.add(o.getForm());
});
return ListTools.trim(ids, true, true);
}
@SuppressWarnings("unchecked")
public List<Mapping> listMappingEffectiveWithApplicationAndProcess(String application, String process)
throws Exception {
final List<Mapping> list = new ArrayList<>();
CacheCategory cacheCategory = new CacheCategory(Mapping.class);
CacheKey cacheKey = new CacheKey("listMappingEffectiveWithApplicationAndProcess", application, process);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
list.addAll((List<Mapping>) optional.get());
} else {
EntityManager em = this.entityManagerContainer().get(Mapping.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Mapping> cq = cb.createQuery(Mapping.class);
Root<Mapping> root = cq.from(Mapping.class);
Predicate p = cb.equal(root.get(Mapping_.enable), true);
p = cb.and(p, cb.equal(root.get(Mapping_.application), application));
p = cb.and(p, cb.or(cb.equal(root.get(Mapping_.process), process), cb.equal(root.get(Mapping_.process), ""),
cb.isNull(root.get(Mapping_.process))));
List<Mapping> os = em.createQuery(cq.where(p)).getResultList();
os.stream().collect(Collectors.groupingBy(o -> {
return o.getApplication() + o.getTableName();
})).forEach((k, v) -> {
list.add(v.stream().filter(i -> StringUtils.isNotEmpty(i.getProcess())).findFirst().orElse(v.get(0)));
});
CacheManager.put(cacheCategory, cacheKey, list);
}
return list;
}
public CompiledScript getCompiledScript(String applicationId, Activity o, String event) throws Exception {
CacheCategory cacheCategory = new CacheCategory(o.getClass());
CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
CompiledScript compiledScript = null;
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
String scriptName = null;
String scriptText = null;
switch (event) {
case Business.EVENT_BEFOREARRIVE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeArriveScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeArriveScriptText_FIELDNAME));
break;
case Business.EVENT_AFTERARRIVE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterArriveScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterArriveScriptText_FIELDNAME));
break;
case Business.EVENT_BEFOREEXECUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeExecuteScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeExecuteScriptText_FIELDNAME));
break;
case Business.EVENT_AFTEREXECUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterExecuteScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterExecuteScriptText_FIELDNAME));
break;
case Business.EVENT_BEFOREINQUIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeInquireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeInquireScriptText_FIELDNAME));
break;
case Business.EVENT_AFTERINQUIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterInquireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterInquireScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALTASKEXPIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.taskExpireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.taskExpireScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALTASK:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.taskScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.taskScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALSTAY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualStayScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.manualStayScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALBEFORETASK:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualBeforeTaskScript_FIELDNAME));
scriptText = Objects
.toString(PropertyUtils.getProperty(o, Manual.manualBeforeTaskScriptText_FIELDNAME));
break;
case Business.EVENT_MANUALAFTERTASK:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualAfterTaskScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.manualAfterTaskScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXWSPARAMETER:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsParameterScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsParameterScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXRSPARAMETER:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsParameterScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsParameterScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXWSRESPONSE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsResponseScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsResponseScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXRSRESPONSE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsResponseScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsResponseScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXRSBODY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsBodyScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsBodyScriptText_FIELDNAME));
break;
case Business.EVENT_INVOKEJAXRSHEAD:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsHeadScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsHeadScriptText_FIELDNAME));
break;
case Business.EVENT_READ:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.readScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.readScriptText_FIELDNAME));
break;
case Business.EVENT_REVIEW:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.reviewScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.reviewScriptText_FIELDNAME));
break;
case Business.EVENT_AGENT:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Agent.script_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Agent.scriptText_FIELDNAME));
break;
case Business.EVENT_SERVICE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Service.script_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Service.scriptText_FIELDNAME));
break;
case Business.EVENT_AGENTINTERRUPT:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Agent.agentInterruptScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Agent.agentInterruptScriptText_FIELDNAME));
break;
case Business.EVENT_DELAY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Delay.delayScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Delay.delayScriptText_FIELDNAME));
break;
case Business.EVENT_EMBEDTARGETASSIGNDATA:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetAssginDataScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetAssginDataScriptText_FIELDNAME));
break;
case Business.EVENT_EMBEDTARGETIDENTITY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetIdentityScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetIdentityScriptText_FIELDNAME));
break;
case Business.EVENT_EMBEDTARGETTITLE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetTitleScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetTitleScriptText_FIELDNAME));
break;
case Business.EVENT_SPLIT:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Split.script_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Split.scriptText_FIELDNAME));
break;
default:
break;
}
StringBuilder sb = new StringBuilder();
try {
sb.append("(function(){").append(System.lineSeparator());
if (StringUtils.isNotEmpty(scriptName)) {
List<Script> list = listScriptNestedWithApplicationWithUniqueName(applicationId, scriptName);
for (Script script : list) {
sb.append(script.getText()).append(System.lineSeparator());
}
}
if (StringUtils.isNotEmpty(scriptText)) {
sb.append(scriptText).append(System.lineSeparator());
}
sb.append("}).apply(bind);");
compiledScript = ScriptFactory.compile(sb.toString());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
} catch (Exception e) {
logger.error(e);
}
}
return compiledScript;
}
public CompiledScript getCompiledScript(String applicationId, Route o, String event) throws Exception {
CacheCategory cacheCategory = new CacheCategory(Route.class);
CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
CompiledScript compiledScript = null;
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
String scriptName = null;
String scriptText = null;
switch (event) {
case Business.EVENT_ROUTEAPPENDTASKIDENTITY:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Route.appendTaskIdentityScript_FIELDNAME));
scriptText = Objects
.toString(PropertyUtils.getProperty(o, Route.appendTaskIdentityScriptText_FIELDNAME));
break;
case Business.EVENT_ROUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Route.script_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Route.scriptText_FIELDNAME));
break;
default:
break;
}
StringBuilder sb = new StringBuilder();
try {
sb.append("(function(){").append(System.lineSeparator());
if (StringUtils.isNotEmpty(scriptName)) {
List<Script> list = listScriptNestedWithApplicationWithUniqueName(applicationId, scriptName);
for (Script script : list) {
sb.append(script.getText()).append(System.lineSeparator());
}
}
if (StringUtils.isNotEmpty(scriptText)) {
sb.append(scriptText).append(System.lineSeparator());
}
sb.append("}).apply(bind);");
compiledScript = ScriptFactory.compile(sb.toString());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
} catch (Exception e) {
logger.error(e);
}
}
return compiledScript;
}
public CompiledScript getCompiledScript(String applicationId, Process o, String event) throws Exception {
CacheCategory cacheCategory = new CacheCategory(Process.class);
CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
CompiledScript compiledScript = null;
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
String scriptName = null;
String scriptText = null;
switch (event) {
case Business.EVENT_BEFOREARRIVE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeArriveScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeArriveScriptText_FIELDNAME));
break;
case Business.EVENT_AFTERARRIVE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterArriveScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterArriveScriptText_FIELDNAME));
break;
case Business.EVENT_BEFOREEXECUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeExecuteScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeExecuteScriptText_FIELDNAME));
break;
case Business.EVENT_AFTEREXECUTE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterExecuteScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterExecuteScriptText_FIELDNAME));
break;
case Business.EVENT_BEFOREINQUIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeInquireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeInquireScriptText_FIELDNAME));
break;
case Business.EVENT_AFTERINQUIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterInquireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterInquireScriptText_FIELDNAME));
break;
case Business.EVENT_PROCESSAFTERBEGIN:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterBeginScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterBeginScriptText_FIELDNAME));
break;
case Business.EVENT_PROCESSAFTEREND:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterEndScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterEndScriptText_FIELDNAME));
break;
case Business.EVENT_PROCESSEXPIRE:
scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.expireScript_FIELDNAME));
scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.expireScriptText_FIELDNAME));
break;
default:
break;
}
StringBuilder sb = new StringBuilder();
try {
sb.append("(function(){").append(System.lineSeparator());
if (StringUtils.isNotEmpty(scriptName)) {
List<Script> list = listScriptNestedWithApplicationWithUniqueName(applicationId, scriptName);
for (Script script : list) {
sb.append(script.getText()).append(System.lineSeparator());
}
}
if (StringUtils.isNotEmpty(scriptText)) {
sb.append(scriptText).append(System.lineSeparator());
}
sb.append("}).apply(bind);");
compiledScript = ScriptFactory.compile(sb.toString());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
} catch (Exception e) {
logger.error(e);
}
}
return compiledScript;
}
public CompiledScript getCompiledScript(Activity activity, String event, String name, String code) {
CacheCategory cacheCategory = new CacheCategory(activity.getClass());
CacheKey cacheKey = new CacheKey("getCompiledScript", activity.getId(), event, name, code);
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
CompiledScript compiledScript = null;
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
StringBuilder sb = new StringBuilder();
try {
sb.append("(function(){").append(System.lineSeparator());
if (StringUtils.isNotEmpty(code)) {
sb.append(code).append(System.lineSeparator());
}
sb.append("}).apply(bind);");
compiledScript = ScriptFactory.compile(sb.toString());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
} catch (Exception e) {
logger.error(e);
}
}
return compiledScript;
}
}
| 修复流程中引入脚本在脚本更新后缓存为更新的问题
| o2server/x_processplatform_service_processing/src/main/java/com/x/processplatform/service/processing/factory/ElementFactory.java | 修复流程中引入脚本在脚本更新后缓存为更新的问题 | <ide><path>2server/x_processplatform_service_processing/src/main/java/com/x/processplatform/service/processing/factory/ElementFactory.java
<ide>
<ide> public Activity get(String id, ActivityType activityType) throws Exception {
<ide> switch (activityType) {
<del> case agent:
<del> return this.get(id, Agent.class);
<del> case begin:
<del> return this.get(id, Begin.class);
<del> case cancel:
<del> return this.get(id, Cancel.class);
<del> case choice:
<del> return this.get(id, Choice.class);
<del> case delay:
<del> return this.get(id, Delay.class);
<del> case embed:
<del> return this.get(id, Embed.class);
<del> case end:
<del> return this.get(id, End.class);
<del> case invoke:
<del> return this.get(id, Invoke.class);
<del> case manual:
<del> return this.get(id, Manual.class);
<del> case merge:
<del> return this.get(id, Merge.class);
<del> case message:
<del> return this.get(id, Message.class);
<del> case parallel:
<del> return this.get(id, Parallel.class);
<del> case service:
<del> return this.get(id, Service.class);
<del> case split:
<del> return this.get(id, Split.class);
<del> default:
<del> return null;
<add> case agent:
<add> return this.get(id, Agent.class);
<add> case begin:
<add> return this.get(id, Begin.class);
<add> case cancel:
<add> return this.get(id, Cancel.class);
<add> case choice:
<add> return this.get(id, Choice.class);
<add> case delay:
<add> return this.get(id, Delay.class);
<add> case embed:
<add> return this.get(id, Embed.class);
<add> case end:
<add> return this.get(id, End.class);
<add> case invoke:
<add> return this.get(id, Invoke.class);
<add> case manual:
<add> return this.get(id, Manual.class);
<add> case merge:
<add> return this.get(id, Merge.class);
<add> case message:
<add> return this.get(id, Message.class);
<add> case parallel:
<add> return this.get(id, Parallel.class);
<add> case service:
<add> return this.get(id, Service.class);
<add> case split:
<add> return this.get(id, Split.class);
<add> default:
<add> return null;
<ide> }
<ide> }
<ide>
<ide> public List<Route> listRouteWithActvity(String id, ActivityType activityType) throws Exception {
<ide> List<Route> list = new ArrayList<>();
<ide> switch (activityType) {
<del> case agent:
<del> Agent agent = this.get(id, Agent.class);
<del> list.add(this.get(agent.getRoute(), Route.class));
<del> break;
<del> case begin:
<del> Begin begin = this.get(id, Begin.class);
<del> list.add(this.get(begin.getRoute(), Route.class));
<del> break;
<del> case cancel:
<del> break;
<del> case choice:
<del> Choice choice = this.get(id, Choice.class);
<del> for (String str : choice.getRouteList()) {
<del> list.add(this.get(str, Route.class));
<del> }
<del> break;
<del> case delay:
<del> Delay delay = this.get(id, Delay.class);
<del> list.add(this.get(delay.getRoute(), Route.class));
<del> break;
<del> case embed:
<del> Embed embed = this.get(id, Embed.class);
<del> list.add(this.get(embed.getRoute(), Route.class));
<del> break;
<del> case end:
<del> break;
<del> case invoke:
<del> Invoke invoke = this.get(id, Invoke.class);
<del> list.add(this.get(invoke.getRoute(), Route.class));
<del> break;
<del> case manual:
<del> Manual manual = this.get(id, Manual.class);
<del> for (String str : manual.getRouteList()) {
<del> list.add(this.get(str, Route.class));
<del> }
<del> break;
<del> case merge:
<del> Merge merge = this.get(id, Merge.class);
<del> list.add(this.get(merge.getRoute(), Route.class));
<del> break;
<del> case message:
<del> Message message = this.get(id, Message.class);
<del> list.add(this.get(message.getRoute(), Route.class));
<del> break;
<del> case parallel:
<del> Parallel parallel = this.get(id, Parallel.class);
<del> for (String str : parallel.getRouteList()) {
<del> list.add(this.get(str, Route.class));
<del> }
<del> break;
<del> case service:
<del> Service service = this.get(id, Service.class);
<del> list.add(this.get(service.getRoute(), Route.class));
<del> break;
<del> case split:
<del> Split split = this.get(id, Split.class);
<del> list.add(this.get(split.getRoute(), Route.class));
<del> break;
<del> default:
<del> break;
<add> case agent:
<add> Agent agent = this.get(id, Agent.class);
<add> list.add(this.get(agent.getRoute(), Route.class));
<add> break;
<add> case begin:
<add> Begin begin = this.get(id, Begin.class);
<add> list.add(this.get(begin.getRoute(), Route.class));
<add> break;
<add> case cancel:
<add> break;
<add> case choice:
<add> Choice choice = this.get(id, Choice.class);
<add> for (String str : choice.getRouteList()) {
<add> list.add(this.get(str, Route.class));
<add> }
<add> break;
<add> case delay:
<add> Delay delay = this.get(id, Delay.class);
<add> list.add(this.get(delay.getRoute(), Route.class));
<add> break;
<add> case embed:
<add> Embed embed = this.get(id, Embed.class);
<add> list.add(this.get(embed.getRoute(), Route.class));
<add> break;
<add> case end:
<add> break;
<add> case invoke:
<add> Invoke invoke = this.get(id, Invoke.class);
<add> list.add(this.get(invoke.getRoute(), Route.class));
<add> break;
<add> case manual:
<add> Manual manual = this.get(id, Manual.class);
<add> for (String str : manual.getRouteList()) {
<add> list.add(this.get(str, Route.class));
<add> }
<add> break;
<add> case merge:
<add> Merge merge = this.get(id, Merge.class);
<add> list.add(this.get(merge.getRoute(), Route.class));
<add> break;
<add> case message:
<add> Message message = this.get(id, Message.class);
<add> list.add(this.get(message.getRoute(), Route.class));
<add> break;
<add> case parallel:
<add> Parallel parallel = this.get(id, Parallel.class);
<add> for (String str : parallel.getRouteList()) {
<add> list.add(this.get(str, Route.class));
<add> }
<add> break;
<add> case service:
<add> Service service = this.get(id, Service.class);
<add> list.add(this.get(service.getRoute(), Route.class));
<add> break;
<add> case split:
<add> Split split = this.get(id, Split.class);
<add> list.add(this.get(split.getRoute(), Route.class));
<add> break;
<add> default:
<add> break;
<ide> }
<ide> return ListTools.trim(list, true, true);
<ide> }
<ide> }
<ide>
<ide> public CompiledScript getCompiledScript(String applicationId, Activity o, String event) throws Exception {
<del> CacheCategory cacheCategory = new CacheCategory(o.getClass());
<add> CacheCategory cacheCategory = new CacheCategory(o.getClass(), Script.class);
<ide> CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
<ide> Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
<ide> CompiledScript compiledScript = null;
<ide> String scriptName = null;
<ide> String scriptText = null;
<ide> switch (event) {
<del> case Business.EVENT_BEFOREARRIVE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeArriveScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeArriveScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_AFTERARRIVE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterArriveScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterArriveScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_BEFOREEXECUTE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeExecuteScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeExecuteScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_AFTEREXECUTE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterExecuteScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterExecuteScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_BEFOREINQUIRE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeInquireScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeInquireScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_AFTERINQUIRE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterInquireScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterInquireScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_MANUALTASKEXPIRE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.taskExpireScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.taskExpireScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_MANUALTASK:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.taskScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.taskScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_MANUALSTAY:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualStayScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.manualStayScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_MANUALBEFORETASK:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualBeforeTaskScript_FIELDNAME));
<del> scriptText = Objects
<del> .toString(PropertyUtils.getProperty(o, Manual.manualBeforeTaskScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_MANUALAFTERTASK:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualAfterTaskScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.manualAfterTaskScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_INVOKEJAXWSPARAMETER:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsParameterScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsParameterScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_INVOKEJAXRSPARAMETER:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsParameterScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsParameterScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_INVOKEJAXWSRESPONSE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsResponseScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsResponseScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_INVOKEJAXRSRESPONSE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsResponseScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsResponseScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_INVOKEJAXRSBODY:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsBodyScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsBodyScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_INVOKEJAXRSHEAD:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsHeadScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsHeadScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_READ:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.readScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.readScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_REVIEW:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.reviewScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.reviewScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_AGENT:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Agent.script_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Agent.scriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_SERVICE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Service.script_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Service.scriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_AGENTINTERRUPT:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Agent.agentInterruptScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Agent.agentInterruptScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_DELAY:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Delay.delayScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Delay.delayScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_EMBEDTARGETASSIGNDATA:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetAssginDataScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetAssginDataScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_EMBEDTARGETIDENTITY:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetIdentityScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetIdentityScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_EMBEDTARGETTITLE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetTitleScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetTitleScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_SPLIT:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Split.script_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Split.scriptText_FIELDNAME));
<del> break;
<del> default:
<del> break;
<add> case Business.EVENT_BEFOREARRIVE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeArriveScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeArriveScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_AFTERARRIVE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterArriveScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterArriveScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_BEFOREEXECUTE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeExecuteScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeExecuteScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_AFTEREXECUTE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterExecuteScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterExecuteScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_BEFOREINQUIRE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeInquireScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.beforeInquireScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_AFTERINQUIRE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.afterInquireScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.afterInquireScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_MANUALTASKEXPIRE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.taskExpireScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.taskExpireScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_MANUALTASK:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.taskScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.taskScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_MANUALSTAY:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualStayScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.manualStayScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_MANUALBEFORETASK:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualBeforeTaskScript_FIELDNAME));
<add> scriptText = Objects
<add> .toString(PropertyUtils.getProperty(o, Manual.manualBeforeTaskScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_MANUALAFTERTASK:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.manualAfterTaskScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.manualAfterTaskScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_INVOKEJAXWSPARAMETER:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsParameterScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsParameterScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_INVOKEJAXRSPARAMETER:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsParameterScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsParameterScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_INVOKEJAXWSRESPONSE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsResponseScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxwsResponseScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_INVOKEJAXRSRESPONSE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsResponseScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsResponseScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_INVOKEJAXRSBODY:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsBodyScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsBodyScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_INVOKEJAXRSHEAD:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsHeadScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Invoke.jaxrsHeadScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_READ:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.readScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.readScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_REVIEW:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Manual.reviewScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Manual.reviewScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_AGENT:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Agent.script_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Agent.scriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_SERVICE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Service.script_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Service.scriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_AGENTINTERRUPT:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Agent.agentInterruptScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Agent.agentInterruptScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_DELAY:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Delay.delayScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Delay.delayScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_EMBEDTARGETASSIGNDATA:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetAssginDataScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetAssginDataScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_EMBEDTARGETIDENTITY:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetIdentityScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetIdentityScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_EMBEDTARGETTITLE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Embed.targetTitleScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Embed.targetTitleScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_SPLIT:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Split.script_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Split.scriptText_FIELDNAME));
<add> break;
<add> default:
<add> break;
<ide> }
<ide> StringBuilder sb = new StringBuilder();
<ide> try {
<ide> }
<ide>
<ide> public CompiledScript getCompiledScript(String applicationId, Route o, String event) throws Exception {
<del> CacheCategory cacheCategory = new CacheCategory(Route.class);
<add> CacheCategory cacheCategory = new CacheCategory(Route.class, Script.class);
<ide> CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
<ide> Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
<ide> CompiledScript compiledScript = null;
<ide> String scriptName = null;
<ide> String scriptText = null;
<ide> switch (event) {
<del> case Business.EVENT_ROUTEAPPENDTASKIDENTITY:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Route.appendTaskIdentityScript_FIELDNAME));
<del> scriptText = Objects
<del> .toString(PropertyUtils.getProperty(o, Route.appendTaskIdentityScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_ROUTE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Route.script_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Route.scriptText_FIELDNAME));
<del> break;
<del> default:
<del> break;
<add> case Business.EVENT_ROUTEAPPENDTASKIDENTITY:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Route.appendTaskIdentityScript_FIELDNAME));
<add> scriptText = Objects
<add> .toString(PropertyUtils.getProperty(o, Route.appendTaskIdentityScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_ROUTE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Route.script_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Route.scriptText_FIELDNAME));
<add> break;
<add> default:
<add> break;
<ide> }
<ide> StringBuilder sb = new StringBuilder();
<ide> try {
<ide> }
<ide>
<ide> public CompiledScript getCompiledScript(String applicationId, Process o, String event) throws Exception {
<del> CacheCategory cacheCategory = new CacheCategory(Process.class);
<add> CacheCategory cacheCategory = new CacheCategory(Process.class, Script.class);
<ide> CacheKey cacheKey = new CacheKey("getCompiledScript", applicationId, o.getId(), event);
<ide> Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
<ide> CompiledScript compiledScript = null;
<ide> String scriptName = null;
<ide> String scriptText = null;
<ide> switch (event) {
<del> case Business.EVENT_BEFOREARRIVE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeArriveScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeArriveScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_AFTERARRIVE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterArriveScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterArriveScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_BEFOREEXECUTE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeExecuteScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeExecuteScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_AFTEREXECUTE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterExecuteScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterExecuteScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_BEFOREINQUIRE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeInquireScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeInquireScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_AFTERINQUIRE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterInquireScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterInquireScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_PROCESSAFTERBEGIN:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterBeginScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterBeginScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_PROCESSAFTEREND:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterEndScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterEndScriptText_FIELDNAME));
<del> break;
<del> case Business.EVENT_PROCESSEXPIRE:
<del> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.expireScript_FIELDNAME));
<del> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.expireScriptText_FIELDNAME));
<del> break;
<del> default:
<del> break;
<add> case Business.EVENT_BEFOREARRIVE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeArriveScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeArriveScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_AFTERARRIVE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterArriveScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterArriveScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_BEFOREEXECUTE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeExecuteScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeExecuteScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_AFTEREXECUTE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterExecuteScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterExecuteScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_BEFOREINQUIRE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.beforeInquireScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.beforeInquireScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_AFTERINQUIRE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterInquireScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterInquireScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_PROCESSAFTERBEGIN:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterBeginScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterBeginScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_PROCESSAFTEREND:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.afterEndScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.afterEndScriptText_FIELDNAME));
<add> break;
<add> case Business.EVENT_PROCESSEXPIRE:
<add> scriptName = Objects.toString(PropertyUtils.getProperty(o, Process.expireScript_FIELDNAME));
<add> scriptText = Objects.toString(PropertyUtils.getProperty(o, Process.expireScriptText_FIELDNAME));
<add> break;
<add> default:
<add> break;
<ide> }
<ide> StringBuilder sb = new StringBuilder();
<ide> try {
<ide> }
<ide>
<ide> public CompiledScript getCompiledScript(Activity activity, String event, String name, String code) {
<del> CacheCategory cacheCategory = new CacheCategory(activity.getClass());
<add> CacheCategory cacheCategory = new CacheCategory(activity.getClass(), Script.class);
<ide> CacheKey cacheKey = new CacheKey("getCompiledScript", activity.getId(), event, name, code);
<ide> Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
<ide> CompiledScript compiledScript = null; |
|
Java | apache-2.0 | 8a46006bb1354b2971d1a23ed8b3b192029d3080 | 0 | googleinterns/step1-2020,googleinterns/step1-2020 | package com.google.step.snippet.external;
import com.google.step.snippet.data.Card;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public final class StackOverflowClient implements Client {
private static final String SEARCH_URL_TEMPLATE =
"https://api.stackexchange.com/2.2/questions/%s?"
+ "order=desc&sort=activity&site=stackoverflow";
private static final String QUESTION_URL_TEMPLATE =
"https://api.stackexchange.com/2.2/questions/%s/answers?"
+ "order=desc&sort=votes&site=stackoverflow";
// This URL specifies a custom StackExchange API filter that generates answer body.
private static final String ANSWER_URL_TEMPLATE =
"https://api.stackexchange.com/2.2/answers/%s?order"
+ "=desc&sort=activity&site=stackoverflow&filter=!9_bDE(fI5";
// The URL is in the pattern of stackoverlow.com/questions/question_id/title.
// The ID_INDEX help retrieve the question_id from parsed URL.
private static final int ID_INDEX = 2;
private static final String ITEM_PARAMETER = "items";
private static final String TITLE_PARAMETER = "title";
private static final String BODY_PARAMETER = "body";
private static final String CODE_PARAMETER = "code";
private static final String ANSWER_ID_PARAMETER = "answer_id";
// Set 200 to be the maximum length of description for MVP.
private static final int MAX_DESCRIPTION_LENGTH = 200;
private final String cseId;
public StackOverflowClient(String cseId) {
this.cseId = cseId;
}
@Override
public String getCseId() {
return cseId;
}
/**
* Creates and returns a {@code Card} for the given StackOverflow URL.
*
* @param url the URL of the StackOverflow question to create the card for
* @return the created card, or {@code null} if a card could not be created
*/
@Override
public Card search(String url) {
String questionId = getQuestionId(url);
if (questionId == null) {
return null;
}
String answerId = getAnswerId(questionId);
if (answerId == null) {
return null;
}
String title = getTitle(questionId);
String answerBody = getAnswerBody(answerId);
if (title == null || answerBody == null) {
return null;
}
// No description or code is allowed for StackOverflow.
String description = getDescription(answerBody);
String code = getCode(answerBody);
return new Card(title, code, url, description);
}
/* Get the question id of passed in URL. */
private String getQuestionId(String url) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
return null;
}
// Parse the URL to get the question id.
String[] segments = uri.getPath().split("/");
String questionId = segments[ID_INDEX];
if (!Pattern.matches("[0-9]+", questionId)) {
return null;
}
return questionId;
}
/* Return the most voted answer's id. */
private String getAnswerId(String questionId) {
String questionUrl = String.format(QUESTION_URL_TEMPLATE, questionId);
return getResponse(questionUrl, ANSWER_ID_PARAMETER);
}
/* Return the question title using question id */
private String getTitle(String questionId) {
String searchUrl = String.format(SEARCH_URL_TEMPLATE, questionId);
return getResponse(searchUrl, TITLE_PARAMETER);
}
/* Get the content of the answer and store it in the card. */
private String getAnswerBody(String answerId) {
String answerUrl = String.format(ANSWER_URL_TEMPLATE, answerId);
return getResponse(answerUrl, BODY_PARAMETER);
}
/* Return the description parsed from answer body. */
private String getDescription(String body) {
Document doc = Jsoup.parse(body);
// Combine all description in the answer body.
Elements descriptionHtml = doc.select("p");
String description = "";
for (Element e : descriptionHtml) {
description += e.outerHtml();
if (description.length() >= MAX_DESCRIPTION_LENGTH) {
description = description.substring(0, MAX_DESCRIPTION_LENGTH);
break;
}
}
return description;
}
/* Return the code parsed from answer body. */
private String getCode(String body) {
Document doc = Jsoup.parse(body);
// Combine all code in the answer body.
Elements codeHtml = doc.select(CODE_PARAMETER);
String code = "";
for (Element e : codeHtml) {
code += e.outerHtml();
}
return code;
}
private String getResponse(String url, String fieldParam) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response;
try {
response = httpClient.execute(new HttpGet(url));
} catch (IOException e) {
return null;
}
if (response.getStatusLine().getStatusCode() != 200) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
} catch (IOException e) {
return null;
}
StringBuilder responseBody = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
responseBody.append(line);
}
reader.close();
} catch (IOException e) {
return null;
}
JSONObject json = new JSONObject(responseBody.toString());
if(json.has(ITEM_PARAMETER) && json.getJSONArray(ITEM_PARAMETER).length() > 0) {
JSONArray items = json.getJSONArray(ITEM_PARAMETER);
JSONObject obj = items.getJSONObject(0);
if(obj.has(fieldParam)) {
String result = obj.get(fieldParam).toString();
return result;
}
}
return null;
}
}
| src/main/java/com/google/step/snippet/external/StackOverflowClient.java | package com.google.step.snippet.external;
import com.google.step.snippet.data.Card;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public final class StackOverflowClient implements Client {
private static final String SEARCH_URL_TEMPLATE =
"https://api.stackexchange.com/2.2/questions/%s?"
+ "order=desc&sort=activity&site=stackoverflow";
private static final String QUESTION_URL_TEMPLATE =
"https://api.stackexchange.com/2.2/questions/%s/answers?"
+ "order=desc&sort=votes&site=stackoverflow";
// This URL specifies a custom StackExchange API filter that generates answer body.
private static final String ANSWER_URL_TEMPLATE =
"https://api.stackexchange.com/2.2/answers/%s?order"
+ "=desc&sort=activity&site=stackoverflow&filter=!9_bDE(fI5";
// The URL is in the pattern of stackoverlow.com/questions/question_id/title.
// The ID_INDEX help retrieve the question_id from parsed URL.
private static final int ID_INDEX = 2;
private static final String ITEM_PARAMETER = "items";
private static final String TITLE_PARAMETER = "title";
private static final String BODY_PARAMETER = "body";
private static final String CODE_PARAMETER = "code";
private static final String ANSWER_ID_PARAMETER = "answer_id";
// Set 200 to be the maximum length of description for MVP.
private static final int MAX_DESCRIPTION_LENGTH = 200;
private final String cseId;
public StackOverflowClient(String cseId) {
this.cseId = cseId;
}
@Override
public String getCseId() {
return cseId;
}
/**
* Creates and returns a {@code Card} for the given StackOverflow URL.
*
* @param url the URL of the StackOverflow question to create the card for
* @return the created card, or {@code null} if a card could not be created
*/
@Override
public Card search(String url) {
String questionId = getQuestionId(url);
if (questionId == null) {
return null;
}
String answerId = getAnswerId(questionId);
if (answerId == null) {
return null;
}
String title = getTitle(questionId);
String answerBody = getAnswerBody(answerId);
if (title == null || answerBody == null) {
return null;
}
// No description or code is allowed for StackOverflow.
String description = getDescription(answerBody);
String code = getCode(answerBody);
return new Card(title, code, url, description);
}
/* Get the question id of passed in URL. */
private String getQuestionId(String url) {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
return null;
}
// Parse the URL to get the question id.
String[] segments = uri.getPath().split("/");
String questionId = segments[ID_INDEX];
if (!Pattern.matches("[0-9]+", questionId)) {
return null;
}
return questionId;
}
/* Return the most voted answer's id. */
private String getAnswerId(String questionId) {
String questionUrl = String.format(QUESTION_URL_TEMPLATE, questionId);
return getResponse(questionUrl, ANSWER_ID_PARAMETER);
}
/* Return the question title using question id */
private String getTitle(String questionId) {
String searchUrl = String.format(SEARCH_URL_TEMPLATE, questionId);
return getResponse(searchUrl, TITLE_PARAMETER);
}
/* Get the content of the answer and store it in the card. */
private String getAnswerBody(String answerId) {
String answerUrl = String.format(ANSWER_URL_TEMPLATE, answerId);
return getResponse(answerUrl, BODY_PARAMETER);
}
/* Return the description parsed from answer body. */
private String getDescription(String body) {
Document doc = Jsoup.parse(body);
// Combine all description in the answer body.
Elements descriptionHtml = doc.select("p");
String description = "";
for (Element e : descriptionHtml) {
description += e.outerHtml();
if (description.length() >= MAX_DESCRIPTION_LENGTH) {
description = description.substring(0, MAX_DESCRIPTION_LENGTH);
break;
}
}
return description;
}
/* Return the code parsed from answer body. */
private String getCode(String body) {
Document doc = Jsoup.parse(body);
// Combine all code in the answer body.
Elements codeHtml = doc.select(CODE_PARAMETER);
String code = "";
for (Element e : codeHtml) {
code += e.outerHtml();
}
return code;
}
private String getResponse(String url, String fieldParam) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response;
try {
response = httpClient.execute(new HttpGet(url));
} catch (IOException e) {
return null;
}
if (response.getStatusLine().getStatusCode() != 200) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(entity.getContent()));
} catch (IOException e) {
return null;
}
StringBuilder responseBody = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
responseBody.append(line);
}
reader.close();
} catch (IOException e) {
return null;
}
JSONObject json = new JSONObject(responseBody.toString());
JSONArray items = json.getJSONArray(ITEM_PARAMETER);
if (items == null || items.length() == 0) {
return null;
}
String result = items.getJSONObject(0).get(fieldParam).toString();
if (response.getStatusLine().getStatusCode() != 200) {
return null;
}
return result;
}
}
| change code for getting items
| src/main/java/com/google/step/snippet/external/StackOverflowClient.java | change code for getting items | <ide><path>rc/main/java/com/google/step/snippet/external/StackOverflowClient.java
<ide> return null;
<ide> }
<ide> JSONObject json = new JSONObject(responseBody.toString());
<del> JSONArray items = json.getJSONArray(ITEM_PARAMETER);
<del> if (items == null || items.length() == 0) {
<del> return null;
<add> if(json.has(ITEM_PARAMETER) && json.getJSONArray(ITEM_PARAMETER).length() > 0) {
<add> JSONArray items = json.getJSONArray(ITEM_PARAMETER);
<add> JSONObject obj = items.getJSONObject(0);
<add> if(obj.has(fieldParam)) {
<add> String result = obj.get(fieldParam).toString();
<add> return result;
<add> }
<ide> }
<del> String result = items.getJSONObject(0).get(fieldParam).toString();
<del> if (response.getStatusLine().getStatusCode() != 200) {
<del> return null;
<del> }
<del> return result;
<add> return null;
<ide> }
<ide> } |
|
Java | bsd-3-clause | 2fdab693dced76c4d76add2444dc90724b2062e0 | 0 | mosauter/Battleship | // CollisionOrientationFirstTrueTest.java
package de.htwg.battleship.controller.impl;
import de.htwg.battleship.model.IShip;
import de.htwg.battleship.model.impl.Ship;
import de.htwg.battleship.util.StatCollection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.Before;
import org.junit.Test;
/**
* CollisionOrientationFirstTrueTest tests an implementation of the chain.
* @author Moritz Sauter ([email protected])
* @version 1.00
* @since 2014-12-04
*/
public class CollisionOrientationFirstTrueTest {
/**
* Saves the implementation.
*/
private CollisionOrientationFirstTrue cc;
/**
* Saves the first ship.
*/
private IShip ship1;
/**
* Saves the second ship.
*/
private IShip ship2;
/**
* Saves the third ship.
*/
private IShip ship3;
/**
* Set-Up.
*/
@Before
public final void setUp() {
StatCollection.heightLenght = 10;
StatCollection.shipNumberMax = 5;
cc = new CollisionOrientationFirstTrue();
ship1 = new Ship(2, true, 4, 4);
ship2 = new Ship(3, false, 4, 5);
ship3 = new Ship(3, false, 5, 4);
}
/**
* Test of isCollision method, of class CollisionOrientationFirstTrue.
*/
@Test
public final void testIsCollision() {
boolean expRes = false;
boolean result = cc.isCollision(ship1, ship2);
assertEquals(expRes, result);
expRes = true;
result = cc.isCollision(ship1, ship3);
assertEquals(expRes, result);
}
@Test
public final void testIsCollisionFalse() {
Ship sh = new Ship(1, false, -1, 4);
assertFalse(cc.isCollision(ship1, sh));
}
} | Battleship/src/test/java/de/htwg/battleship/controller/impl/CollisionOrientationFirstTrueTest.java | // CollisionOrientationFirstTrueTest.java
package de.htwg.battleship.controller.impl;
import de.htwg.battleship.model.IShip;
import de.htwg.battleship.model.impl.Ship;
import de.htwg.battleship.util.StatCollection;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
/**
* CollisionOrientationFirstTrueTest tests an implementation of the chain.
* @author Moritz Sauter ([email protected])
* @version 1.00
* @since 2014-12-04
*/
public class CollisionOrientationFirstTrueTest {
/**
* Saves the implementation.
*/
private CollisionOrientationFirstTrue cc;
/**
* Saves the first ship.
*/
private IShip ship1;
/**
* Saves the second ship.
*/
private IShip ship2;
/**
* Saves the third ship.
*/
private IShip ship3;
/**
* Set-Up.
*/
@Before
public final void setUp() {
StatCollection.heightLenght = 10;
StatCollection.shipNumberMax = 5;
cc = new CollisionOrientationFirstTrue();
ship1 = new Ship(2, true, 4, 4);
ship2 = new Ship(3, false, 4, 5);
ship3 = new Ship(3, false, 5, 4);
}
/**
* Test of isCollision method, of class CollisionOrientationFirstTrue.
*/
@Test
public final void testIsCollision() {
boolean expRes = false;
boolean result = cc.isCollision(ship1, ship2);
assertEquals(expRes, result);
expRes = true;
result = cc.isCollision(ship1, ship3);
assertEquals(expRes, result);
}
} | pushed to full branch coverage | Battleship/src/test/java/de/htwg/battleship/controller/impl/CollisionOrientationFirstTrueTest.java | pushed to full branch coverage | <ide><path>attleship/src/test/java/de/htwg/battleship/controller/impl/CollisionOrientationFirstTrueTest.java
<ide> import de.htwg.battleship.model.impl.Ship;
<ide> import de.htwg.battleship.util.StatCollection;
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertFalse;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<ide> result = cc.isCollision(ship1, ship3);
<ide> assertEquals(expRes, result);
<ide> }
<add>
<add> @Test
<add> public final void testIsCollisionFalse() {
<add> Ship sh = new Ship(1, false, -1, 4);
<add> assertFalse(cc.isCollision(ship1, sh));
<add> }
<ide> } |
|
Java | apache-2.0 | 8115c6154d69edf4bb70176d61445b63250417c2 | 0 | alter-ego/Swipeable-Cards | package com.andtinder.view;
import com.andtinder.R;
import com.andtinder.model.BaseCardModel;
import com.andtinder.model.Orientations.Orientation;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import java.util.Random;
public class CardContainer extends AdapterView<CardStackAdapter> {
public static final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
private static final double DISORDERED_MAX_ROTATION_RADIANS = Math.PI / 64;
private static final int MAX_VISIBLE_CARDS_DEFAULT = 5;
private int mNumberOfCards = -1;
private final DataSetObserver mDataSetObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
clearStack();
ensureFull();
}
@Override
public void onInvalidated() {
super.onInvalidated();
clearStack();
}
};
private final Random mRandom = new Random();
private final Rect boundsRect = new Rect();
private final Rect childRect = new Rect();
private final Matrix mMatrix = new Matrix();
//TODO: determine max dynamically based on device speed
private int mMaxVisible = MAX_VISIBLE_CARDS_DEFAULT;
private GestureDetector mGestureDetector;
private int mFlingSlop;
private Orientation mOrientation;
private CardStackAdapter mListAdapter;
private float mLastTouchX;
private float mLastTouchY;
private View mTopCard;
private int mTouchSlop;
private int mGravity;
private int mNextAdapterPosition;
private boolean mDragging;
private int mChildWidth;
private int mChildHeight;
public CardContainer(Context context) {
super(context);
setOrientation(Orientation.Disordered);
setGravity(Gravity.CENTER);
init();
}
public CardContainer(Context context, AttributeSet attrs) {
super(context, attrs);
initFromXml(attrs);
init();
}
public CardContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initFromXml(attrs);
init();
}
private void init() {
ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());
mFlingSlop = viewConfiguration.getScaledMinimumFlingVelocity();
mTouchSlop = viewConfiguration.getScaledTouchSlop();
mGestureDetector = new GestureDetector(getContext(), new GestureListener());
}
private void initFromXml(AttributeSet attr) {
TypedArray a = getContext().obtainStyledAttributes(attr,
R.styleable.CardContainer);
setGravity(a.getInteger(R.styleable.CardContainer_android_gravity, Gravity.CENTER));
int orientation = a.getInteger(R.styleable.CardContainer_orientation, 1);
setOrientation(Orientation.fromIndex(orientation));
a.recycle();
}
@Override
public CardStackAdapter getAdapter() {
return mListAdapter;
}
@Override
public void setAdapter(CardStackAdapter adapter) {
if (mListAdapter != null) {
mListAdapter.unregisterDataSetObserver(mDataSetObserver);
}
clearStack();
mListAdapter = adapter;
adapter.registerDataSetObserver(mDataSetObserver);
ensureFull();
mNumberOfCards = getAdapter().getCount();
requestLayout();
}
private void ensureFull() {
while (mNextAdapterPosition < mListAdapter.getCount() && getChildCount() < mMaxVisible) {
View view = mListAdapter.getView(mNextAdapterPosition, null, this);
view.setLayerType(LAYER_TYPE_SOFTWARE, null);
if (mOrientation == Orientation.Disordered) {
view.setRotation(getDisorderedRotation());
}
addViewInLayout(view, 0, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
mListAdapter.getItemViewType(mNextAdapterPosition)), false);
requestLayout();
mNextAdapterPosition += 1;
}
if (getChildCount() != 0) {
mTopCard = getChildAt(getChildCount() - 1);
mTopCard.setLayerType(LAYER_TYPE_HARDWARE, null);
}
}
private void clearStack() {
removeAllViewsInLayout();
mNextAdapterPosition = 0;
mTopCard = null;
}
public Orientation getOrientation() {
return mOrientation;
}
public void setOrientation(Orientation orientation) {
if (orientation == null) {
throw new NullPointerException("Orientation may not be null");
}
if (mOrientation != orientation) {
this.mOrientation = orientation;
if (orientation == Orientation.Disordered) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.setRotation(getDisorderedRotation());
}
} else {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.setRotation(0);
}
}
requestLayout();
}
}
private float getDisorderedRotation() {
return (float) Math.toDegrees(mRandom.nextGaussian() * DISORDERED_MAX_ROTATION_RADIANS);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int requestedWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
int requestedHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
if (mOrientation == Orientation.Disordered) {
int R1, R2;
if (requestedWidth >= requestedHeight) {
R1 = requestedHeight;
R2 = requestedWidth;
} else {
R1 = requestedWidth;
R2 = requestedHeight;
}
mChildWidth = (int) ((R1 * Math.cos(DISORDERED_MAX_ROTATION_RADIANS) - R2 * Math.sin(DISORDERED_MAX_ROTATION_RADIANS)) / Math
.cos(2 * DISORDERED_MAX_ROTATION_RADIANS));
mChildHeight = (int) ((R2 * Math.cos(DISORDERED_MAX_ROTATION_RADIANS) - R1 * Math.sin(DISORDERED_MAX_ROTATION_RADIANS)) / Math
.cos(2 * DISORDERED_MAX_ROTATION_RADIANS));
} else {
mChildWidth = requestedWidth;
mChildHeight = requestedHeight;
}
int childWidthMeasureSpec, childHeightMeasureSpec;
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mChildWidth, MeasureSpec.AT_MOST);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mChildHeight, MeasureSpec.AT_MOST);
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
assert child != null;
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
for (int i = 0; i < getChildCount(); i++) {
boundsRect.set(0, 0, getWidth(), getHeight());
View view = getChildAt(i);
int w, h;
w = view.getMeasuredWidth();
h = view.getMeasuredHeight();
Gravity.apply(mGravity, w, h, boundsRect, childRect);
view.layout(childRect.left, childRect.top, childRect.right, childRect.bottom);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mTopCard == null) {
return false;
}
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
// Log.d("Touch Event", MotionEvent.actionToString(event.getActionMasked()) + " ");
final int pointerIndex;
final float x, y;
final float dx, dy;
Object model = getAdapter().getItem(0);
BaseCardModel baseCardModel = null;
if (model instanceof BaseCardModel) {
baseCardModel = (BaseCardModel) model;
}
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mTopCard.getHitRect(childRect);
pointerIndex = event.getActionIndex();
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (!childRect.contains((int) x, (int) y)) {
return false;
}
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = event.getPointerId(pointerIndex);
float[] points = new float[]{x - mTopCard.getLeft(), y - mTopCard.getTop()};
mTopCard.getMatrix().invert(mMatrix);
mMatrix.mapPoints(points);
mTopCard.setPivotX(points[0]);
mTopCard.setPivotY(points[1]);
break;
case MotionEvent.ACTION_MOVE:
pointerIndex = event.findPointerIndex(mActivePointerId);
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
dx = x - mLastTouchX;
dy = y - mLastTouchY;
if (Math.abs(dx) > mTouchSlop || Math.abs(dy) > mTouchSlop) {
mDragging = true;
}
if (!mDragging) {
return true;
}
mTopCard.setTranslationX(mTopCard.getTranslationX() + dx);
mTopCard.setTranslationY(mTopCard.getTranslationY() + dy);
mTopCard.setRotation(40 * mTopCard.getTranslationX() / (getWidth() / 2.f));
float currentTranslationX = mTopCard.getTranslationX();
if (baseCardModel != null && baseCardModel.getOnCardSwipeListener() != null) {
if (currentTranslationX > 0) {
baseCardModel.getOnCardSwipeListener().onSwipeStartedLike();
} else {
baseCardModel.getOnCardSwipeListener().onSwipeStartedDislike();
}
}
mLastTouchX = x;
mLastTouchY = y;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (!mDragging) {
return true;
}
mDragging = false;
mActivePointerId = INVALID_POINTER_ID;
ValueAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mTopCard,
PropertyValuesHolder.ofFloat("translationX", 0),
PropertyValuesHolder.ofFloat("translationY", 0),
PropertyValuesHolder.ofFloat("rotation", mOrientation == Orientation.Disordered ? getDisorderedRotation() : 0),
PropertyValuesHolder.ofFloat("pivotX", mTopCard.getWidth() / 2.f),
PropertyValuesHolder.ofFloat("pivotY", mTopCard.getHeight() / 2.f)
).setDuration(250);
animator.setInterpolator(new AccelerateInterpolator());
animator.start();
if (baseCardModel != null && baseCardModel.getOnCardSwipeListener() != null) {
baseCardModel.getOnCardSwipeListener().onSwipeStopped();
}
break;
case MotionEvent.ACTION_POINTER_UP:
pointerIndex = event.getActionIndex();
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = event.getX(newPointerIndex);
mLastTouchY = event.getY(newPointerIndex);
mActivePointerId = event.getPointerId(newPointerIndex);
}
break;
}
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mTopCard == null) {
return false;
}
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
final int pointerIndex;
final float x, y;
final float dx, dy;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mTopCard.getHitRect(childRect);
Object model = getAdapter().getItem(0);
if (model instanceof BaseCardModel) {
BaseCardModel baseCardModel = (BaseCardModel) model;
if (baseCardModel.getOnCardClickListener() != null) {
baseCardModel.getOnCardClickListener().OnClickListener();
}
}
pointerIndex = event.getActionIndex();
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (!childRect.contains((int) x, (int) y)) {
return false;
}
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = event.getPointerId(pointerIndex);
break;
case MotionEvent.ACTION_MOVE:
pointerIndex = event.findPointerIndex(mActivePointerId);
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (Math.abs(x - mLastTouchX) > mTouchSlop || Math.abs(y - mLastTouchY) > mTouchSlop) {
float[] points = new float[]{x - mTopCard.getLeft(), y - mTopCard.getTop()};
mTopCard.getMatrix().invert(mMatrix);
mMatrix.mapPoints(points);
mTopCard.setPivotX(points[0]);
mTopCard.setPivotY(points[1]);
return true;
}
}
return false;
}
@Override
public View getSelectedView() {
//DO NOTHING
return null;
}
@Override
public void setSelection(int position) {
//DO NOTHING
}
public int getGravity() {
return mGravity;
}
public void setGravity(int gravity) {
mGravity = gravity;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
int viewType;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(int w, int h, int viewType) {
super(w, h);
this.viewType = viewType;
}
}
private class GestureListener extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.d("Fling", "Fling with " + velocityX + ", " + velocityY);
final View topCard = mTopCard;
float dx = e2.getX() - e1.getX();
if (Math.abs(dx) > mTouchSlop &&
Math.abs(velocityX) > Math.abs(velocityY) &&
Math.abs(velocityX) > mFlingSlop * 3) {
float targetX = topCard.getX();
float targetY = topCard.getY();
long duration = 0;
boundsRect.set(0 - topCard.getWidth() - 100, 0 - topCard.getHeight() - 100, getWidth() + 100, getHeight() + 100);
while (boundsRect.contains((int) targetX, (int) targetY)) {
targetX += velocityX / 10;
targetY += velocityY / 10;
duration += 100;
}
likeOrDislike(targetX, targetY, Math.min(500, duration));
return true;
} else {
return false;
}
}
}
private void likeOrDislike(float targetX, float targetY, long duration) {
final View topCard = mTopCard;
mTopCard = getChildAt(getChildCount() - 2);
if (mTopCard != null) {
mTopCard.setLayerType(LAYER_TYPE_HARDWARE, null);
}
Object model = getAdapter().getItem(0);
if (model instanceof BaseCardModel) {
BaseCardModel baseCardModel = (BaseCardModel) model;
if (baseCardModel.getOnCardDismissedListener() != null) {
if (targetX > 0) {
baseCardModel.getOnCardDismissedListener().onLike();
} else {
baseCardModel.getOnCardDismissedListener().onDislike();
}
}
}
topCard.animate()
.setDuration(duration)
.alpha(.75f)
.setInterpolator(new LinearInterpolator())
.x(targetX)
.y(targetY)
.rotation(Math.copySign(45, targetX))
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
removeViewInLayout(topCard);
getAdapter().pop();
}
@Override
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
}
public void like() {
likeOrDislike(mChildWidth, 0, 500);
}
public void dislike() {
likeOrDislike(-mChildWidth, 0, 500);
}
public void setMaxVisible(int maxVisible) {
mMaxVisible = maxVisible;
}
}
| AndTinder/src/main/java/com/andtinder/view/CardContainer.java | package com.andtinder.view;
import com.andtinder.R;
import com.andtinder.model.BaseCardModel;
import com.andtinder.model.Orientations.Orientation;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import java.util.Random;
public class CardContainer extends AdapterView<CardStackAdapter> {
public static final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
private static final double DISORDERED_MAX_ROTATION_RADIANS = Math.PI / 64;
private static final int MAX_VISIBLE_CARDS_DEFAULT = 5;
private int mNumberOfCards = -1;
private final DataSetObserver mDataSetObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
clearStack();
ensureFull();
}
@Override
public void onInvalidated() {
super.onInvalidated();
clearStack();
}
};
private final Random mRandom = new Random();
private final Rect boundsRect = new Rect();
private final Rect childRect = new Rect();
private final Matrix mMatrix = new Matrix();
//TODO: determine max dynamically based on device speed
private int mMaxVisible = MAX_VISIBLE_CARDS_DEFAULT;
private GestureDetector mGestureDetector;
private int mFlingSlop;
private Orientation mOrientation;
private CardStackAdapter mListAdapter;
private float mLastTouchX;
private float mLastTouchY;
private View mTopCard;
private int mTouchSlop;
private int mGravity;
private int mNextAdapterPosition;
private boolean mDragging;
private int mChildWidth;
private int mChildHeight;
public CardContainer(Context context) {
super(context);
setOrientation(Orientation.Disordered);
setGravity(Gravity.CENTER);
init();
}
public CardContainer(Context context, AttributeSet attrs) {
super(context, attrs);
initFromXml(attrs);
init();
}
public CardContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initFromXml(attrs);
init();
}
private void init() {
ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext());
mFlingSlop = viewConfiguration.getScaledMinimumFlingVelocity();
mTouchSlop = viewConfiguration.getScaledTouchSlop();
mGestureDetector = new GestureDetector(getContext(), new GestureListener());
}
private void initFromXml(AttributeSet attr) {
TypedArray a = getContext().obtainStyledAttributes(attr,
R.styleable.CardContainer);
setGravity(a.getInteger(R.styleable.CardContainer_android_gravity, Gravity.CENTER));
int orientation = a.getInteger(R.styleable.CardContainer_orientation, 1);
setOrientation(Orientation.fromIndex(orientation));
a.recycle();
}
@Override
public CardStackAdapter getAdapter() {
return mListAdapter;
}
@Override
public void setAdapter(CardStackAdapter adapter) {
if (mListAdapter != null) {
mListAdapter.unregisterDataSetObserver(mDataSetObserver);
}
clearStack();
mListAdapter = adapter;
adapter.registerDataSetObserver(mDataSetObserver);
ensureFull();
mNumberOfCards = getAdapter().getCount();
requestLayout();
}
private void ensureFull() {
while (mNextAdapterPosition < mListAdapter.getCount() && getChildCount() < mMaxVisible) {
View view = mListAdapter.getView(mNextAdapterPosition, null, this);
view.setLayerType(LAYER_TYPE_SOFTWARE, null);
if (mOrientation == Orientation.Disordered) {
view.setRotation(getDisorderedRotation());
}
addViewInLayout(view, 0, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
mListAdapter.getItemViewType(mNextAdapterPosition)), false);
requestLayout();
mNextAdapterPosition += 1;
}
if (getChildCount() != 0) {
mTopCard = getChildAt(getChildCount() - 1);
mTopCard.setLayerType(LAYER_TYPE_HARDWARE, null);
}
}
private void clearStack() {
removeAllViewsInLayout();
mNextAdapterPosition = 0;
mTopCard = null;
}
public Orientation getOrientation() {
return mOrientation;
}
public void setOrientation(Orientation orientation) {
if (orientation == null) {
throw new NullPointerException("Orientation may not be null");
}
if (mOrientation != orientation) {
this.mOrientation = orientation;
if (orientation == Orientation.Disordered) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.setRotation(getDisorderedRotation());
}
} else {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.setRotation(0);
}
}
requestLayout();
}
}
private float getDisorderedRotation() {
return (float) Math.toDegrees(mRandom.nextGaussian() * DISORDERED_MAX_ROTATION_RADIANS);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int requestedWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
int requestedHeight = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
if (mOrientation == Orientation.Disordered) {
int R1, R2;
if (requestedWidth >= requestedHeight) {
R1 = requestedHeight;
R2 = requestedWidth;
} else {
R1 = requestedWidth;
R2 = requestedHeight;
}
mChildWidth = (int) ((R1 * Math.cos(DISORDERED_MAX_ROTATION_RADIANS) - R2 * Math.sin(DISORDERED_MAX_ROTATION_RADIANS)) / Math
.cos(2 * DISORDERED_MAX_ROTATION_RADIANS));
mChildHeight = (int) ((R2 * Math.cos(DISORDERED_MAX_ROTATION_RADIANS) - R1 * Math.sin(DISORDERED_MAX_ROTATION_RADIANS)) / Math
.cos(2 * DISORDERED_MAX_ROTATION_RADIANS));
} else {
mChildWidth = requestedWidth;
mChildHeight = requestedHeight;
}
int childWidthMeasureSpec, childHeightMeasureSpec;
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(mChildWidth, MeasureSpec.AT_MOST);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(mChildHeight, MeasureSpec.AT_MOST);
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
assert child != null;
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
for (int i = 0; i < getChildCount(); i++) {
boundsRect.set(0, 0, getWidth(), getHeight());
View view = getChildAt(i);
int w, h;
w = view.getMeasuredWidth();
h = view.getMeasuredHeight();
Gravity.apply(mGravity, w, h, boundsRect, childRect);
view.layout(childRect.left, childRect.top, childRect.right, childRect.bottom);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mTopCard == null) {
return false;
}
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
// Log.d("Touch Event", MotionEvent.actionToString(event.getActionMasked()) + " ");
final int pointerIndex;
final float x, y;
final float dx, dy;
Object model = getAdapter().getItem(getChildCount() - 1);
BaseCardModel baseCardModel = null;
if (model instanceof BaseCardModel) {
baseCardModel = (BaseCardModel) model;
}
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mTopCard.getHitRect(childRect);
pointerIndex = event.getActionIndex();
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (!childRect.contains((int) x, (int) y)) {
return false;
}
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = event.getPointerId(pointerIndex);
float[] points = new float[]{x - mTopCard.getLeft(), y - mTopCard.getTop()};
mTopCard.getMatrix().invert(mMatrix);
mMatrix.mapPoints(points);
mTopCard.setPivotX(points[0]);
mTopCard.setPivotY(points[1]);
break;
case MotionEvent.ACTION_MOVE:
pointerIndex = event.findPointerIndex(mActivePointerId);
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
dx = x - mLastTouchX;
dy = y - mLastTouchY;
if (Math.abs(dx) > mTouchSlop || Math.abs(dy) > mTouchSlop) {
mDragging = true;
}
if (!mDragging) {
return true;
}
mTopCard.setTranslationX(mTopCard.getTranslationX() + dx);
mTopCard.setTranslationY(mTopCard.getTranslationY() + dy);
mTopCard.setRotation(40 * mTopCard.getTranslationX() / (getWidth() / 2.f));
float currentTranslationX = mTopCard.getTranslationX();
if (baseCardModel != null && baseCardModel.getOnCardSwipeListener() != null) {
if (currentTranslationX > 0) {
baseCardModel.getOnCardSwipeListener().onSwipeStartedLike();
} else {
baseCardModel.getOnCardSwipeListener().onSwipeStartedDislike();
}
}
mLastTouchX = x;
mLastTouchY = y;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (!mDragging) {
return true;
}
mDragging = false;
mActivePointerId = INVALID_POINTER_ID;
ValueAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mTopCard,
PropertyValuesHolder.ofFloat("translationX", 0),
PropertyValuesHolder.ofFloat("translationY", 0),
PropertyValuesHolder.ofFloat("rotation", mOrientation == Orientation.Disordered ? getDisorderedRotation() : 0),
PropertyValuesHolder.ofFloat("pivotX", mTopCard.getWidth() / 2.f),
PropertyValuesHolder.ofFloat("pivotY", mTopCard.getHeight() / 2.f)
).setDuration(250);
animator.setInterpolator(new AccelerateInterpolator());
animator.start();
if (baseCardModel != null && baseCardModel.getOnCardSwipeListener() != null) {
baseCardModel.getOnCardSwipeListener().onSwipeStopped();
}
break;
case MotionEvent.ACTION_POINTER_UP:
pointerIndex = event.getActionIndex();
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastTouchX = event.getX(newPointerIndex);
mLastTouchY = event.getY(newPointerIndex);
mActivePointerId = event.getPointerId(newPointerIndex);
}
break;
}
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (mTopCard == null) {
return false;
}
if (mGestureDetector.onTouchEvent(event)) {
return true;
}
final int pointerIndex;
final float x, y;
final float dx, dy;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mTopCard.getHitRect(childRect);
Object model = getAdapter().getItem(0);
if (model instanceof BaseCardModel) {
BaseCardModel baseCardModel = (BaseCardModel) model;
if (baseCardModel.getOnCardClickListener() != null) {
baseCardModel.getOnCardClickListener().OnClickListener();
}
}
pointerIndex = event.getActionIndex();
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (!childRect.contains((int) x, (int) y)) {
return false;
}
mLastTouchX = x;
mLastTouchY = y;
mActivePointerId = event.getPointerId(pointerIndex);
break;
case MotionEvent.ACTION_MOVE:
pointerIndex = event.findPointerIndex(mActivePointerId);
x = event.getX(pointerIndex);
y = event.getY(pointerIndex);
if (Math.abs(x - mLastTouchX) > mTouchSlop || Math.abs(y - mLastTouchY) > mTouchSlop) {
float[] points = new float[]{x - mTopCard.getLeft(), y - mTopCard.getTop()};
mTopCard.getMatrix().invert(mMatrix);
mMatrix.mapPoints(points);
mTopCard.setPivotX(points[0]);
mTopCard.setPivotY(points[1]);
return true;
}
}
return false;
}
@Override
public View getSelectedView() {
//DO NOTHING
return null;
}
@Override
public void setSelection(int position) {
//DO NOTHING
}
public int getGravity() {
return mGravity;
}
public void setGravity(int gravity) {
mGravity = gravity;
}
public static class LayoutParams extends ViewGroup.LayoutParams {
int viewType;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(int w, int h, int viewType) {
super(w, h);
this.viewType = viewType;
}
}
private class GestureListener extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.d("Fling", "Fling with " + velocityX + ", " + velocityY);
final View topCard = mTopCard;
float dx = e2.getX() - e1.getX();
if (Math.abs(dx) > mTouchSlop &&
Math.abs(velocityX) > Math.abs(velocityY) &&
Math.abs(velocityX) > mFlingSlop * 3) {
float targetX = topCard.getX();
float targetY = topCard.getY();
long duration = 0;
boundsRect.set(0 - topCard.getWidth() - 100, 0 - topCard.getHeight() - 100, getWidth() + 100, getHeight() + 100);
while (boundsRect.contains((int) targetX, (int) targetY)) {
targetX += velocityX / 10;
targetY += velocityY / 10;
duration += 100;
}
likeOrDislike(targetX, targetY, Math.min(500, duration));
return true;
} else {
return false;
}
}
}
private void likeOrDislike(float targetX, float targetY, long duration) {
final View topCard = mTopCard;
mTopCard = getChildAt(getChildCount() - 2);
if (mTopCard != null) {
mTopCard.setLayerType(LAYER_TYPE_HARDWARE, null);
}
Object model = getAdapter().getItem(0);
if (model instanceof BaseCardModel) {
BaseCardModel baseCardModel = (BaseCardModel) model;
if (baseCardModel.getOnCardDismissedListener() != null) {
if (targetX > 0) {
baseCardModel.getOnCardDismissedListener().onLike();
} else {
baseCardModel.getOnCardDismissedListener().onDislike();
}
}
}
topCard.animate()
.setDuration(duration)
.alpha(.75f)
.setInterpolator(new LinearInterpolator())
.x(targetX)
.y(targetY)
.rotation(Math.copySign(45, targetX))
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
removeViewInLayout(topCard);
getAdapter().pop();
}
@Override
public void onAnimationCancel(Animator animation) {
onAnimationEnd(animation);
}
});
}
public void like() {
likeOrDislike(mChildWidth, 0, 500);
}
public void dislike() {
likeOrDislike(-mChildWidth, 0, 500);
}
public void setMaxVisible(int maxVisible) {
mMaxVisible = maxVisible;
}
}
| fixed wrong adapter item in onTouchEvent bug
| AndTinder/src/main/java/com/andtinder/view/CardContainer.java | fixed wrong adapter item in onTouchEvent bug | <ide><path>ndTinder/src/main/java/com/andtinder/view/CardContainer.java
<ide> final float x, y;
<ide> final float dx, dy;
<ide>
<del> Object model = getAdapter().getItem(getChildCount() - 1);
<add> Object model = getAdapter().getItem(0);
<ide> BaseCardModel baseCardModel = null;
<ide>
<ide> if (model instanceof BaseCardModel) { |
|
Java | epl-1.0 | error: pathspec 'applications/plugins/org.csstudio.opibuilder.adl2boy/src/org/csstudio/opibuilder/adl2boy/translator/TranslatorUtils.java' did not match any file(s) known to git
| 50064d8c342dab3ea45fe73d34bfc67615271b70 | 1 | ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio | package org.csstudio.opibuilder.adl2boy.translator;
import java.util.ArrayList;
import org.csstudio.opibuilder.model.AbstractContainerModel;
import org.csstudio.utility.adlparser.fileParser.ADLWidget;
import org.eclipse.swt.graphics.RGB;
public class TranslatorUtils {
public static void ConvertChildren(ArrayList<ADLWidget> childWidgets, AbstractContainerModel parentModel, RGB colorMap[]){
for (ADLWidget adlWidget : childWidgets){
try {
String widgetType = adlWidget.getType();
if (widgetType.equals("arc")){
parentModel.addChild((new Arc2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("bar")){
parentModel.addChild((new Bar2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("byte")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("cartesian plot")){
parentModel.addChild((new CartesianPlot2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("choice button")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("composite")){
parentModel.addChild((new Composite2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("dynamic symbol")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("file")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("image")){
parentModel.addChild((new Image2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("indicator")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("menu")){
parentModel.addChild((new Menu2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("message button")){
parentModel.addChild((new MessageButton2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("toggle button")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("meter")){
parentModel.addChild((new Meter2Model(adlWidget, colorMap)).getWidgetModel());
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("oval")){
parentModel.addChild((new Oval2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("polygon")){
parentModel.addChild((new Polygon2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("polyline")){
parentModel.addChild((new PolyLine2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("line")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("rectangle")){
parentModel.addChild((new Rectangle2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("related display")){
parentModel.addChild((new RelatedDisplay2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("strip chart")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("text")){
parentModel.addChild((new Text2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("text update")){
parentModel.addChild((new TextUpdate2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("text entry")){
parentModel.addChild((new TextEntry2Model(adlWidget, colorMap)).getWidgetModel());
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("valuator")){
parentModel.addChild((new Valuator2Model(adlWidget, colorMap)).getWidgetModel());
printNotCompletelyHandledMessage(widgetType);
}
else if (widgetType.equals("basic attribute")){
printNotHandledMessage(widgetType);
}
else if (widgetType.equals("dynamic attribute")){
printNotHandledMessage(widgetType);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Print message that a given ADL file structure is not handled.
*/
private static void printNotHandledMessage(String type) {
System.out.println("EditHandler: " + type + " is not handled");
}
private static void printNotCompletelyHandledMessage(String type) {
System.out.println("EditHandler: " + type + " is not completely handled");
}
}
| applications/plugins/org.csstudio.opibuilder.adl2boy/src/org/csstudio/opibuilder/adl2boy/translator/TranslatorUtils.java | New class to handle common tasks. Most importantly run through a list of ADLWidgets and convert them to the appropriate model classes.
| applications/plugins/org.csstudio.opibuilder.adl2boy/src/org/csstudio/opibuilder/adl2boy/translator/TranslatorUtils.java | New class to handle common tasks. Most importantly run through a list of ADLWidgets and convert them to the appropriate model classes. | <ide><path>pplications/plugins/org.csstudio.opibuilder.adl2boy/src/org/csstudio/opibuilder/adl2boy/translator/TranslatorUtils.java
<add>package org.csstudio.opibuilder.adl2boy.translator;
<add>
<add>import java.util.ArrayList;
<add>
<add>import org.csstudio.opibuilder.model.AbstractContainerModel;
<add>import org.csstudio.utility.adlparser.fileParser.ADLWidget;
<add>import org.eclipse.swt.graphics.RGB;
<add>
<add>public class TranslatorUtils {
<add>
<add> public static void ConvertChildren(ArrayList<ADLWidget> childWidgets, AbstractContainerModel parentModel, RGB colorMap[]){
<add> for (ADLWidget adlWidget : childWidgets){
<add> try {
<add> String widgetType = adlWidget.getType();
<add> if (widgetType.equals("arc")){
<add> parentModel.addChild((new Arc2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add> }
<add> else if (widgetType.equals("bar")){
<add> parentModel.addChild((new Bar2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("byte")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("cartesian plot")){
<add> parentModel.addChild((new CartesianPlot2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("choice button")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("composite")){
<add> parentModel.addChild((new Composite2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("dynamic symbol")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("file")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("image")){
<add> parentModel.addChild((new Image2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("indicator")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("menu")){
<add> parentModel.addChild((new Menu2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("message button")){
<add> parentModel.addChild((new MessageButton2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("toggle button")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("meter")){
<add> parentModel.addChild((new Meter2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("oval")){
<add> parentModel.addChild((new Oval2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("polygon")){
<add> parentModel.addChild((new Polygon2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("polyline")){
<add> parentModel.addChild((new PolyLine2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("line")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("rectangle")){
<add> parentModel.addChild((new Rectangle2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("related display")){
<add> parentModel.addChild((new RelatedDisplay2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("strip chart")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("text")){
<add> parentModel.addChild((new Text2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("text update")){
<add> parentModel.addChild((new TextUpdate2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("text entry")){
<add> parentModel.addChild((new TextEntry2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("valuator")){
<add> parentModel.addChild((new Valuator2Model(adlWidget, colorMap)).getWidgetModel());
<add> printNotCompletelyHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("basic attribute")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> else if (widgetType.equals("dynamic attribute")){
<add> printNotHandledMessage(widgetType);
<add>
<add> }
<add> }
<add> catch (Exception ex) {
<add> ex.printStackTrace();
<add> }
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Print message that a given ADL file structure is not handled.
<add> */
<add> private static void printNotHandledMessage(String type) {
<add> System.out.println("EditHandler: " + type + " is not handled");
<add> }
<add> private static void printNotCompletelyHandledMessage(String type) {
<add> System.out.println("EditHandler: " + type + " is not completely handled");
<add> }
<add>
<add>} |
|
Java | apache-2.0 | ea2b3d97106ee7f385525047a658c592e9a01bc6 | 0 | ldo/ObjViewer_Android,pandaface0513/ObjViewer_Android | package nz.gen.geek_central.GLUseful;
/*
Quaternion representation of 3D rotation transformations.
Copyright 2011 by Lawrence D'Oliveiro <[email protected]>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
*/
import android.opengl.GLES11;
public class Rotation implements android.os.Parcelable
{
public final float c, x, y, z;
public Rotation
(
float AngleDegrees,
float X,
float Y,
float Z
)
/* constructs a Rotation that rotates by the specified angle
about the axis direction (X, Y, Z). */
{
final float Cos = android.util.FloatMath.cos((float)Math.toRadians(AngleDegrees / 2));
final float Sin = android.util.FloatMath.sin((float)Math.toRadians(AngleDegrees / 2));
final float Mag = android.util.FloatMath.sqrt(X * X + Y * Y + Z * Z);
c = Cos;
x = Sin * X / Mag;
y = Sin * Y / Mag;
z = Sin * Z / Mag;
} /*Rotation*/
public static final Rotation Null = new Rotation(0, 0, 0, 1);
/* represents no rotation at all */
private Rotation
(
float c,
float x,
float y,
float z,
Object Dummy
)
/* internal-use constructor with directly-computed components. Note
this does not compensate for accumulated rounding errors. */
{
this.c = c;
this.x = x;
this.y = y;
this.z = z;
} /*Rotation*/
public static final android.os.Parcelable.Creator<Rotation> CREATOR =
/* restore state from a Parcel. */
new android.os.Parcelable.Creator<Rotation>()
{
public Rotation createFromParcel
(
android.os.Parcel Post
)
{
final android.os.Bundle MyState = Post.readBundle();
return
new Rotation
(
MyState.getFloat("c", Null.c),
MyState.getFloat("x", Null.x),
MyState.getFloat("y", Null.y),
MyState.getFloat("z", Null.z),
null
);
} /*createFromParcel*/
public Rotation[] newArray
(
int NrElts
)
{
return
new Rotation[NrElts];
} /*newArray*/
} /*Parcelable.Creator*/;
@Override
public int describeContents()
{
return
0; /* nothing special */
} /*describeContents*/
@Override
public void writeToParcel
(
android.os.Parcel Post,
int Flags
)
/* save state to a Parcel. */
{
final android.os.Bundle MyState = new android.os.Bundle();
MyState.putFloat("c", c);
MyState.putFloat("x", x);
MyState.putFloat("y", y);
MyState.putFloat("z", z);
Post.writeBundle(MyState);
} /*writeToParcel*/
public Rotation inv()
/* returns rotation by the opposite angle around the same axis. Or alternatively,
the same angle around the opposite-pointing axis . */
{
return
new Rotation(c, -x, -y, -z, null);
} /*inv*/
public Rotation mul
(
Rotation that
)
/* returns composition with another rotation. */
{
return
new Rotation
(
this.c * that.c - this.x * that.x - this.y * that.y - this.z * that.z,
this.y * that.z - this.z * that.y + this.c * that.x + that.c * this.x,
this.z * that.x - this.x * that.z + this.c * that.y + that.c * this.y,
this.x * that.y - this.y * that.x + this.c * that.z + that.c * this.z,
null
);
} /*mul*/
public Rotation mul
(
float Frac
)
/* returns the specified fraction of the rotation. */
{
final float Mag = android.util.FloatMath.sqrt(x * x + y * y + z * z);
return
Mag != 0.0f ?
new Rotation((float)Math.toDegrees(2 * Math.atan2(Mag, c) * Frac), x / Mag, y / Mag, z / Mag)
:
new Rotation(0, 0, 0, 1);
} /*mul*/
public void Apply()
/* applies the rotation to the currently-selected GL matrix. */
{
final float Mag = android.util.FloatMath.sqrt(x * x + y * y + z * z);
if (Mag != 0.0f)
{
GLES11.glRotatef((float)Math.toDegrees(2 * Math.atan2(Mag, c)), x / Mag, y / Mag, z / Mag);
} /*if*/
} /*Apply*/
public String toString()
{
return
String.format
(
"Rotation(%e, %e, %e, %e)",
c, x, y, z
);
} /*toString*/
} /*Rotation*/
| src/Rotation.java | package nz.gen.geek_central.GLUseful;
/*
Quaternion representation of 3D rotation transformations.
Copyright 2011 by Lawrence D'Oliveiro <[email protected]>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
*/
import android.opengl.GLES11;
public class Rotation implements android.os.Parcelable
{
public final float c, x, y, z;
public Rotation
(
float AngleDegrees,
float X,
float Y,
float Z
)
/* constructs a Rotation that rotates by the specified angle
about the axis direction (X, Y, Z). */
{
final float Cos = android.util.FloatMath.cos((float)Math.toRadians(AngleDegrees / 2));
final float Sin = android.util.FloatMath.sin((float)Math.toRadians(AngleDegrees / 2));
final float Mag = android.util.FloatMath.sqrt(X * X + Y * Y + Z * Z);
c = Cos;
x = Sin * X / Mag;
y = Sin * Y / Mag;
z = Sin * Z / Mag;
} /*Rotation*/
public static final Rotation Null = new Rotation(0, 0, 0, 1);
/* represents no rotation at all */
private Rotation
(
float c,
float x,
float y,
float z,
Object Dummy
)
/* internal-use constructor with directly-computed components. Note
this does not compensate for accumulated rounding errors. */
{
this.c = c;
this.x = x;
this.y = y;
this.z = z;
} /*Rotation*/
public static android.os.Parcelable.Creator<Rotation> CREATOR =
/* restore state from a Parcel. */
new android.os.Parcelable.Creator<Rotation>()
{
public Rotation createFromParcel
(
android.os.Parcel Post
)
{
final android.os.Bundle MyState = Post.readBundle();
return
new Rotation
(
MyState.getFloat("c", Null.c),
MyState.getFloat("x", Null.x),
MyState.getFloat("y", Null.y),
MyState.getFloat("z", Null.z),
null
);
} /*createFromParcel*/
public Rotation[] newArray
(
int NrElts
)
{
return
new Rotation[NrElts];
} /*newArray*/
} /*Parcelable.Creator*/;
@Override
public int describeContents()
{
return
0; /* nothing special */
} /*describeContents*/
@Override
public void writeToParcel
(
android.os.Parcel Post,
int Flags
)
/* save state to a Parcel. */
{
final android.os.Bundle MyState = new android.os.Bundle();
MyState.putFloat("c", c);
MyState.putFloat("x", x);
MyState.putFloat("y", y);
MyState.putFloat("z", z);
Post.writeBundle(MyState);
} /*writeToParcel*/
public Rotation inv()
/* returns rotation by the opposite angle around the same axis. Or alternatively,
the same angle around the opposite-pointing axis . */
{
return
new Rotation(c, -x, -y, -z, null);
} /*inv*/
public Rotation mul
(
Rotation that
)
/* returns composition with another rotation. */
{
return
new Rotation
(
this.c * that.c - this.x * that.x - this.y * that.y - this.z * that.z,
this.y * that.z - this.z * that.y + this.c * that.x + that.c * this.x,
this.z * that.x - this.x * that.z + this.c * that.y + that.c * this.y,
this.x * that.y - this.y * that.x + this.c * that.z + that.c * this.z,
null
);
} /*mul*/
public Rotation mul
(
float Frac
)
/* returns the specified fraction of the rotation. */
{
final float Mag = android.util.FloatMath.sqrt(x * x + y * y + z * z);
return
Mag != 0.0f ?
new Rotation((float)Math.toDegrees(2 * Math.atan2(Mag, c) * Frac), x / Mag, y / Mag, z / Mag)
:
new Rotation(0, 0, 0, 1);
} /*mul*/
public void Apply()
/* applies the rotation to the currently-selected GL matrix. */
{
final float Mag = android.util.FloatMath.sqrt(x * x + y * y + z * z);
if (Mag != 0.0f)
{
GLES11.glRotatef((float)Math.toDegrees(2 * Math.atan2(Mag, c)), x / Mag, y / Mag, z / Mag);
} /*if*/
} /*Apply*/
public String toString()
{
return
String.format
(
"Rotation(%e, %e, %e, %e)",
c, x, y, z
);
} /*toString*/
} /*Rotation*/
| CREATOR field should probably be final
| src/Rotation.java | CREATOR field should probably be final | <ide><path>rc/Rotation.java
<ide> this.z = z;
<ide> } /*Rotation*/
<ide>
<del> public static android.os.Parcelable.Creator<Rotation> CREATOR =
<add> public static final android.os.Parcelable.Creator<Rotation> CREATOR =
<ide> /* restore state from a Parcel. */
<ide> new android.os.Parcelable.Creator<Rotation>()
<ide> { |
|
Java | apache-2.0 | b9657963c66927530e931c822b3f98ee3de0f725 | 0 | apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena,apache/jena | /*
* 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.jena.sparql.path;
import java.util.ArrayList ;
import java.util.Iterator ;
import java.util.List ;
import java.util.Objects;
import java.util.function.Predicate;
import org.apache.jena.atlas.iterator.Iter ;
import org.apache.jena.graph.Graph ;
import org.apache.jena.graph.Node ;
import org.apache.jena.graph.Triple ;
import org.apache.jena.sparql.ARQInternalErrorException ;
import org.apache.jena.sparql.algebra.Op ;
import org.apache.jena.sparql.algebra.op.OpBGP ;
import org.apache.jena.sparql.algebra.op.OpPath ;
import org.apache.jena.sparql.algebra.op.OpSequence ;
import org.apache.jena.sparql.core.BasicPattern ;
import org.apache.jena.sparql.core.PathBlock ;
import org.apache.jena.sparql.core.TriplePath ;
import org.apache.jena.sparql.core.Var ;
import org.apache.jena.sparql.engine.ExecutionContext ;
import org.apache.jena.sparql.engine.QueryIterator ;
import org.apache.jena.sparql.engine.binding.Binding ;
import org.apache.jena.sparql.engine.binding.BindingFactory ;
import org.apache.jena.sparql.engine.iterator.QueryIterConcat ;
import org.apache.jena.sparql.engine.iterator.QueryIterPlainWrapper ;
import org.apache.jena.sparql.engine.iterator.QueryIterYieldN ;
import org.apache.jena.sparql.mgt.Explain ;
import org.apache.jena.sparql.path.eval.PathEval ;
import org.apache.jena.sparql.pfunction.PropertyFunctionFactory ;
import org.apache.jena.sparql.pfunction.PropertyFunctionRegistry ;
import org.apache.jena.sparql.util.Context;
import org.apache.jena.sparql.util.graph.GraphUtils ;
public class PathLib
{
/** Convert any paths of exactly one predicate to a triple pattern */
public static Op pathToTriples(PathBlock pattern) {
BasicPattern bp = null;
Op op = null;
for ( TriplePath tp : pattern ) {
if ( tp.isTriple() ) {
if ( bp == null )
bp = new BasicPattern();
bp.add(tp.asTriple());
continue;
}
// Path form.
op = flush(bp, op);
bp = null;
OpPath opPath2 = new OpPath(tp);
op = OpSequence.create(op, opPath2);
continue;
}
// End. Finish off any outstanding BGP.
op = flush(bp, op);
return op;
}
static private Op flush(BasicPattern bp, Op op) {
if ( bp == null || bp.isEmpty() )
return op;
OpBGP opBGP = new OpBGP(bp);
op = OpSequence.create(op, opBGP);
return op;
}
/** Install a path as a property function in the global property function registry */
public static void install(String uri, Path path)
{ install(uri, path, PropertyFunctionRegistry.get()) ; }
/** Install a path as a property function in a given registry */
public static void install(String uri, final Path path, PropertyFunctionRegistry registry) {
PropertyFunctionFactory pathPropFuncFactory = (u) -> new PathPropertyFunction(path) ;
registry.put(uri, pathPropFuncFactory) ;
}
public static QueryIterator execTriplePath(Binding binding, TriplePath triplePath, ExecutionContext execCxt) {
if ( triplePath.isTriple() ) {
// Fake it. This happens only for API constructed situations.
Path path = new P_Link(triplePath.getPredicate());
triplePath = new TriplePath(triplePath.getSubject(), path, triplePath.getObject());
}
return execTriplePath(binding,
triplePath.getSubject(),
triplePath.getPath(),
triplePath.getObject(),
execCxt) ;
}
public static QueryIterator execTriplePath(Binding binding, Node s, Path path, Node o, ExecutionContext execCxt) {
Explain.explain(s, path, o, execCxt.getContext()) ;
s = Var.lookup(binding, s) ;
o = Var.lookup(binding, o) ;
Iterator<Node> iter = null ;
Node endNode = null ;
Graph graph = execCxt.getActiveGraph() ;
// Both variables.
if ( Var.isVar(s) && Var.isVar(o) ) {
if ( s.equals(o) )
return execUngroundedPathSameVar(binding, graph, Var.alloc(s), path, execCxt);
else
return execUngroundedPath(binding, graph, Var.alloc(s), path, Var.alloc(o), execCxt);
}
// Both constants.
if ( !Var.isVar(s) && !Var.isVar(o) )
return evalGroundedPath(binding, graph, s, path, o, execCxt);
// One variable, one constant
if ( Var.isVar(s) ) {
// Var subject, concrete object - do backwards.
iter = PathEval.evalReverse(graph, o, path, execCxt.getContext());
endNode = s;
} else {
iter = PathEval.eval(graph, s, path, execCxt.getContext());
endNode = o;
}
return evalGroundedOneEnd(binding, iter, endNode, execCxt);
}
private static QueryIterator evalGroundedOneEnd(Binding binding, Iterator<Node> iter, Node endNode, ExecutionContext execCxt) {
List<Binding> results = new ArrayList<>() ;
if (! Var.isVar(endNode))
throw new ARQInternalErrorException("Non-variable endnode in _execTriplePath") ;
Var var = Var.alloc(endNode) ;
// Assign.
for (; iter.hasNext();) {
Node n = iter.next() ;
results.add(BindingFactory.binding(binding, var, n)) ;
}
return new QueryIterPlainWrapper(results.iterator(), execCxt) ;
}
// Subject and object are nodes.
private static QueryIterator evalGroundedPath(Binding binding,
Graph graph, Node subject, Path path, Node object,
ExecutionContext execCxt) {
Iterator<Node> iter = PathEval.eval(graph, subject, path, execCxt.getContext()) ;
// Now count the number of matches.
int count = 0 ;
for ( ; iter.hasNext() ; ) {
Node n = iter.next() ;
if ( n.sameValueAs(object) )
count++ ;
}
return new QueryIterYieldN(count, binding, execCxt) ;
}
// Brute force evaluation of a TriplePath where neither subject nor object are bound
private static QueryIterator execUngroundedPath(Binding binding, Graph graph, Var sVar, Path path, Var oVar, ExecutionContext execCxt) {
// Starting points.
Iterator<Node> iter = determineUngroundedStartingSet(graph, path, execCxt) ;
QueryIterConcat qIterCat = new QueryIterConcat(execCxt) ;
for ( ; iter.hasNext() ; )
{
Node n = iter.next() ;
Binding b2 = BindingFactory.binding(binding, sVar, n) ;
Iterator<Node> pathIter = PathEval.eval(graph, n, path, execCxt.getContext()) ;
QueryIterator qIter = evalGroundedOneEnd(b2, pathIter, oVar, execCxt) ;
qIterCat.add(qIter) ;
}
return qIterCat ;
}
private static QueryIterator execUngroundedPathSameVar(Binding binding, Graph graph, Var var, Path path, ExecutionContext execCxt) {
// Try each end, ungrounded.
// Slightly more efficient would be to add a per-engine to do this.
Iterator<Node> iter = determineUngroundedStartingSet(graph, path, execCxt) ;
QueryIterConcat qIterCat = new QueryIterConcat(execCxt) ;
for ( ; iter.hasNext() ; )
{
Node n = iter.next() ;
Binding b2 = BindingFactory.binding(binding, var, n) ;
int x = existsPath(graph, n, path, n, execCxt) ;
if ( x > 0 )
{
QueryIterator qIter = new QueryIterYieldN(x, b2, execCxt) ;
qIterCat.add(qIter) ;
}
}
return qIterCat ;
}
private static Iterator<Node> determineUngroundedStartingSet(Graph graph, Path path, ExecutionContext execCxt) {
// Find a better set of seed values than "everything"
// (:p+) and (^:p)+
// :p* need everything because it is always the case that "<x> :p* <x>"
if ( path instanceof P_OneOrMore1 || path instanceof P_OneOrMoreN ) {
Path subPath = ((P_Path1)path).getSubPath() ;
if ( subPath instanceof P_Link ) {
// :predicate+
// If a property functions,
P_Link link = (P_Link)subPath ;
if ( ! isPropertyFunction(link.getNode(), execCxt.getContext()) ) {
Iterator<Triple> sIter = graph.find(null, link.getNode(), null) ;
return Iter.iter(sIter).distinctAdjacent().map(Triple::getSubject).distinct() ;
}
} else {
if ( subPath instanceof P_Inverse ) {
P_Inverse pInv = (P_Inverse)subPath ;
if ( pInv.getSubPath() instanceof P_Link ) {
// (^:predicate)+
P_Link link = (P_Link)(pInv.getSubPath()) ;
if ( ! isPropertyFunction(link.getNode(), execCxt.getContext()) ) {
Iterator<Triple> sIter = graph.find(null, link.getNode(), null) ;
return Iter.iter(sIter).distinctAdjacent().map(Triple::getObject).distinct() ;
}
}
}
}
}
// No idea - everything.
return GraphUtils.allNodes(graph) ;
}
private static boolean isPropertyFunction(Node node, Context context) {
if ( ! node.isURI() )
return false ;
return PropertyFunctionRegistry.chooseRegistry(context).isRegistered(node.getURI());
}
private static int existsPath(Graph graph, Node subject, Path path, final Node object, ExecutionContext execCxt) {
if ( ! subject.isConcrete() || !object.isConcrete() )
throw new ARQInternalErrorException("Non concrete node for existsPath evaluation") ;
Iterator<Node> iter = PathEval.eval(graph, subject, path, execCxt.getContext()) ;
Predicate<Node> filter = node -> Objects.equals(node, object);
// See if we got to the node we're interested in finishing at.
iter = Iter.filter(iter, filter) ;
long x = Iter.count(iter) ;
return (int)x ;
}
}
| jena-arq/src/main/java/org/apache/jena/sparql/path/PathLib.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.jena.sparql.path;
import java.util.ArrayList ;
import java.util.Iterator ;
import java.util.List ;
import java.util.Objects;
import java.util.function.Predicate;
import org.apache.jena.atlas.iterator.Iter ;
import org.apache.jena.graph.Graph ;
import org.apache.jena.graph.Node ;
import org.apache.jena.graph.Triple ;
import org.apache.jena.sparql.ARQInternalErrorException ;
import org.apache.jena.sparql.algebra.Op ;
import org.apache.jena.sparql.algebra.op.OpBGP ;
import org.apache.jena.sparql.algebra.op.OpPath ;
import org.apache.jena.sparql.algebra.op.OpSequence ;
import org.apache.jena.sparql.core.BasicPattern ;
import org.apache.jena.sparql.core.PathBlock ;
import org.apache.jena.sparql.core.TriplePath ;
import org.apache.jena.sparql.core.Var ;
import org.apache.jena.sparql.engine.ExecutionContext ;
import org.apache.jena.sparql.engine.QueryIterator ;
import org.apache.jena.sparql.engine.binding.Binding ;
import org.apache.jena.sparql.engine.binding.BindingFactory ;
import org.apache.jena.sparql.engine.iterator.QueryIterConcat ;
import org.apache.jena.sparql.engine.iterator.QueryIterPlainWrapper ;
import org.apache.jena.sparql.engine.iterator.QueryIterYieldN ;
import org.apache.jena.sparql.mgt.Explain ;
import org.apache.jena.sparql.path.eval.PathEval ;
import org.apache.jena.sparql.pfunction.PropertyFunctionFactory ;
import org.apache.jena.sparql.pfunction.PropertyFunctionRegistry ;
import org.apache.jena.sparql.util.graph.GraphUtils ;
public class PathLib
{
/** Convert any paths of exactly one predicate to a triple pattern */
public static Op pathToTriples(PathBlock pattern) {
BasicPattern bp = null;
Op op = null;
for ( TriplePath tp : pattern ) {
if ( tp.isTriple() ) {
if ( bp == null )
bp = new BasicPattern();
bp.add(tp.asTriple());
continue;
}
// Path form.
op = flush(bp, op);
bp = null;
OpPath opPath2 = new OpPath(tp);
op = OpSequence.create(op, opPath2);
continue;
}
// End. Finish off any outstanding BGP.
op = flush(bp, op);
return op;
}
static private Op flush(BasicPattern bp, Op op) {
if ( bp == null || bp.isEmpty() )
return op;
OpBGP opBGP = new OpBGP(bp);
op = OpSequence.create(op, opBGP);
return op;
}
/** Install a path as a property function in the global property function registry */
public static void install(String uri, Path path)
{ install(uri, path, PropertyFunctionRegistry.get()) ; }
/** Install a path as a property function in a given registry */
public static void install(String uri, final Path path, PropertyFunctionRegistry registry) {
PropertyFunctionFactory pathPropFuncFactory = (u) -> new PathPropertyFunction(path) ;
registry.put(uri, pathPropFuncFactory) ;
}
public static QueryIterator execTriplePath(Binding binding, TriplePath triplePath, ExecutionContext execCxt) {
if ( triplePath.isTriple() ) {
// Fake it. This happens only for API constructed situations.
Path path = new P_Link(triplePath.getPredicate());
triplePath = new TriplePath(triplePath.getSubject(), path, triplePath.getObject());
}
return execTriplePath(binding,
triplePath.getSubject(),
triplePath.getPath(),
triplePath.getObject(),
execCxt) ;
}
public static QueryIterator execTriplePath(Binding binding, Node s, Path path, Node o, ExecutionContext execCxt) {
Explain.explain(s, path, o, execCxt.getContext()) ;
s = Var.lookup(binding, s) ;
o = Var.lookup(binding, o) ;
Iterator<Node> iter = null ;
Node endNode = null ;
Graph graph = execCxt.getActiveGraph() ;
// Both variables.
if ( Var.isVar(s) && Var.isVar(o) ) {
if ( s.equals(o) )
return execUngroundedPathSameVar(binding, graph, Var.alloc(s), path, execCxt);
else
return execUngroundedPath(binding, graph, Var.alloc(s), path, Var.alloc(o), execCxt);
}
// Both constants.
if ( !Var.isVar(s) && !Var.isVar(o) )
return evalGroundedPath(binding, graph, s, path, o, execCxt);
// One variable, one constant
if ( Var.isVar(s) ) {
// Var subject, concrete object - do backwards.
iter = PathEval.evalReverse(graph, o, path, execCxt.getContext());
endNode = s;
} else {
iter = PathEval.eval(graph, s, path, execCxt.getContext());
endNode = o;
}
return evalGroundedOneEnd(binding, iter, endNode, execCxt);
}
private static QueryIterator evalGroundedOneEnd(Binding binding, Iterator<Node> iter, Node endNode, ExecutionContext execCxt) {
List<Binding> results = new ArrayList<>() ;
if (! Var.isVar(endNode))
throw new ARQInternalErrorException("Non-variable endnode in _execTriplePath") ;
Var var = Var.alloc(endNode) ;
// Assign.
for (; iter.hasNext();) {
Node n = iter.next() ;
results.add(BindingFactory.binding(binding, var, n)) ;
}
return new QueryIterPlainWrapper(results.iterator(), execCxt) ;
}
// Subject and object are nodes.
private static QueryIterator evalGroundedPath(Binding binding,
Graph graph, Node subject, Path path, Node object,
ExecutionContext execCxt) {
Iterator<Node> iter = PathEval.eval(graph, subject, path, execCxt.getContext()) ;
// Now count the number of matches.
int count = 0 ;
for ( ; iter.hasNext() ; ) {
Node n = iter.next() ;
if ( n.sameValueAs(object) )
count++ ;
}
return new QueryIterYieldN(count, binding, execCxt) ;
}
// Brute force evaluation of a TriplePath where neither subject nor object are bound
private static QueryIterator execUngroundedPath(Binding binding, Graph graph, Var sVar, Path path, Var oVar, ExecutionContext execCxt) {
// Starting points.
Iterator<Node> iter = determineUngroundedStartingSet(graph, path, execCxt) ;
QueryIterConcat qIterCat = new QueryIterConcat(execCxt) ;
for ( ; iter.hasNext() ; )
{
Node n = iter.next() ;
Binding b2 = BindingFactory.binding(binding, sVar, n) ;
Iterator<Node> pathIter = PathEval.eval(graph, n, path, execCxt.getContext()) ;
QueryIterator qIter = evalGroundedOneEnd(b2, pathIter, oVar, execCxt) ;
qIterCat.add(qIter) ;
}
return qIterCat ;
}
private static QueryIterator execUngroundedPathSameVar(Binding binding, Graph graph, Var var, Path path, ExecutionContext execCxt) {
// Try each end, ungrounded.
// Slightly more efficient would be to add a per-engine to do this.
Iterator<Node> iter = determineUngroundedStartingSet(graph, path, execCxt) ;
QueryIterConcat qIterCat = new QueryIterConcat(execCxt) ;
for ( ; iter.hasNext() ; )
{
Node n = iter.next() ;
Binding b2 = BindingFactory.binding(binding, var, n) ;
int x = existsPath(graph, n, path, n, execCxt) ;
if ( x > 0 )
{
QueryIterator qIter = new QueryIterYieldN(x, b2, execCxt) ;
qIterCat.add(qIter) ;
}
}
return qIterCat ;
}
private static Iterator<Node> determineUngroundedStartingSet(Graph graph, Path path, ExecutionContext execCxt) {
// Find a better set of seed values than "everything"
// (:p+) and (^:p)+
// :p* need everything because it is always the case that "<x> :p* <x>"
if ( path instanceof P_OneOrMore1 || path instanceof P_OneOrMoreN ) {
Path subPath = ((P_Path1)path).getSubPath() ;
if ( subPath instanceof P_Link ) {
// :predicate+
P_Link link = (P_Link)subPath ;
Iterator<Triple> sIter = graph.find(null, link.getNode(), null) ;
return Iter.iter(sIter).distinctAdjacent().map(Triple::getSubject).distinct() ;
} else {
if ( subPath instanceof P_Inverse ) {
P_Inverse pInv = (P_Inverse)subPath ;
if ( pInv.getSubPath() instanceof P_Link ) {
// (^:predicate)+
P_Link link = (P_Link)(pInv.getSubPath()) ;
Iterator<Triple> sIter = graph.find(null, link.getNode(), null) ;
return Iter.iter(sIter).distinctAdjacent().map(Triple::getObject).distinct() ;
}
}
}
}
// No idea - everything.
return GraphUtils.allNodes(graph) ;
}
private static int existsPath(Graph graph, Node subject, Path path, final Node object, ExecutionContext execCxt) {
if ( ! subject.isConcrete() || !object.isConcrete() )
throw new ARQInternalErrorException("Non concrete node for existsPath evaluation") ;
Iterator<Node> iter = PathEval.eval(graph, subject, path, execCxt.getContext()) ;
Predicate<Node> filter = node -> Objects.equals(node, object);
// See if we got to the node we're interested in finishing at.
iter = Iter.filter(iter, filter) ;
long x = Iter.count(iter) ;
return (int)x ;
}
}
| Cope with property paths in p+ paths. | jena-arq/src/main/java/org/apache/jena/sparql/path/PathLib.java | Cope with property paths in p+ paths. | <ide><path>ena-arq/src/main/java/org/apache/jena/sparql/path/PathLib.java
<ide> import org.apache.jena.sparql.path.eval.PathEval ;
<ide> import org.apache.jena.sparql.pfunction.PropertyFunctionFactory ;
<ide> import org.apache.jena.sparql.pfunction.PropertyFunctionRegistry ;
<add>import org.apache.jena.sparql.util.Context;
<ide> import org.apache.jena.sparql.util.graph.GraphUtils ;
<ide>
<ide> public class PathLib
<ide> Path subPath = ((P_Path1)path).getSubPath() ;
<ide> if ( subPath instanceof P_Link ) {
<ide> // :predicate+
<add> // If a property functions,
<ide> P_Link link = (P_Link)subPath ;
<del> Iterator<Triple> sIter = graph.find(null, link.getNode(), null) ;
<del> return Iter.iter(sIter).distinctAdjacent().map(Triple::getSubject).distinct() ;
<add> if ( ! isPropertyFunction(link.getNode(), execCxt.getContext()) ) {
<add> Iterator<Triple> sIter = graph.find(null, link.getNode(), null) ;
<add> return Iter.iter(sIter).distinctAdjacent().map(Triple::getSubject).distinct() ;
<add> }
<ide> } else {
<ide> if ( subPath instanceof P_Inverse ) {
<ide> P_Inverse pInv = (P_Inverse)subPath ;
<ide> if ( pInv.getSubPath() instanceof P_Link ) {
<ide> // (^:predicate)+
<ide> P_Link link = (P_Link)(pInv.getSubPath()) ;
<del> Iterator<Triple> sIter = graph.find(null, link.getNode(), null) ;
<del> return Iter.iter(sIter).distinctAdjacent().map(Triple::getObject).distinct() ;
<add> if ( ! isPropertyFunction(link.getNode(), execCxt.getContext()) ) {
<add> Iterator<Triple> sIter = graph.find(null, link.getNode(), null) ;
<add> return Iter.iter(sIter).distinctAdjacent().map(Triple::getObject).distinct() ;
<add> }
<ide> }
<ide> }
<ide> }
<ide> return GraphUtils.allNodes(graph) ;
<ide> }
<ide>
<add> private static boolean isPropertyFunction(Node node, Context context) {
<add> if ( ! node.isURI() )
<add> return false ;
<add> return PropertyFunctionRegistry.chooseRegistry(context).isRegistered(node.getURI());
<add> }
<add>
<ide> private static int existsPath(Graph graph, Node subject, Path path, final Node object, ExecutionContext execCxt) {
<ide> if ( ! subject.isConcrete() || !object.isConcrete() )
<ide> throw new ARQInternalErrorException("Non concrete node for existsPath evaluation") ; |
|
Java | apache-2.0 | 6235953eb014a27b89d2c0cdc1ef9ae5e6f6b6fa | 0 | researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds | webofneeds/won-bot/src/main/java/won/bot/framework/eventbot/event/impl/wonmessage/OpenFromOtherAtomEvent.java | /*
* Copyright 2012 Research Studios Austria Forschungsges.m.b.H. 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 won.bot.framework.eventbot.event.impl.wonmessage;
import won.protocol.message.WonMessage;
import won.protocol.model.Connection;
/**
*
*/
public class OpenFromOtherAtomEvent extends WonMessageReceivedOnConnectionEvent {
public OpenFromOtherAtomEvent(final Connection con, final WonMessage wonMessage) {
super(con, wonMessage);
}
}
| Remove all traces of open message type | webofneeds/won-bot/src/main/java/won/bot/framework/eventbot/event/impl/wonmessage/OpenFromOtherAtomEvent.java | Remove all traces of open message type | <ide><path>ebofneeds/won-bot/src/main/java/won/bot/framework/eventbot/event/impl/wonmessage/OpenFromOtherAtomEvent.java
<del>/*
<del> * Copyright 2012 Research Studios Austria Forschungsges.m.b.H. Licensed under
<del> * the Apache License, Version 2.0 (the "License"); you may not use this file
<del> * except in compliance with the License. You may obtain a copy of the License
<del> * at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
<del> * law or agreed to in writing, software distributed under the License is
<del> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<del> * KIND, either express or implied. See the License for the specific language
<del> * governing permissions and limitations under the License.
<del> */
<del>package won.bot.framework.eventbot.event.impl.wonmessage;
<del>
<del>import won.protocol.message.WonMessage;
<del>import won.protocol.model.Connection;
<del>
<del>/**
<del> *
<del> */
<del>public class OpenFromOtherAtomEvent extends WonMessageReceivedOnConnectionEvent {
<del> public OpenFromOtherAtomEvent(final Connection con, final WonMessage wonMessage) {
<del> super(con, wonMessage);
<del> }
<del>} |
||
Java | apache-2.0 | dcbe4ef3b2a993734950bbe0cc3395b7bbe3f7cc | 0 | socialsensor/socialsensor-framework-client,MKLab-ITI/mklab-framework-client,MKLab-ITI/mklab-framework-client,socialsensor/socialsensor-framework-client,MKLab-ITI/mklab-framework-client,MKLab-ITI/mklab-framework-client,socialsensor/socialsensor-framework-client | package eu.socialsensor.framework.client.search.solr;
import eu.socialsensor.framework.common.domain.Query;
import eu.socialsensor.framework.common.domain.dysco.Dysco;
import eu.socialsensor.framework.common.domain.dysco.Dysco.DyscoType;
import eu.socialsensor.framework.common.domain.dysco.Entity;
import eu.socialsensor.framework.common.domain.dysco.Entity.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.beans.Field;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
*
* @author etzoannos - [email protected]
*/
public class SolrDysco {
public final Logger logger = Logger.getLogger(SolrDysco.class);
//The id of the dysco
@Field(value = "id")
private String id;
//The creation date of the dysco
@Field(value = "creationDate")
private Date creationDate;
//The title of the dysco
@Field(value = "title")
private String title;
//The score that shows how trending the dysco is
@Field(value = "dyscoScore")
private Double score = 0d;
//The type of the dysco (CUSTOM/TRENDING)
@Field(value = "dyscoType")
private String dyscoType;
//Fields holding the information about the main context
//of the items that constitute the dysco
//The extracted entities from items' content
//all 6 refer to the 3 types of entities and their weights in the dysco
@Field(value = "persons")
private List<String> persons = new ArrayList<String>();
@Field(value = "locations")
private List<String> locations = new ArrayList<String>();
@Field(value = "organizations")
private List<String> organizations = new ArrayList<String>();
//The users that contribute in social networks to dysco's topic
@Expose
@SerializedName(value = "contributors")
private List<String> contributors = new ArrayList<String>();
//The extracted keywords from items' content with their assigned weights
@Field(value = "keywords")
private List<String> keywords = new ArrayList<String>();
//The extracted hashtags from items' content with their assigned weights
@Field(value = "hashtags")
private List<String> hashtags = new ArrayList<String>();
//The query that will be used for retrieving relevant content to the Dysco from Solr
@Field(value = "solrQueryString")
private String solrQueryString;
@Field(value = "solrQueriesString")
private List<String> solrQueriesString = new ArrayList<String>();
@Field(value = "primalSolrQueriesString")
private List<String> primalSolrQueriesString = new ArrayList<String>();
@Field(value = "solrQueriesScore")
private List<String> solrQueriesScore = new ArrayList<String>();
//The variable can get values 0,1,2 and shows dysco's trending evolution.
@Field(value = "trending")
private int trending;
//The date that the dysco was last created (updated because similar dyscos existed in the past)
@Field(value = "updateDate")
private Date updateDate;
@Field(value = "listId")
private String listId;
public SolrDysco() {
id = UUID.randomUUID().toString();
}
public SolrDysco(Dysco dysco) {
id = dysco.getId();
creationDate = dysco.getCreationDate();
title = dysco.getTitle();
score = dysco.getScore();
dyscoType = dysco.getDyscoType().toString();
List<Entity> dyscoEntities = dysco.getEntities();
for (Entity entity : dyscoEntities) {
if (entity.getType().equals(Type.LOCATION)) {
locations.add(entity.getName());
}
if (entity.getType().equals(Type.PERSON)) {
persons.add(entity.getName());
}
if (entity.getType().equals(Type.ORGANIZATION)) {
organizations.add(entity.getName());
}
}
contributors = dysco.getContributors();
for (Map.Entry<String, Double> entry : dysco.getKeywords().entrySet()) {
keywords.add(entry.getKey());
}
for (Map.Entry<String, Double> entry : dysco.getHashtags().entrySet()) {
hashtags.add(entry.getKey());
}
solrQueryString = dysco.getSolrQueryString();
for(Query query : dysco.getPrimalSolrQueries()){
//logger.info("query name: "+query.getName());
//logger.info("query score: "+query.getScore().toString());
primalSolrQueriesString.add(query.getName());
}
//logger.info("DYSCO QUERIES : "+dysco.getSolrQueries().size());
for(Query query : dysco.getSolrQueries()){
//logger.info("query name: "+query.getName());
//logger.info("query score: "+query.getScore().toString());
solrQueriesString.add(query.getName());
solrQueriesScore.add(query.getScore().toString());
}
trending = dysco.getTrending();
updateDate = dysco.getUpdateDate();
listId = dysco.getListId();
}
public Dysco toDysco() {
Dysco dysco = new Dysco();
dysco.setId(id);
dysco.setCreationDate(creationDate);
dysco.setTitle(title);
dysco.setScore(score);
if (dyscoType.equals("CUSTOM")) {
dysco.setDyscoType(DyscoType.CUSTOM);
} else {
dysco.setDyscoType(DyscoType.TRENDING);
}
if (persons != null) {
for (String person : persons) {
Entity dyscoEntity = new Entity(person, 0.0, Type.PERSON);
dysco.addEntity(dyscoEntity);
}
}
if (locations != null) {
for (String location : locations) {
Entity dyscoEntity = new Entity(location, 0.0, Type.LOCATION);
dysco.addEntity(dyscoEntity);
}
}
if (organizations != null) {
for (String organization : organizations) {
Entity dyscoEntity = new Entity(organization, 0.0, Type.ORGANIZATION);
dysco.addEntity(dyscoEntity);
}
}
dysco.setContributors(contributors);
if (keywords != null) {
for (String keyword : keywords) {
dysco.addKeyword(keyword, 0.0);
}
}
if (hashtags != null) {
for (String hashtag : hashtags) {
dysco.addHashtag(hashtag, 0.0);
}
}
dysco.setSolrQueryString(solrQueryString);
List<Query> queries = new ArrayList<Query>();
for(int i=0;i<solrQueriesString.size();i++){
Query query = new Query();
query.setName(solrQueriesString.get(i));
query.setScore(Double.parseDouble(solrQueriesScore.get(i)));
queries.add(query);
}
dysco.setSolrQueries(queries);
dysco.setTrending(trending);
dysco.setUpdateDate(updateDate);
dysco.setListId(listId);
return dysco;
}
/**
* Returns the id of the dysco
*
* @return String
*/
public String getId() {
return id;
}
/**
* Sets the id of the dysco
*
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* Returns the creation date of the dysco
*
* @return Date
*/
public Date getCreationDate() {
return creationDate;
}
/**
* Sets the creation date of the dysco
*
* @param creationDate
*/
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
/**
* Returns the title of the dysco
*
* @return String
*/
public String getTitle() {
return title;
}
/**
* Sets the title of the dysco
*
* @param Title
*/
public void setTitle(String Title) {
this.title = Title;
}
/**
* Returns the score of the dysco
*
* @return Float
*/
public Double getScore() {
return score;
}
/**
* Sets the score of the dysco
*
* @param score
*/
public void setScore(Double score) {
this.score = score;
}
/**
* Returns the list of names of the Entities that are Persons inside the
* dysco
*
* @return List of String
*/
public List<String> getPersons() {
return persons;
}
/**
* Sets the list of names of the Entities that are Persons inside the dysco
*
* @param persons
*/
public void setPersons(List<String> persons) {
this.persons = persons;
}
/**
* Returns the list of names of the Entities that are Locations inside the
* dysco
*
* @return
*/
public List<String> getLocations() {
return locations;
}
/**
* Sets the list of names of the Entities that are Locations inside the
* dysco
*
* @param locations
*/
public void setLocations(List<String> locations) {
this.locations = locations;
}
/**
* Returns the list of names of the Entities that are Organizations inside
* the dysco
*
* @return List of String
*/
public List<String> getOrganizations() {
return organizations;
}
/**
* Sets the list of names of the Entities that are Organizations inside the
* dysco
*
* @param organizations
*/
public void setOrganizations(List<String> organizations) {
this.organizations = organizations;
}
/**
* Returns the list of contributors for the dysco
*
* @return List of String
*/
public List<String> getContributors() {
return contributors;
}
/**
* Sets the contributors for the dysco
*
* @param contributors
*/
public void setContributors(List<String> contributors) {
this.contributors = contributors;
}
/**
* Returns the keywords of the dysco
*
* @return List of String
*/
public List<String> getKeywords() {
return keywords;
}
/**
* Sets the keywords of the dysco
*
* @param keywords
*/
public void setKeywords(List<String> keywords) {
this.keywords = keywords;
}
/**
* Returns the hashtags of the dysco
*
* @return List of String
*/
public List<String> getHashtags() {
return hashtags;
}
/**
* Sets the hashtags of the dysco
*
* @param hashtags
*/
public void setHashtags(List<String> hashtags) {
this.hashtags = hashtags;
}
/**
* Returns the query as a stringfor the retrieval of relevant content to the
* dysco from solr
*
* @return String
*/
public String getSolrQueryString() {
return solrQueryString;
}
/**
* Sets the solr query as a string for the retrieval of relevant content
*
* @param solrQuery
*/
public void setSolrQueryString(String solrQueryString) {
this.solrQueryString = solrQueryString;
}
public List<String> getPrimalSolrQueriesString(){
return primalSolrQueriesString;
}
public List<String> getSolrQueriesString(){
return solrQueriesString;
}
public List<String> getSolrQueriesScore(){
return solrQueriesScore;
}
public void setPrimalSolrQueriesString(List<String> primalSolrQueriesString){
this.primalSolrQueriesString = primalSolrQueriesString;
}
public void setSolrQueriesString(List<String> solrQueriesString){
this.solrQueriesString = solrQueriesString;
}
public void setSolrQueriesScore(List<String> solrQueriesScore){
this.solrQueriesScore = solrQueriesScore;
}
/**
* Returns the trending value that shows dysco's trending evolution (can be
* 0,1,2)
*
* @return
*/
public int getTrending() {
return trending;
}
/**
* Sets the trending value that shows dysco's trending evolution (can be
* 0,1,2)
*
* @param trending
*/
public void setTrending(int trending) {
this.trending = trending;
}
/**
* Returns the date that dysco was last updated.
*
* @return
*/
public Date getUpdateDate() {
return updateDate;
}
/**
* Sets the date that dysco was last updated.
*
* @return
*/
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
/**
* Returns the type of the dysco
*
* @return dyscoType
*/
public String getDyscoType() {
return dyscoType;
}
/**
* Sets the type of the dysco (CUSTOM/TRENDING)
*
* @param dyscoType
*/
public void setDyscoType(String dyscoType) {
this.dyscoType = dyscoType;
}
}
| src/main/java/eu/socialsensor/framework/client/search/solr/SolrDysco.java | package eu.socialsensor.framework.client.search.solr;
import eu.socialsensor.framework.common.domain.Query;
import eu.socialsensor.framework.common.domain.dysco.Dysco;
import eu.socialsensor.framework.common.domain.dysco.Dysco.DyscoType;
import eu.socialsensor.framework.common.domain.dysco.Entity;
import eu.socialsensor.framework.common.domain.dysco.Entity.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.beans.Field;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
*
* @author etzoannos - [email protected]
*/
public class SolrDysco {
public final Logger logger = Logger.getLogger(SolrDysco.class);
//The id of the dysco
@Field(value = "id")
private String id;
//The creation date of the dysco
@Field(value = "creationDate")
private Date creationDate;
//The title of the dysco
@Field(value = "title")
private String title;
//The score that shows how trending the dysco is
@Field(value = "dyscoScore")
private Double score = 0d;
//The type of the dysco (CUSTOM/TRENDING)
@Field(value = "dyscoType")
private String dyscoType;
//Fields holding the information about the main context
//of the items that constitute the dysco
//The extracted entities from items' content
//all 6 refer to the 3 types of entities and their weights in the dysco
@Field(value = "persons")
private List<String> persons = new ArrayList<String>();
@Field(value = "locations")
private List<String> locations = new ArrayList<String>();
@Field(value = "organizations")
private List<String> organizations = new ArrayList<String>();
//The users that contribute in social networks to dysco's topic
@Expose
@SerializedName(value = "contributors")
private List<String> contributors = new ArrayList<String>();
//The extracted keywords from items' content with their assigned weights
@Field(value = "keywords")
private List<String> keywords = new ArrayList<String>();
//The extracted hashtags from items' content with their assigned weights
@Field(value = "hashtags")
private List<String> hashtags = new ArrayList<String>();
//The query that will be used for retrieving relevant content to the Dysco from Solr
@Field(value = "solrQueryString")
private String solrQueryString;
@Field(value = "solrQueriesString")
private List<String> solrQueriesString = new ArrayList<String>();
@Field(value = "primalSolrQueriesString")
private List<String> primalSolrQueriesString = new ArrayList<String>();
@Field(value = "solrQueriesScore")
private List<String> solrQueriesScore = new ArrayList<String>();
//The variable can get values 0,1,2 and shows dysco's trending evolution.
@Field(value = "trending")
private int trending;
//The date that the dysco was last created (updated because similar dyscos existed in the past)
@Field(value = "updateDate")
private Date updateDate;
@Field(value = "listId")
private String listId;
public SolrDysco() {
id = UUID.randomUUID().toString();
}
public SolrDysco(Dysco dysco) {
id = dysco.getId();
creationDate = dysco.getCreationDate();
title = dysco.getTitle();
score = dysco.getScore();
dyscoType = dysco.getDyscoType().toString();
List<Entity> dyscoEntities = dysco.getEntities();
for (Entity entity : dyscoEntities) {
if (entity.getType().equals(Type.LOCATION)) {
locations.add(entity.getName());
}
if (entity.getType().equals(Type.PERSON)) {
persons.add(entity.getName());
}
if (entity.getType().equals(Type.ORGANIZATION)) {
organizations.add(entity.getName());
}
}
contributors = dysco.getContributors();
for (Map.Entry<String, Double> entry : dysco.getKeywords().entrySet()) {
keywords.add(entry.getKey());
}
for (Map.Entry<String, Double> entry : dysco.getHashtags().entrySet()) {
hashtags.add(entry.getKey());
}
solrQueryString = dysco.getSolrQueryString();
for(Query query : dysco.getPrimalSolrQueries()){
//logger.info("query name: "+query.getName());
//logger.info("query score: "+query.getScore().toString());
primalSolrQueriesString.add(query.getName());
}
//logger.info("DYSCO QUERIES : "+dysco.getSolrQueries().size());
for(Query query : dysco.getSolrQueries()){
//logger.info("query name: "+query.getName());
//logger.info("query score: "+query.getScore().toString());
solrQueriesString.add(query.getName());
solrQueriesScore.add(query.getScore().toString());
}
for(Query query : dysco.getPrimalSolrQueries()){
primalSolrQueriesString.add(query.getName());
}
trending = dysco.getTrending();
updateDate = dysco.getUpdateDate();
listId = dysco.getListId();
}
public Dysco toDysco() {
Dysco dysco = new Dysco();
dysco.setId(id);
dysco.setCreationDate(creationDate);
dysco.setTitle(title);
dysco.setScore(score);
if (dyscoType.equals("CUSTOM")) {
dysco.setDyscoType(DyscoType.CUSTOM);
} else {
dysco.setDyscoType(DyscoType.TRENDING);
}
if (persons != null) {
for (String person : persons) {
Entity dyscoEntity = new Entity(person, 0.0, Type.PERSON);
dysco.addEntity(dyscoEntity);
}
}
if (locations != null) {
for (String location : locations) {
Entity dyscoEntity = new Entity(location, 0.0, Type.LOCATION);
dysco.addEntity(dyscoEntity);
}
}
if (organizations != null) {
for (String organization : organizations) {
Entity dyscoEntity = new Entity(organization, 0.0, Type.ORGANIZATION);
dysco.addEntity(dyscoEntity);
}
}
dysco.setContributors(contributors);
if (keywords != null) {
for (String keyword : keywords) {
dysco.addKeyword(keyword, 0.0);
}
}
if (hashtags != null) {
for (String hashtag : hashtags) {
dysco.addHashtag(hashtag, 0.0);
}
}
dysco.setSolrQueryString(solrQueryString);
List<Query> queries = new ArrayList<Query>();
for(int i=0;i<solrQueriesString.size();i++){
Query query = new Query();
query.setName(solrQueriesString.get(i));
query.setScore(Double.parseDouble(solrQueriesScore.get(i)));
queries.add(query);
}
dysco.setSolrQueries(queries);
dysco.setTrending(trending);
dysco.setUpdateDate(updateDate);
dysco.setListId(listId);
return dysco;
}
/**
* Returns the id of the dysco
*
* @return String
*/
public String getId() {
return id;
}
/**
* Sets the id of the dysco
*
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* Returns the creation date of the dysco
*
* @return Date
*/
public Date getCreationDate() {
return creationDate;
}
/**
* Sets the creation date of the dysco
*
* @param creationDate
*/
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
/**
* Returns the title of the dysco
*
* @return String
*/
public String getTitle() {
return title;
}
/**
* Sets the title of the dysco
*
* @param Title
*/
public void setTitle(String Title) {
this.title = Title;
}
/**
* Returns the score of the dysco
*
* @return Float
*/
public Double getScore() {
return score;
}
/**
* Sets the score of the dysco
*
* @param score
*/
public void setScore(Double score) {
this.score = score;
}
/**
* Returns the list of names of the Entities that are Persons inside the
* dysco
*
* @return List of String
*/
public List<String> getPersons() {
return persons;
}
/**
* Sets the list of names of the Entities that are Persons inside the dysco
*
* @param persons
*/
public void setPersons(List<String> persons) {
this.persons = persons;
}
/**
* Returns the list of names of the Entities that are Locations inside the
* dysco
*
* @return
*/
public List<String> getLocations() {
return locations;
}
/**
* Sets the list of names of the Entities that are Locations inside the
* dysco
*
* @param locations
*/
public void setLocations(List<String> locations) {
this.locations = locations;
}
/**
* Returns the list of names of the Entities that are Organizations inside
* the dysco
*
* @return List of String
*/
public List<String> getOrganizations() {
return organizations;
}
/**
* Sets the list of names of the Entities that are Organizations inside the
* dysco
*
* @param organizations
*/
public void setOrganizations(List<String> organizations) {
this.organizations = organizations;
}
/**
* Returns the list of contributors for the dysco
*
* @return List of String
*/
public List<String> getContributors() {
return contributors;
}
/**
* Sets the contributors for the dysco
*
* @param contributors
*/
public void setContributors(List<String> contributors) {
this.contributors = contributors;
}
/**
* Returns the keywords of the dysco
*
* @return List of String
*/
public List<String> getKeywords() {
return keywords;
}
/**
* Sets the keywords of the dysco
*
* @param keywords
*/
public void setKeywords(List<String> keywords) {
this.keywords = keywords;
}
/**
* Returns the hashtags of the dysco
*
* @return List of String
*/
public List<String> getHashtags() {
return hashtags;
}
/**
* Sets the hashtags of the dysco
*
* @param hashtags
*/
public void setHashtags(List<String> hashtags) {
this.hashtags = hashtags;
}
/**
* Returns the query as a stringfor the retrieval of relevant content to the
* dysco from solr
*
* @return String
*/
public String getSolrQueryString() {
return solrQueryString;
}
/**
* Sets the solr query as a string for the retrieval of relevant content
*
* @param solrQuery
*/
public void setSolrQueryString(String solrQueryString) {
this.solrQueryString = solrQueryString;
}
public List<String> getPrimalSolrQueriesString(){
return primalSolrQueriesString;
}
public List<String> getSolrQueriesString(){
return solrQueriesString;
}
public List<String> getSolrQueriesScore(){
return solrQueriesScore;
}
public void setPrimalSolrQueriesString(List<String> primalSolrQueriesString){
this.primalSolrQueriesString = primalSolrQueriesString;
}
public void setSolrQueriesString(List<String> solrQueriesString){
this.solrQueriesString = solrQueriesString;
}
public void setSolrQueriesScore(List<String> solrQueriesScore){
this.solrQueriesScore = solrQueriesScore;
}
/**
* Returns the trending value that shows dysco's trending evolution (can be
* 0,1,2)
*
* @return
*/
public int getTrending() {
return trending;
}
/**
* Sets the trending value that shows dysco's trending evolution (can be
* 0,1,2)
*
* @param trending
*/
public void setTrending(int trending) {
this.trending = trending;
}
/**
* Returns the date that dysco was last updated.
*
* @return
*/
public Date getUpdateDate() {
return updateDate;
}
/**
* Sets the date that dysco was last updated.
*
* @return
*/
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
/**
* Returns the type of the dysco
*
* @return dyscoType
*/
public String getDyscoType() {
return dyscoType;
}
/**
* Sets the type of the dysco (CUSTOM/TRENDING)
*
* @param dyscoType
*/
public void setDyscoType(String dyscoType) {
this.dyscoType = dyscoType;
}
}
| removed duplicate primal solr queries addition | src/main/java/eu/socialsensor/framework/client/search/solr/SolrDysco.java | removed duplicate primal solr queries addition | <ide><path>rc/main/java/eu/socialsensor/framework/client/search/solr/SolrDysco.java
<ide> solrQueriesString.add(query.getName());
<ide> solrQueriesScore.add(query.getScore().toString());
<ide> }
<del> for(Query query : dysco.getPrimalSolrQueries()){
<del>
<del> primalSolrQueriesString.add(query.getName());
<del>
<del> }
<del>
<ide>
<ide> trending = dysco.getTrending();
<ide> |
|
Java | mit | 84d56f33b234cf78b11779fb7907948e7e615243 | 0 | satoshinm/WebSandboxMC | package io.github.satoshinm.WebSandboxMC.bridge;
import io.github.satoshinm.WebSandboxMC.Settings;
import io.github.satoshinm.WebSandboxMC.ws.WebSocketServerThread;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Furnace;
import org.bukkit.block.Sign;
import org.bukkit.material.Directional;
import org.bukkit.material.MaterialData;
import org.bukkit.material.Sapling;
import org.bukkit.material.Wool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
/**
* Bridges blocks in the world, translates between coordinate systems
*/
public class BlockBridge {
public WebSocketServerThread webSocketServerThread;
private final int x_center, y_center, z_center, radius, y_offset;
public final World world;
public Location spawnLocation;
private boolean allowBreakPlaceBlocks;
private boolean allowSigns;
private Map<Material, Integer> blocksToWeb;
private int blocksToWebMissing; // unknown/unsupported becomes cloud, if key missing
private boolean warnMissing;
private List<Material> unbreakableBlocks;
private String textureURL;
public BlockBridge(WebSocketServerThread webSocketServerThread, Settings settings) {
this.webSocketServerThread = webSocketServerThread;
this.x_center = settings.x_center;
this.y_center = settings.y_center;
this.z_center = settings.z_center;
this.radius = settings.radius;
this.y_offset = settings.y_offset;
if (settings.world == null || "".equals(settings.world)) {
this.world = Bukkit.getWorlds().get(0);
} else {
this.world = Bukkit.getWorld(settings.world);
}
if (this.world == null) {
throw new IllegalArgumentException("World not found: " + settings.world);
}
// TODO: configurable spawn within range of sandbox, right now, it is the center of the sandbox
this.spawnLocation = new Location(this.world, this.x_center, this.y_center, this.z_center);
this.allowBreakPlaceBlocks = settings.allowBreakPlaceBlocks;
this.allowSigns = settings.allowSigns;
this.blocksToWeb = new HashMap<Material, Integer>();
this.blocksToWebMissing = 16; // unknown/unsupported becomes cloud
// Overrides from config, if any
for (String materialString : settings.blocksToWebOverride.keySet()) {
Object object = settings.blocksToWebOverride.get(materialString);
int n = 0;
if (object instanceof String) {
n = Integer.parseInt((String) object);
} else if (object instanceof Integer) {
n = (Integer) object;
} else {
webSocketServerThread.log(Level.WARNING, "blocks_to_web_override invalid integer ignored: "+n+", in "+object);
continue;
}
Material material = Material.getMaterial(materialString);
if (materialString.equals("missing")) {
this.blocksToWebMissing = n;
this.webSocketServerThread.log(Level.FINEST, "blocks_to_web_override missing value to set to: "+n);
} else {
if (material == null) {
webSocketServerThread.log(Level.WARNING, "blocks_to_web_override invalid material ignored: " + materialString);
continue;
}
this.blocksToWeb.put(material, n);
this.webSocketServerThread.log(Level.FINEST, "blocks_to_web_override: " + material + " = " + n);
}
}
this.warnMissing = settings.warnMissing;
this.unbreakableBlocks = new ArrayList<Material>();
for (String materialString : settings.unbreakableBlocks) {
Material material = Material.getMaterial(materialString);
if (material == null) {
webSocketServerThread.log(Level.WARNING, "unbreakable_blocks invalid material ignored: " + materialString);
continue;
}
this.unbreakableBlocks.add(material);
}
this.textureURL = settings.textureURL;
}
// Send the client the initial section of the world when they join
public void sendWorld(final Channel channel) {
if (textureURL != null) {
webSocketServerThread.sendLine(channel, "t," + textureURL);
}
boolean thereIsAWorld = false;
// TODO: bulk block update compressed, for efficiency (this is very efficient, but surprisingly works!)
for (int i = -radius; i < radius; ++i) {
for (int j = -radius; j < radius; ++j) {
for (int k = -radius; k < radius; ++k) {
Block block = world.getBlockAt(i + x_center, j + y_center, k + z_center);
//int type = toWebBlockType(block.getType(), block.getData());
//webSocketServerThread.sendLine(channel, "B,0,0," + (i + radius) + "," + (j + radius + y_offset) + "," + (k + radius) + "," + type);
thereIsAWorld |= setBlockUpdate(block.getLocation(), block.getType(), block.getState());
}
}
}
webSocketServerThread.sendLine(channel,"K,0,0,1");
webSocketServerThread.sendLine(channel, "R,0,0");
if (!thereIsAWorld) {
webSocketServerThread.sendLine(channel, "T,No blocks sent (server misconfiguration, check x/y/z_center)");
webSocketServerThread.log(Level.WARNING, "No valid blocks were found centered around ("+
x_center + "," + y_center + "," + z_center + ") radius " + radius +
", try changing these values or blocks_to_web in the configuration. All blocks were air or missing!");
}
// Move player on top of the new blocks
int x_start = radius;
int y_start = world.getHighestBlockYAt(x_center, z_center) - radius - y_offset;
int z_start = radius;
int rotation_x = 0;
int rotation_y = 0;
webSocketServerThread.sendLine(channel, "U,1," + x_start + "," + y_start + "," + z_start + "," + rotation_x + "," + rotation_y );
}
public boolean withinSandboxRange(Location location) {
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
if (x >= x_center + radius || x < x_center - radius) {
return false;
}
if (y >= y_center + radius || y < y_center - radius) {
return false;
}
if (z >= z_center + radius || z < z_center - radius) {
return false;
}
return true;
}
public Location toBukkitLocation(int x, int y, int z) {
x += -radius + x_center;
y += -radius + y_center - y_offset;
z += -radius + z_center;
Location location = new Location(world, x, y, z);
return location;
}
public Location toBukkitPlayerLocation(double x, double y, double z) {
x += -radius + x_center;
y += -radius + y_center - y_offset;
z += -radius + z_center;
Location location = new Location(world, x, y, z);
return location;
}
public int toWebLocationBlockX(Location location) { return location.getBlockX() - (-radius + x_center); }
public int toWebLocationBlockY(Location location) { return location.getBlockY() - (-radius + y_center - y_offset); }
public int toWebLocationBlockZ(Location location) { return location.getBlockZ() - (-radius + z_center); }
public double toWebLocationEntityX(Location location) { return location.getX() - (-radius + x_center); }
public double toWebLocationEntityY(Location location) { return location.getY() - (-radius + y_center - y_offset); }
public double toWebLocationEntityZ(Location location) { return location.getZ() - (-radius + z_center); }
// Handle the web client changing a block, update the bukkit world
public void clientBlockUpdate(ChannelHandlerContext ctx, int x, int y, int z, int type) {
if (!allowBreakPlaceBlocks) {
webSocketServerThread.sendLine(ctx.channel(), "T,Breaking/placing blocks not allowed");
// TODO: set back to original block to revert on client
return;
}
Location location = toBukkitLocation(x, y, z);
if (!withinSandboxRange(location)) {
webSocketServerThread.log(Level.FINEST, "client tried to modify outside of sandbox! "+location); // not severe, since not prevented client-side
webSocketServerThread.sendLine(ctx.channel(), "T,You cannot build at ("+x+","+y+","+z+")");
// TODO: Clear the block, fix this (set to air)
/*
webSocketServerThread.sendLine(ctx.channel(), "B,0,0,"+ox+","+oy+","+oz+",0");
webSocketServerThread.sendLine(ctx.channel(), "R,0,0");
*/
return;
}
Block previousBlock = location.getBlock();
Material previousMaterial = previousBlock.getType();
if (unbreakableBlocks.contains(previousMaterial)) {
webSocketServerThread.log(Level.FINEST, "client tried to change unbreakable block at " +
location + " of type previousMaterial="+previousMaterial);
webSocketServerThread.sendLine(ctx.channel(), "T,You cannot break blocks of type " + previousMaterial);
// Revert on client
int previousType = toWebBlockType(previousMaterial, null);
webSocketServerThread.sendLine(ctx.channel(), "B,0,0,"+x+","+y+","+z+","+previousType);
webSocketServerThread.sendLine(ctx.channel(), "R,0,0");
return;
}
Block block = world.getBlockAt(location);
if (block == null) {
webSocketServerThread.log(Level.WARNING, "web client no such block at " + location); // does this happen?
return;
}
webSocketServerThread.log(Level.FINEST, "setting block at "+location);
BlockState blockState = block.getState();
toBukkitBlockType(type, blockState);
// Notify other web clients - note they will have the benefit of seeing the untranslated block (feature or bug?)
webSocketServerThread.broadcastLineExcept(ctx.channel().id(), "B,0,0," + x + "," + y + "," + z + "," + type);
webSocketServerThread.broadcastLineExcept(ctx.channel().id(), "R,0,0");
}
// Handle the bukkit world changing a block, tell all web clients and refresh
public void notifyBlockUpdate(Location location, Material material, BlockState blockState) {
webSocketServerThread.log(Level.FINEST, "bukkit block at "+location+" was set to "+material);
if (!withinSandboxRange(location)) {
// Clients don't need to know about every block change on the server, only within the sandbox
return;
}
setBlockUpdate(location, material, blockState);
webSocketServerThread.broadcastLine("R,0,0");
}
private boolean setBlockUpdate(Location location, Material material, BlockState blockState) {
// Send to all web clients to let them know it changed using the "B," command
int type = toWebBlockType(material, blockState);
boolean substantial;
if (type == -1) {
if (warnMissing) {
webSocketServerThread.log(Level.WARNING, "Block type missing from blocks_to_web: " + material + " at " + location);
}
type = blocksToWebMissing;
substantial = false;
} else if (type == 0) {
substantial = false;
} else {
substantial = true;
}
int x = toWebLocationBlockX(location);
int y = toWebLocationBlockY(location);
int z = toWebLocationBlockZ(location);
webSocketServerThread.broadcastLine("B,0,0,"+x+","+y+","+z+","+type);
int light_level = toWebLighting(material, blockState);
if (light_level != 0) {
webSocketServerThread.broadcastLine("L,0,0,"+x+","+y+","+z+"," + light_level);
}
if (material == Material.WALL_SIGN || material == Material.SIGN_POST) {
Block block = location.getWorld().getBlockAt(location);
if (blockState instanceof Sign) {
Sign sign = (Sign) blockState;
notifySignChange(block.getLocation(), block.getType(), block.getState(), sign.getLines());
}
}
webSocketServerThread.log(Level.FINEST, "notified block update: ("+x+","+y+","+z+") to "+type);
return substantial; // was something "real" set? (not air, not missing)
}
private int toWebLighting(Material material, BlockState blockState) {
// See http://minecraft.gamepedia.com/Light#Blocks
// Note not all of these may be fully supported yet
switch (material) {
case BEACON:
case ENDER_PORTAL:
case FIRE:
case GLOWSTONE:
case JACK_O_LANTERN:
case LAVA:
case REDSTONE_LAMP_ON: // TODO: get notified when toggles on/off
case SEA_LANTERN:
case END_ROD:
return 15;
case TORCH:
return 14;
case BURNING_FURNACE:
return 13;
case PORTAL:
return 11;
case GLOWING_REDSTONE_ORE:
return 9;
case ENDER_CHEST:
case REDSTONE_TORCH_ON:
return 7;
case MAGMA:
return 3;
case BREWING_STAND:
case BROWN_MUSHROOM:
case DRAGON_EGG:
case ENDER_PORTAL_FRAME:
return 1;
default:
return 0;
}
}
// The web client represents directional blocks has four block ids
private int getDirectionalOrthogonalWebBlock(int base, Directional directional) {
switch (directional.getFacing()) {
case NORTH: return base+0;
case SOUTH: return base+1;
case WEST: return base+2;
case EAST: return base+3;
default:
webSocketServerThread.log(Level.WARNING, "unknown orthogonal directional rotation: "+directional.getFacing());
return base;
}
}
// Translate web<->bukkit blocks
// TODO: refactor to remove all bukkit dependency in this class (enums strings?), generalize to can support others
private int toWebBlockType(Material material, BlockState blockState) {
if (blocksToWeb.containsKey(material)) {
return blocksToWeb.get(material);
}
MaterialData materialData = blockState != null ? blockState.getData() : null;
switch (material) {
case AIR: return 0;
case GRASS: return 1;
case SAND: return 2;
case SMOOTH_BRICK: return 3; // stone brick :0
//blocksToWebDefault.put(, 76; // TODO: mossy stone brick, :1
//blocksToWebDefault.put(, 77; // TODO: cracked stone brick, :2
case BRICK: return 4;
case LOG: return 5;
case LOG_2: return 5; // wood
case GOLD_ORE: return 70;
case IRON_ORE: return 71;
case COAL_ORE: return 72;
case LAPIS_ORE: return 73;
case LAPIS_BLOCK: return 74;
case DIAMOND_ORE: return 48;
case REDSTONE_ORE: return 49;
// TODO: more ores, for now, showing as stone
case QUARTZ_ORE: return 6;
case STONE: return 6;
case DIRT: return 7;
case WOOD: return 8; // plank
case SNOW: return 9;
case GLASS: return 10;
case COBBLESTONE: return 11;
// TODO: return light stone (12);
// TODO: return dark stone (13);
case CHEST: return 14;
case LEAVES: return 15;
case LEAVES_2: return 15;
// TODO: return cloud (16);
case DOUBLE_PLANT: return 17; // TODO: other double plants, but a lot look like longer long grass
case LONG_GRASS: return 17; // tall grass
//blocksToWebDefault.put(, 29; // TODO: fern
case YELLOW_FLOWER: return 18;
case RED_ROSE: return 19;
//TODO case CHORUS_FLOWER: return 20;
case SAPLING: {
if (materialData instanceof Sapling) {
Sapling sapling = (Sapling) materialData;
switch (sapling.getSpecies()) {
default:
case GENERIC: return 20; // oak sapling
case REDWOOD: return 30; // spruce sapling ("darker barked/leaves tree species")
case BIRCH: return 31; // birch sapling
}
}
return 20; // oak sapling
}
// TODO: return sunflower (21);
// TODO: return white flower (22);
// TODO: return blue flower (23);
case WOOL:
{
if (materialData instanceof Wool) {
Wool wool = (Wool) materialData;
switch (wool.getColor()) {
case WHITE: return 32;
case ORANGE: return 33;
case MAGENTA: return 34;
case LIGHT_BLUE: return 35;
case YELLOW: return 36;
case LIME: return 37;
case PINK: return 38;
case GRAY: return 39;
case SILVER: return 40; // light gray
case CYAN: return 41;
case PURPLE: return 42;
case BLUE: return 43;
case BROWN: return 44;
case GREEN: return 45;
case RED: return 46;
default:
case BLACK: return 47;
}
}
return 47;
}
case WALL_SIGN: return 0; // air, since text is written on block behind it
case SIGN_POST: return 8; // plank TODO: return sign post model
// Light sources (nonzero toWebLighting()) TODO: return different textures? + allow placement, distinct blocks
case GLOWSTONE: return 64; // #define GLOWING_STONE
case SEA_LANTERN: return 35; // light blue wool
case TORCH: return 21; // sunflower, looks kinda like a torch
case REDSTONE_TORCH_OFF: return 19;
case REDSTONE_TORCH_ON: return 19; // red flower, vaguely a torch
// Liquids - currently using color blocks as placeholders since they appear too often
case STATIONARY_WATER: return 35; // light blue wool
case WATER: return 35; // light blue wool
case STATIONARY_LAVA: return 35; // orange wool
case LAVA: return 35; // orange wool
// TODO: support more blocks by default
case BEDROCK: return 65;
case GRAVEL: return 66;
case IRON_BLOCK: return 67;
case GOLD_BLOCK: return 68;
case DIAMOND_BLOCK: return 69;
case SANDSTONE: return 75;
case BOOKSHELF: return 50;
case MOSSY_COBBLESTONE: return 51;
case OBSIDIAN: return 52;
case WORKBENCH: return 53;
case FURNACE: {
if (materialData instanceof org.bukkit.material.Furnace) {
org.bukkit.material.Furnace furnace = (org.bukkit.material.Furnace) materialData;
return getDirectionalOrthogonalWebBlock(90, furnace); // 90, 91, 92, 93
}
return 90;
//return 54; // old
}
case BURNING_FURNACE: { // TODO: refactor with above, same code! different base block
if (materialData instanceof org.bukkit.material.Furnace) {
org.bukkit.material.Furnace furnace = (org.bukkit.material.Furnace) materialData;
return getDirectionalOrthogonalWebBlock(94, furnace); // 94, 95, 96, 97
}
return 94;
//return 55; // old
}
case MOB_SPAWNER: return 56;
case SNOW_BLOCK: return 57;
case ICE: return 58;
case CLAY: return 59;
case JUKEBOX: return 60;
case CACTUS: return 61;
case MYCEL: return 62;
case NETHERRACK: return 63;
case SPONGE: return 24;
case MELON_BLOCK: return 25;
case ENDER_STONE: return 26;
case TNT: return 27;
case EMERALD_BLOCK: return 28;
case PUMPKIN: return 78; // TODO: face
case JACK_O_LANTERN: return 79; // TODO: face side
case HUGE_MUSHROOM_1: return 80; // brown TODO: data
case HUGE_MUSHROOM_2: return 81; // red TODO: data
case COMMAND: return 82;
case EMERALD_ORE: return 83;
case SOUL_SAND: return 84;
case NETHER_BRICK: return 85;
case SOIL: return 86; // wet farmland TODO: dry farmland (87)
case REDSTONE_LAMP_OFF: return 88;
case REDSTONE_LAMP_ON: return 89;
default: return this.blocksToWebMissing;
}
}
// Mutate blockState to block of type type
private void toBukkitBlockType(int type, BlockState blockState) {
Material material = null;
MaterialData materialData = null;
switch (type) {
case 0: material = Material.AIR; break;
case 1: material = Material.GRASS; break;
case 2: material = Material.SAND; break;
case 3: material = Material.SMOOTH_BRICK; break; // "smooth stone brick"
case 4: material = Material.BRICK; break;
case 5: material = Material.LOG; break;
case 6: material = Material.STONE; break; // "cement"
case 7: material = Material.DIRT; break;
case 8: material = Material.WOOD; break;
case 9: material = Material.SNOW_BLOCK; break;
case 10: material = Material.GLASS; break;
case 11: material = Material.COBBLESTONE; break;
//case 12: material = Material. light stone?
//case 13: material = Material. dark stone?
case 14: material = Material.CHEST; break;
case 15: material = Material.LEAVES; break;
//case 16: material = Material.clouds; break; // clouds
case 17: material = Material.LONG_GRASS; break;
case 18: material = Material.YELLOW_FLOWER; break;
case 19: material = Material.RED_ROSE; break;
case 20: material = Material.CHORUS_FLOWER; break;
case 21: material = Material.DOUBLE_PLANT; break; // sunflower
case 22: material = Material.RED_ROSE; break; // TODO: white flower
case 23: material = Material.YELLOW_FLOWER; break; // TODO: blue flower
// TODO: 24-31
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
case 38:
case 39:
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
material = Material.WOOL;
DyeColor color;
switch (type) {
default:
case 32: color = DyeColor.WHITE; break;
case 33: color = DyeColor.ORANGE; break;
case 34: color = DyeColor.MAGENTA; break;
case 35: color = DyeColor.LIGHT_BLUE; break;
case 36: color = DyeColor.YELLOW; break;
case 37: color = DyeColor.LIME; break;
case 38: color = DyeColor.PINK; break;
case 39: color = DyeColor.GRAY; break;
case 40: color = DyeColor.SILVER; break; // light gray
case 41: color = DyeColor.CYAN; break;
case 42: color = DyeColor.PURPLE; break;
case 43: color = DyeColor.BLUE; break;
case 44: color = DyeColor.BROWN; break;
case 45: color = DyeColor.GREEN; break;
case 46: color = DyeColor.RED; break;
case 47: color = DyeColor.BLACK; break;
}
materialData = new Wool(color);
break;
case 64: material = Material.GLOWSTONE; break;
default:
webSocketServerThread.log(Level.WARNING, "untranslated web block id "+type);
material = Material.DIAMOND_ORE; // placeholder TODO fix
}
if (unbreakableBlocks.contains(material)) {
webSocketServerThread.log(Level.WARNING, "client tried to place unplaceable block type "+type+ " from "+material);
return; // ignore, not reverting
}
if (material != null) {
blockState.setType(material);
if (materialData != null) {
blockState.setData(materialData);
}
boolean force = true;
boolean applyPhysics = false;
blockState.update(force, applyPhysics);
}
}
public void notifySignChange(Location location, Material material, BlockState blockState, String[] lines) {
int x = toWebLocationBlockX(location);
int y = toWebLocationBlockY(location);
int z = toWebLocationBlockZ(location);
byte data = blockState.getData().getData();
// data is packed bitfield, see http://minecraft.gamepedia.com/Sign#Block_data
// Craft's faces:
// 0 - west
// 1 - east
// 2 - north
// 3 - south
// 4 - top, rotated 1
// 5 - top, rotated 2
// 6 - top, rotated 3
// 7 - top, rotated 4
int face = 7;
if (material == Material.WALL_SIGN) {
// wallsigns, attached to block behind
switch (data) {
case 2: // north
face = 2; // north
z += 1;
break;
case 3: // south
face = 3; // south
z -= 1;
break;
case 4: // west
face = 0; // west
x += 1;
break;
case 5: // east
face = 1; // east
x -= 1;
break;
}
} else if (material == Material.SIGN_POST) {
// standing sign, on the block itself
// TODO: support more fine-grained directions, right now Craft only four cardinal
switch (data) {
case 0: // south
case 1: // south-southwest
case 2: // southwest
face = 3; // south
break;
case 3: // west-southwest
case 4: // west
case 5: // west-northwest
case 6: // northwest
face = 0; // west
break;
case 7: // north-northwest
case 8: // north
case 9: // north-northeast
case 10: // northeast
face = 2; // north
break;
case 11: // east-northeast
case 12: // east
case 13: // east-southeast
case 14: // southeast
case 15: // south-southeast
face = 1; // east
break;
}
}
webSocketServerThread.log(Level.FINEST, "sign change: "+location+", data="+data);
String text = "";
for (int i = 0; i < lines.length; ++i) {
text += lines[i] + " "; // TODO: support explicit newlines; Craft wraps sign text lines automatically
}
if (text.contains("\n")) {
// \n is used as a command terminator in the Craft protocol (but ',' is acceptable)
text = text.replaceAll("\n", " ");
}
webSocketServerThread.broadcastLine("S,0,0,"+x+","+y+","+z+","+face+","+text);
webSocketServerThread.broadcastLine("R,0,0");
}
public void clientNewSign(ChannelHandlerContext ctx, int x, int y, int z, int face, String text) {
if (!allowSigns) {
webSocketServerThread.sendLine(ctx.channel(), "T,Writing on signs is not allowed");
// TODO: revert on client
return;
}
byte data = 0;
switch (face) {
case 0: // west
data = 4; // west
x -= 1;
break;
case 1: // east
data = 5; // east
x += 1;
break;
case 2: // north
data = 2; // north
z -= 1;
break;
case 3: // south
data = 3; // south
z += 1;
break;
}
Location location = toBukkitLocation(x, y, z);
if (!withinSandboxRange(location)) {
webSocketServerThread.log(Level.FINEST, "client tried to write a sign outside sandbox range");
return;
}
Block block = location.getWorld().getBlockAt(location);
boolean applyPhysics = false;
block.setTypeIdAndData(Material.WALL_SIGN.getId(), data, applyPhysics);
webSocketServerThread.log(Level.FINEST, "setting sign at "+location+" data="+data);
BlockState blockState = block.getState();
if (!(blockState instanceof Sign)) {
webSocketServerThread.log(Level.WARNING, "failed to place sign at "+location);
return;
}
Sign sign = (Sign) blockState;
// TODO: text lines by 15 characters into 5 lines
sign.setLine(0, text);
sign.update(false, applyPhysics);
// SignChangeEvent not posted when signs created programmatically; notify web clients ourselves
notifySignChange(location, block.getType(), block.getState(), sign.getLines());
}
}
| src/main/java/io/github/satoshinm/WebSandboxMC/bridge/BlockBridge.java | package io.github.satoshinm.WebSandboxMC.bridge;
import io.github.satoshinm.WebSandboxMC.Settings;
import io.github.satoshinm.WebSandboxMC.ws.WebSocketServerThread;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Furnace;
import org.bukkit.block.Sign;
import org.bukkit.material.MaterialData;
import org.bukkit.material.Sapling;
import org.bukkit.material.Wool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
/**
* Bridges blocks in the world, translates between coordinate systems
*/
public class BlockBridge {
public WebSocketServerThread webSocketServerThread;
private final int x_center, y_center, z_center, radius, y_offset;
public final World world;
public Location spawnLocation;
private boolean allowBreakPlaceBlocks;
private boolean allowSigns;
private Map<Material, Integer> blocksToWeb;
private int blocksToWebMissing; // unknown/unsupported becomes cloud, if key missing
private boolean warnMissing;
private List<Material> unbreakableBlocks;
private String textureURL;
public BlockBridge(WebSocketServerThread webSocketServerThread, Settings settings) {
this.webSocketServerThread = webSocketServerThread;
this.x_center = settings.x_center;
this.y_center = settings.y_center;
this.z_center = settings.z_center;
this.radius = settings.radius;
this.y_offset = settings.y_offset;
if (settings.world == null || "".equals(settings.world)) {
this.world = Bukkit.getWorlds().get(0);
} else {
this.world = Bukkit.getWorld(settings.world);
}
if (this.world == null) {
throw new IllegalArgumentException("World not found: " + settings.world);
}
// TODO: configurable spawn within range of sandbox, right now, it is the center of the sandbox
this.spawnLocation = new Location(this.world, this.x_center, this.y_center, this.z_center);
this.allowBreakPlaceBlocks = settings.allowBreakPlaceBlocks;
this.allowSigns = settings.allowSigns;
this.blocksToWeb = new HashMap<Material, Integer>();
this.blocksToWebMissing = 16; // unknown/unsupported becomes cloud
// Overrides from config, if any
for (String materialString : settings.blocksToWebOverride.keySet()) {
Object object = settings.blocksToWebOverride.get(materialString);
int n = 0;
if (object instanceof String) {
n = Integer.parseInt((String) object);
} else if (object instanceof Integer) {
n = (Integer) object;
} else {
webSocketServerThread.log(Level.WARNING, "blocks_to_web_override invalid integer ignored: "+n+", in "+object);
continue;
}
Material material = Material.getMaterial(materialString);
if (materialString.equals("missing")) {
this.blocksToWebMissing = n;
this.webSocketServerThread.log(Level.FINEST, "blocks_to_web_override missing value to set to: "+n);
} else {
if (material == null) {
webSocketServerThread.log(Level.WARNING, "blocks_to_web_override invalid material ignored: " + materialString);
continue;
}
this.blocksToWeb.put(material, n);
this.webSocketServerThread.log(Level.FINEST, "blocks_to_web_override: " + material + " = " + n);
}
}
this.warnMissing = settings.warnMissing;
this.unbreakableBlocks = new ArrayList<Material>();
for (String materialString : settings.unbreakableBlocks) {
Material material = Material.getMaterial(materialString);
if (material == null) {
webSocketServerThread.log(Level.WARNING, "unbreakable_blocks invalid material ignored: " + materialString);
continue;
}
this.unbreakableBlocks.add(material);
}
this.textureURL = settings.textureURL;
}
// Send the client the initial section of the world when they join
public void sendWorld(final Channel channel) {
if (textureURL != null) {
webSocketServerThread.sendLine(channel, "t," + textureURL);
}
boolean thereIsAWorld = false;
// TODO: bulk block update compressed, for efficiency (this is very efficient, but surprisingly works!)
for (int i = -radius; i < radius; ++i) {
for (int j = -radius; j < radius; ++j) {
for (int k = -radius; k < radius; ++k) {
Block block = world.getBlockAt(i + x_center, j + y_center, k + z_center);
//int type = toWebBlockType(block.getType(), block.getData());
//webSocketServerThread.sendLine(channel, "B,0,0," + (i + radius) + "," + (j + radius + y_offset) + "," + (k + radius) + "," + type);
thereIsAWorld |= setBlockUpdate(block.getLocation(), block.getType(), block.getState());
}
}
}
webSocketServerThread.sendLine(channel,"K,0,0,1");
webSocketServerThread.sendLine(channel, "R,0,0");
if (!thereIsAWorld) {
webSocketServerThread.sendLine(channel, "T,No blocks sent (server misconfiguration, check x/y/z_center)");
webSocketServerThread.log(Level.WARNING, "No valid blocks were found centered around ("+
x_center + "," + y_center + "," + z_center + ") radius " + radius +
", try changing these values or blocks_to_web in the configuration. All blocks were air or missing!");
}
// Move player on top of the new blocks
int x_start = radius;
int y_start = world.getHighestBlockYAt(x_center, z_center) - radius - y_offset;
int z_start = radius;
int rotation_x = 0;
int rotation_y = 0;
webSocketServerThread.sendLine(channel, "U,1," + x_start + "," + y_start + "," + z_start + "," + rotation_x + "," + rotation_y );
}
public boolean withinSandboxRange(Location location) {
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
if (x >= x_center + radius || x < x_center - radius) {
return false;
}
if (y >= y_center + radius || y < y_center - radius) {
return false;
}
if (z >= z_center + radius || z < z_center - radius) {
return false;
}
return true;
}
public Location toBukkitLocation(int x, int y, int z) {
x += -radius + x_center;
y += -radius + y_center - y_offset;
z += -radius + z_center;
Location location = new Location(world, x, y, z);
return location;
}
public Location toBukkitPlayerLocation(double x, double y, double z) {
x += -radius + x_center;
y += -radius + y_center - y_offset;
z += -radius + z_center;
Location location = new Location(world, x, y, z);
return location;
}
public int toWebLocationBlockX(Location location) { return location.getBlockX() - (-radius + x_center); }
public int toWebLocationBlockY(Location location) { return location.getBlockY() - (-radius + y_center - y_offset); }
public int toWebLocationBlockZ(Location location) { return location.getBlockZ() - (-radius + z_center); }
public double toWebLocationEntityX(Location location) { return location.getX() - (-radius + x_center); }
public double toWebLocationEntityY(Location location) { return location.getY() - (-radius + y_center - y_offset); }
public double toWebLocationEntityZ(Location location) { return location.getZ() - (-radius + z_center); }
// Handle the web client changing a block, update the bukkit world
public void clientBlockUpdate(ChannelHandlerContext ctx, int x, int y, int z, int type) {
if (!allowBreakPlaceBlocks) {
webSocketServerThread.sendLine(ctx.channel(), "T,Breaking/placing blocks not allowed");
// TODO: set back to original block to revert on client
return;
}
Location location = toBukkitLocation(x, y, z);
if (!withinSandboxRange(location)) {
webSocketServerThread.log(Level.FINEST, "client tried to modify outside of sandbox! "+location); // not severe, since not prevented client-side
webSocketServerThread.sendLine(ctx.channel(), "T,You cannot build at ("+x+","+y+","+z+")");
// TODO: Clear the block, fix this (set to air)
/*
webSocketServerThread.sendLine(ctx.channel(), "B,0,0,"+ox+","+oy+","+oz+",0");
webSocketServerThread.sendLine(ctx.channel(), "R,0,0");
*/
return;
}
Block previousBlock = location.getBlock();
Material previousMaterial = previousBlock.getType();
if (unbreakableBlocks.contains(previousMaterial)) {
webSocketServerThread.log(Level.FINEST, "client tried to change unbreakable block at " +
location + " of type previousMaterial="+previousMaterial);
webSocketServerThread.sendLine(ctx.channel(), "T,You cannot break blocks of type " + previousMaterial);
// Revert on client
int previousType = toWebBlockType(previousMaterial, null);
webSocketServerThread.sendLine(ctx.channel(), "B,0,0,"+x+","+y+","+z+","+previousType);
webSocketServerThread.sendLine(ctx.channel(), "R,0,0");
return;
}
Block block = world.getBlockAt(location);
if (block == null) {
webSocketServerThread.log(Level.WARNING, "web client no such block at " + location); // does this happen?
return;
}
webSocketServerThread.log(Level.FINEST, "setting block at "+location);
BlockState blockState = block.getState();
toBukkitBlockType(type, blockState);
// Notify other web clients - note they will have the benefit of seeing the untranslated block (feature or bug?)
webSocketServerThread.broadcastLineExcept(ctx.channel().id(), "B,0,0," + x + "," + y + "," + z + "," + type);
webSocketServerThread.broadcastLineExcept(ctx.channel().id(), "R,0,0");
}
// Handle the bukkit world changing a block, tell all web clients and refresh
public void notifyBlockUpdate(Location location, Material material, BlockState blockState) {
webSocketServerThread.log(Level.FINEST, "bukkit block at "+location+" was set to "+material);
if (!withinSandboxRange(location)) {
// Clients don't need to know about every block change on the server, only within the sandbox
return;
}
setBlockUpdate(location, material, blockState);
webSocketServerThread.broadcastLine("R,0,0");
}
private boolean setBlockUpdate(Location location, Material material, BlockState blockState) {
// Send to all web clients to let them know it changed using the "B," command
int type = toWebBlockType(material, blockState);
boolean substantial;
if (type == -1) {
if (warnMissing) {
webSocketServerThread.log(Level.WARNING, "Block type missing from blocks_to_web: " + material + " at " + location);
}
type = blocksToWebMissing;
substantial = false;
} else if (type == 0) {
substantial = false;
} else {
substantial = true;
}
int x = toWebLocationBlockX(location);
int y = toWebLocationBlockY(location);
int z = toWebLocationBlockZ(location);
webSocketServerThread.broadcastLine("B,0,0,"+x+","+y+","+z+","+type);
int light_level = toWebLighting(material, blockState);
if (light_level != 0) {
webSocketServerThread.broadcastLine("L,0,0,"+x+","+y+","+z+"," + light_level);
}
if (material == Material.WALL_SIGN || material == Material.SIGN_POST) {
Block block = location.getWorld().getBlockAt(location);
if (blockState instanceof Sign) {
Sign sign = (Sign) blockState;
notifySignChange(block.getLocation(), block.getType(), block.getState(), sign.getLines());
}
}
webSocketServerThread.log(Level.FINEST, "notified block update: ("+x+","+y+","+z+") to "+type);
return substantial; // was something "real" set? (not air, not missing)
}
private int toWebLighting(Material material, BlockState blockState) {
// See http://minecraft.gamepedia.com/Light#Blocks
// Note not all of these may be fully supported yet
switch (material) {
case BEACON:
case ENDER_PORTAL:
case FIRE:
case GLOWSTONE:
case JACK_O_LANTERN:
case LAVA:
case REDSTONE_LAMP_ON: // TODO: get notified when toggles on/off
case SEA_LANTERN:
case END_ROD:
return 15;
case TORCH:
return 14;
case BURNING_FURNACE:
return 13;
case PORTAL:
return 11;
case GLOWING_REDSTONE_ORE:
return 9;
case ENDER_CHEST:
case REDSTONE_TORCH_ON:
return 7;
case MAGMA:
return 3;
case BREWING_STAND:
case BROWN_MUSHROOM:
case DRAGON_EGG:
case ENDER_PORTAL_FRAME:
return 1;
default:
return 0;
}
}
// Translate web<->bukkit blocks
// TODO: refactor to remove all bukkit dependency in this class (enums strings?), generalize to can support others
private int toWebBlockType(Material material, BlockState blockState) {
if (blocksToWeb.containsKey(material)) {
return blocksToWeb.get(material);
}
MaterialData materialData = blockState != null ? blockState.getData() : null;
switch (material) {
case AIR: return 0;
case GRASS: return 1;
case SAND: return 2;
case SMOOTH_BRICK: return 3; // stone brick :0
//blocksToWebDefault.put(, 76; // TODO: mossy stone brick, :1
//blocksToWebDefault.put(, 77; // TODO: cracked stone brick, :2
case BRICK: return 4;
case LOG: return 5;
case LOG_2: return 5; // wood
case GOLD_ORE: return 70;
case IRON_ORE: return 71;
case COAL_ORE: return 72;
case LAPIS_ORE: return 73;
case LAPIS_BLOCK: return 74;
case DIAMOND_ORE: return 48;
case REDSTONE_ORE: return 49;
// TODO: more ores, for now, showing as stone
case QUARTZ_ORE: return 6;
case STONE: return 6;
case DIRT: return 7;
case WOOD: return 8; // plank
case SNOW: return 9;
case GLASS: return 10;
case COBBLESTONE: return 11;
// TODO: return light stone (12);
// TODO: return dark stone (13);
case CHEST: return 14;
case LEAVES: return 15;
case LEAVES_2: return 15;
// TODO: return cloud (16);
case DOUBLE_PLANT: return 17; // TODO: other double plants, but a lot look like longer long grass
case LONG_GRASS: return 17; // tall grass
//blocksToWebDefault.put(, 29; // TODO: fern
case YELLOW_FLOWER: return 18;
case RED_ROSE: return 19;
//TODO case CHORUS_FLOWER: return 20;
case SAPLING: {
if (materialData instanceof Sapling) {
Sapling sapling = (Sapling) materialData;
switch (sapling.getSpecies()) {
default:
case GENERIC: return 20; // oak sapling
case REDWOOD: return 30; // spruce sapling ("darker barked/leaves tree species")
case BIRCH: return 31; // birch sapling
}
}
return 20; // oak sapling
}
// TODO: return sunflower (21);
// TODO: return white flower (22);
// TODO: return blue flower (23);
case WOOL:
{
if (materialData instanceof Wool) {
Wool wool = (Wool) materialData;
switch (wool.getColor()) {
case WHITE: return 32;
case ORANGE: return 33;
case MAGENTA: return 34;
case LIGHT_BLUE: return 35;
case YELLOW: return 36;
case LIME: return 37;
case PINK: return 38;
case GRAY: return 39;
case SILVER: return 40; // light gray
case CYAN: return 41;
case PURPLE: return 42;
case BLUE: return 43;
case BROWN: return 44;
case GREEN: return 45;
case RED: return 46;
default:
case BLACK: return 47;
}
}
return 47;
}
case WALL_SIGN: return 0; // air, since text is written on block behind it
case SIGN_POST: return 8; // plank TODO: return sign post model
// Light sources (nonzero toWebLighting()) TODO: return different textures? + allow placement, distinct blocks
case GLOWSTONE: return 64; // #define GLOWING_STONE
case SEA_LANTERN: return 35; // light blue wool
case TORCH: return 21; // sunflower, looks kinda like a torch
case REDSTONE_TORCH_OFF: return 19;
case REDSTONE_TORCH_ON: return 19; // red flower, vaguely a torch
// Liquids - currently using color blocks as placeholders since they appear too often
case STATIONARY_WATER: return 35; // light blue wool
case WATER: return 35; // light blue wool
case STATIONARY_LAVA: return 35; // orange wool
case LAVA: return 35; // orange wool
// TODO: support more blocks by default
case BEDROCK: return 65;
case GRAVEL: return 66;
case IRON_BLOCK: return 67;
case GOLD_BLOCK: return 68;
case DIAMOND_BLOCK: return 69;
case SANDSTONE: return 75;
case BOOKSHELF: return 50;
case MOSSY_COBBLESTONE: return 51;
case OBSIDIAN: return 52;
case WORKBENCH: return 53;
case FURNACE: {
if (materialData instanceof org.bukkit.material.Furnace) {
org.bukkit.material.Furnace furnace = (org.bukkit.material.Furnace) materialData;
switch (furnace.getFacing()) {
case NORTH: return 90;
case SOUTH: return 91;
case WEST: return 92;
case EAST: return 93;
default:
webSocketServerThread.log(Level.WARNING, "unknown furnace rotation: "+furnace.getFacing());
return 90;
}
}
return 90;
//return 54; // old
}
case BURNING_FURNACE: { // TODO: refactor with above, same code! different base block
if (materialData instanceof org.bukkit.material.Furnace) {
org.bukkit.material.Furnace furnace = (org.bukkit.material.Furnace) materialData;
switch (furnace.getFacing()) {
case NORTH: return 94;
case SOUTH: return 95;
case WEST: return 96;
case EAST: return 97;
default:
webSocketServerThread.log(Level.WARNING, "unknown furnace rotation: "+furnace.getFacing());
return 94;
}
}
return 94;
//return 55; // old
}
case MOB_SPAWNER: return 56;
case SNOW_BLOCK: return 57;
case ICE: return 58;
case CLAY: return 59;
case JUKEBOX: return 60;
case CACTUS: return 61;
case MYCEL: return 62;
case NETHERRACK: return 63;
case SPONGE: return 24;
case MELON_BLOCK: return 25;
case ENDER_STONE: return 26;
case TNT: return 27;
case EMERALD_BLOCK: return 28;
case PUMPKIN: return 78; // TODO: face
case JACK_O_LANTERN: return 79; // TODO: face side
case HUGE_MUSHROOM_1: return 80; // brown TODO: data
case HUGE_MUSHROOM_2: return 81; // red TODO: data
case COMMAND: return 82;
case EMERALD_ORE: return 83;
case SOUL_SAND: return 84;
case NETHER_BRICK: return 85;
case SOIL: return 86; // wet farmland TODO: dry farmland (87)
case REDSTONE_LAMP_OFF: return 88;
case REDSTONE_LAMP_ON: return 89;
default: return this.blocksToWebMissing;
}
}
// Mutate blockState to block of type type
private void toBukkitBlockType(int type, BlockState blockState) {
Material material = null;
MaterialData materialData = null;
switch (type) {
case 0: material = Material.AIR; break;
case 1: material = Material.GRASS; break;
case 2: material = Material.SAND; break;
case 3: material = Material.SMOOTH_BRICK; break; // "smooth stone brick"
case 4: material = Material.BRICK; break;
case 5: material = Material.LOG; break;
case 6: material = Material.STONE; break; // "cement"
case 7: material = Material.DIRT; break;
case 8: material = Material.WOOD; break;
case 9: material = Material.SNOW_BLOCK; break;
case 10: material = Material.GLASS; break;
case 11: material = Material.COBBLESTONE; break;
//case 12: material = Material. light stone?
//case 13: material = Material. dark stone?
case 14: material = Material.CHEST; break;
case 15: material = Material.LEAVES; break;
//case 16: material = Material.clouds; break; // clouds
case 17: material = Material.LONG_GRASS; break;
case 18: material = Material.YELLOW_FLOWER; break;
case 19: material = Material.RED_ROSE; break;
case 20: material = Material.CHORUS_FLOWER; break;
case 21: material = Material.DOUBLE_PLANT; break; // sunflower
case 22: material = Material.RED_ROSE; break; // TODO: white flower
case 23: material = Material.YELLOW_FLOWER; break; // TODO: blue flower
// TODO: 24-31
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
case 38:
case 39:
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
material = Material.WOOL;
DyeColor color;
switch (type) {
default:
case 32: color = DyeColor.WHITE; break;
case 33: color = DyeColor.ORANGE; break;
case 34: color = DyeColor.MAGENTA; break;
case 35: color = DyeColor.LIGHT_BLUE; break;
case 36: color = DyeColor.YELLOW; break;
case 37: color = DyeColor.LIME; break;
case 38: color = DyeColor.PINK; break;
case 39: color = DyeColor.GRAY; break;
case 40: color = DyeColor.SILVER; break; // light gray
case 41: color = DyeColor.CYAN; break;
case 42: color = DyeColor.PURPLE; break;
case 43: color = DyeColor.BLUE; break;
case 44: color = DyeColor.BROWN; break;
case 45: color = DyeColor.GREEN; break;
case 46: color = DyeColor.RED; break;
case 47: color = DyeColor.BLACK; break;
}
materialData = new Wool(color);
break;
case 64: material = Material.GLOWSTONE; break;
default:
webSocketServerThread.log(Level.WARNING, "untranslated web block id "+type);
material = Material.DIAMOND_ORE; // placeholder TODO fix
}
if (unbreakableBlocks.contains(material)) {
webSocketServerThread.log(Level.WARNING, "client tried to place unplaceable block type "+type+ " from "+material);
return; // ignore, not reverting
}
if (material != null) {
blockState.setType(material);
if (materialData != null) {
blockState.setData(materialData);
}
boolean force = true;
boolean applyPhysics = false;
blockState.update(force, applyPhysics);
}
}
public void notifySignChange(Location location, Material material, BlockState blockState, String[] lines) {
int x = toWebLocationBlockX(location);
int y = toWebLocationBlockY(location);
int z = toWebLocationBlockZ(location);
byte data = blockState.getData().getData();
// data is packed bitfield, see http://minecraft.gamepedia.com/Sign#Block_data
// Craft's faces:
// 0 - west
// 1 - east
// 2 - north
// 3 - south
// 4 - top, rotated 1
// 5 - top, rotated 2
// 6 - top, rotated 3
// 7 - top, rotated 4
int face = 7;
if (material == Material.WALL_SIGN) {
// wallsigns, attached to block behind
switch (data) {
case 2: // north
face = 2; // north
z += 1;
break;
case 3: // south
face = 3; // south
z -= 1;
break;
case 4: // west
face = 0; // west
x += 1;
break;
case 5: // east
face = 1; // east
x -= 1;
break;
}
} else if (material == Material.SIGN_POST) {
// standing sign, on the block itself
// TODO: support more fine-grained directions, right now Craft only four cardinal
switch (data) {
case 0: // south
case 1: // south-southwest
case 2: // southwest
face = 3; // south
break;
case 3: // west-southwest
case 4: // west
case 5: // west-northwest
case 6: // northwest
face = 0; // west
break;
case 7: // north-northwest
case 8: // north
case 9: // north-northeast
case 10: // northeast
face = 2; // north
break;
case 11: // east-northeast
case 12: // east
case 13: // east-southeast
case 14: // southeast
case 15: // south-southeast
face = 1; // east
break;
}
}
webSocketServerThread.log(Level.FINEST, "sign change: "+location+", data="+data);
String text = "";
for (int i = 0; i < lines.length; ++i) {
text += lines[i] + " "; // TODO: support explicit newlines; Craft wraps sign text lines automatically
}
if (text.contains("\n")) {
// \n is used as a command terminator in the Craft protocol (but ',' is acceptable)
text = text.replaceAll("\n", " ");
}
webSocketServerThread.broadcastLine("S,0,0,"+x+","+y+","+z+","+face+","+text);
webSocketServerThread.broadcastLine("R,0,0");
}
public void clientNewSign(ChannelHandlerContext ctx, int x, int y, int z, int face, String text) {
if (!allowSigns) {
webSocketServerThread.sendLine(ctx.channel(), "T,Writing on signs is not allowed");
// TODO: revert on client
return;
}
byte data = 0;
switch (face) {
case 0: // west
data = 4; // west
x -= 1;
break;
case 1: // east
data = 5; // east
x += 1;
break;
case 2: // north
data = 2; // north
z -= 1;
break;
case 3: // south
data = 3; // south
z += 1;
break;
}
Location location = toBukkitLocation(x, y, z);
if (!withinSandboxRange(location)) {
webSocketServerThread.log(Level.FINEST, "client tried to write a sign outside sandbox range");
return;
}
Block block = location.getWorld().getBlockAt(location);
boolean applyPhysics = false;
block.setTypeIdAndData(Material.WALL_SIGN.getId(), data, applyPhysics);
webSocketServerThread.log(Level.FINEST, "setting sign at "+location+" data="+data);
BlockState blockState = block.getState();
if (!(blockState instanceof Sign)) {
webSocketServerThread.log(Level.WARNING, "failed to place sign at "+location);
return;
}
Sign sign = (Sign) blockState;
// TODO: text lines by 15 characters into 5 lines
sign.setLine(0, text);
sign.update(false, applyPhysics);
// SignChangeEvent not posted when signs created programmatically; notify web clients ourselves
notifySignChange(location, block.getType(), block.getState(), sign.getLines());
}
}
| Refactor furnace getDirectionalOrthogonalWebBlock() from GH-61
| src/main/java/io/github/satoshinm/WebSandboxMC/bridge/BlockBridge.java | Refactor furnace getDirectionalOrthogonalWebBlock() from GH-61 | <ide><path>rc/main/java/io/github/satoshinm/WebSandboxMC/bridge/BlockBridge.java
<ide> import org.bukkit.block.BlockState;
<ide> import org.bukkit.block.Furnace;
<ide> import org.bukkit.block.Sign;
<add>import org.bukkit.material.Directional;
<ide> import org.bukkit.material.MaterialData;
<ide> import org.bukkit.material.Sapling;
<ide> import org.bukkit.material.Wool;
<ide> return 1;
<ide> default:
<ide> return 0;
<add> }
<add> }
<add>
<add> // The web client represents directional blocks has four block ids
<add> private int getDirectionalOrthogonalWebBlock(int base, Directional directional) {
<add> switch (directional.getFacing()) {
<add> case NORTH: return base+0;
<add> case SOUTH: return base+1;
<add> case WEST: return base+2;
<add> case EAST: return base+3;
<add> default:
<add> webSocketServerThread.log(Level.WARNING, "unknown orthogonal directional rotation: "+directional.getFacing());
<add> return base;
<ide> }
<ide> }
<ide>
<ide> case FURNACE: {
<ide> if (materialData instanceof org.bukkit.material.Furnace) {
<ide> org.bukkit.material.Furnace furnace = (org.bukkit.material.Furnace) materialData;
<del> switch (furnace.getFacing()) {
<del> case NORTH: return 90;
<del> case SOUTH: return 91;
<del> case WEST: return 92;
<del> case EAST: return 93;
<del> default:
<del> webSocketServerThread.log(Level.WARNING, "unknown furnace rotation: "+furnace.getFacing());
<del> return 90;
<del> }
<add> return getDirectionalOrthogonalWebBlock(90, furnace); // 90, 91, 92, 93
<ide> }
<ide> return 90;
<ide> //return 54; // old
<ide> case BURNING_FURNACE: { // TODO: refactor with above, same code! different base block
<ide> if (materialData instanceof org.bukkit.material.Furnace) {
<ide> org.bukkit.material.Furnace furnace = (org.bukkit.material.Furnace) materialData;
<del> switch (furnace.getFacing()) {
<del> case NORTH: return 94;
<del> case SOUTH: return 95;
<del> case WEST: return 96;
<del> case EAST: return 97;
<del> default:
<del> webSocketServerThread.log(Level.WARNING, "unknown furnace rotation: "+furnace.getFacing());
<del> return 94;
<del> }
<add> return getDirectionalOrthogonalWebBlock(94, furnace); // 94, 95, 96, 97
<ide> }
<ide> return 94;
<ide> //return 55; // old |
|
JavaScript | apache-2.0 | 953689fedfa762af63fba709ec74eaa96a5f594d | 0 | naptha/tesseract.js,naptha/tesseract.js | /**
*
* Worker script for browser and node
*
* @fileoverview Worker script for browser and node
* @author Kevin Kwok <[email protected]>
* @author Guillermo Webster <[email protected]>
* @author Jerome Wu <[email protected]>
*/
require('regenerator-runtime/runtime');
const fileType = require('file-type');
const axios = require('axios');
const isURL = require('is-url');
const dump = require('./utils/dump');
const isBrowser = require('../utils/getEnvironment')('type') === 'browser';
const setImage = require('./utils/setImage');
const defaultParams = require('./constants/defaultParams');
const { log, setLogging } = require('../utils/log');
/*
* Tesseract Module returned by TesseractCore.
*/
let TessModule;
/*
* TessearctBaseAPI instance
*/
let api = null;
let latestJob;
let adapter = {};
let params = defaultParams;
const load = ({ workerId, jobId, payload: { options: { corePath, logging } } }, res) => {
setLogging(logging);
if (!TessModule) {
const Core = adapter.getCore(corePath, res);
res.progress({ workerId, status: 'initializing tesseract', progress: 0 });
Core({
TesseractProgress(percent) {
latestJob.progress({
workerId,
jobId,
status: 'recognizing text',
progress: Math.max(0, (percent - 30) / 70),
});
},
}).then((tessModule) => {
TessModule = tessModule;
res.progress({ workerId, status: 'initialized tesseract', progress: 1 });
res.resolve({ loaded: true });
});
} else {
res.resolve({ loaded: true });
}
};
const loadLanguage = async ({
workerId,
payload: {
langs,
options: {
langPath,
dataPath,
cachePath,
cacheMethod,
gzip = true,
},
},
},
res) => {
const loadAndGunzipFile = async (_lang) => {
const lang = typeof _lang === 'string' ? _lang : _lang.code;
const readCache = ['refresh', 'none'].includes(cacheMethod)
? () => Promise.resolve()
: adapter.readCache;
let data = null;
try {
const _data = await readCache(`${cachePath || '.'}/${lang}.traineddata`);
if (typeof _data !== 'undefined') {
log(`[${workerId}]: Load ${lang}.traineddata from cache`);
data = _data;
} else {
throw Error('Not found in cache');
}
} catch (e) {
log(`[${workerId}]: Load ${lang}.traineddata from ${langPath}`);
if (typeof _lang === 'string') {
let path = null;
if (isURL(langPath) || langPath.startsWith('moz-extension://') || langPath.startsWith('chrome-extension://') || langPath.startsWith('file://')) { /** When langPath is an URL */
path = langPath;
}
if (path !== null) {
const { data: _data } = await axios.get(
`${path}/${lang}.traineddata${gzip ? '.gz' : ''}`,
{ responseType: 'arraybuffer' },
);
data = _data;
} else {
data = await adapter.readCache(`${langPath}/${lang}.traineddata${gzip ? '.gz' : ''}`);
}
} else {
data = _lang.data; // eslint-disable-line
}
}
data = new Uint8Array(data);
const type = fileType(data);
if (typeof type !== 'undefined' && type.mime === 'application/gzip') {
data = adapter.gunzip(data);
}
if (TessModule) {
if (dataPath) {
try {
TessModule.FS.mkdir(dataPath);
} catch (err) {
res.reject(err.toString());
}
}
TessModule.FS.writeFile(`${dataPath || '.'}/${lang}.traineddata`, data);
}
if (['write', 'refresh', undefined].includes(cacheMethod)) {
await adapter.writeCache(`${cachePath || '.'}/${lang}.traineddata`, data);
}
return Promise.resolve(data);
};
res.progress({ workerId, status: 'loading language traineddata', progress: 0 });
try {
await Promise.all((typeof langs === 'string' ? langs.split('+') : langs).map(loadAndGunzipFile));
res.progress({ workerId, status: 'loaded language traineddata', progress: 1 });
res.resolve(langs);
} catch (err) {
if (isBrowser && err instanceof DOMException) {
/*
* For some reason google chrome throw DOMException in loadLang,
* while other browser is OK, for now we ignore this exception
* and hopefully to find the root cause one day.
*/
} else {
res.reject(err.toString());
}
}
};
const setParameters = ({ payload: { params: _params } }, res) => {
Object.keys(_params)
.filter(k => !k.startsWith('tessjs_'))
.forEach((key) => {
api.SetVariable(key, _params[key]);
});
params = { ...params, ..._params };
if (typeof res !== 'undefined') {
res.resolve(params);
}
};
const initialize = ({
workerId,
payload: { langs: _langs, oem },
}, res) => {
const langs = (typeof _langs === 'string')
? _langs
: _langs.map(l => ((typeof l === 'string') ? l : l.data)).join('+');
try {
res.progress({
workerId, status: 'initializing api', progress: 0,
});
if (api !== null) {
api.End();
}
api = new TessModule.TessBaseAPI();
api.Init(null, langs, oem);
params = defaultParams;
setParameters({ payload: { params } });
res.progress({
workerId, status: 'initialized api', progress: 1,
});
res.resolve();
} catch (err) {
res.reject(err.toString());
}
};
const recognize = ({ payload: { image, options: { rectangles = [] } } }, res) => {
try {
const ptr = setImage(TessModule, api, image);
rectangles.forEach(({
left, top, width, height,
}) => {
api.SetRectangle(left, top, width, height);
});
api.Recognize(null);
res.resolve(dump(TessModule, api, params));
TessModule._free(ptr);
} catch (err) {
res.reject(err.toString());
}
};
const getPDF = ({ payload: { title, textonly } }, res) => {
const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
pdfRenderer.BeginDocument(title);
pdfRenderer.AddImage(api);
pdfRenderer.EndDocument();
TessModule._free(pdfRenderer);
res.resolve(TessModule.FS.readFile('/tesseract-ocr.pdf'));
};
const detect = ({ payload: { image } }, res) => {
try {
const ptr = setImage(TessModule, api, image);
const results = new TessModule.OSResults();
if (!api.DetectOS(results)) {
api.End();
TessModule._free(ptr);
res.reject('Failed to detect OS');
} else {
const best = results.best_result;
const oid = best.orientation_id;
const sid = best.script_id;
TessModule._free(ptr);
res.resolve({
tesseract_script_id: sid,
script: results.unicharset.get_script_from_script_id(sid),
script_confidence: best.sconfidence,
orientation_degrees: [0, 270, 180, 90][oid],
orientation_confidence: best.oconfidence,
});
}
} catch (err) {
res.reject(err.toString());
}
};
const terminate = (_, res) => {
try {
if (api !== null) {
api.End();
}
res.resolve({ terminated: true });
} catch (err) {
res.reject(err.toString());
}
};
/**
* dispatchHandlers
*
* @name dispatchHandlers
* @function worker data handler
* @access public
* @param {object} data
* @param {string} data.jobId - unique job id
* @param {string} data.action - action of the job, only recognize and detect for now
* @param {object} data.payload - data for the job
* @param {function} send - trigger job to work
*/
exports.dispatchHandlers = (packet, send) => {
const res = (status, data) => {
send({
...packet,
status,
data,
});
};
res.resolve = res.bind(this, 'resolve');
res.reject = res.bind(this, 'reject');
res.progress = res.bind(this, 'progress');
latestJob = res;
try {
({
load,
loadLanguage,
initialize,
setParameters,
recognize,
getPDF,
detect,
terminate,
})[packet.action](packet, res);
} catch (err) {
/** Prepare exception to travel through postMessage */
res.reject(err.toString());
}
};
/**
* setAdapter
*
* @name setAdapter
* @function
* @access public
* @param {object} adapter - implementation of the worker, different in browser and node environment
*/
exports.setAdapter = (_adapter) => {
adapter = _adapter;
};
| src/worker-script/index.js | /**
*
* Worker script for browser and node
*
* @fileoverview Worker script for browser and node
* @author Kevin Kwok <[email protected]>
* @author Guillermo Webster <[email protected]>
* @author Jerome Wu <[email protected]>
*/
require('regenerator-runtime/runtime');
const fileType = require('file-type');
const axios = require('axios');
const isURL = require('is-url');
const dump = require('./utils/dump');
const isBrowser = require('../utils/getEnvironment')('type') === 'browser';
const setImage = require('./utils/setImage');
const defaultParams = require('./constants/defaultParams');
const { log, setLogging } = require('../utils/log');
/*
* Tesseract Module returned by TesseractCore.
*/
let TessModule;
/*
* TessearctBaseAPI instance
*/
let api = null;
let latestJob;
let adapter = {};
let params = defaultParams;
const load = ({ workerId, jobId, payload: { options: { corePath, logging } } }, res) => {
setLogging(logging);
if (!TessModule) {
const Core = adapter.getCore(corePath, res);
res.progress({ workerId, status: 'initializing tesseract', progress: 0 });
Core({
TesseractProgress(percent) {
latestJob.progress({
workerId,
jobId,
status: 'recognizing text',
progress: Math.max(0, (percent - 30) / 70),
});
},
}).then((tessModule) => {
TessModule = tessModule;
res.progress({ workerId, status: 'initialized tesseract', progress: 1 });
res.resolve({ loaded: true });
});
} else {
res.resolve({ loaded: true });
}
};
const loadLanguage = async ({
workerId,
payload: {
langs,
options: {
langPath,
dataPath,
cachePath,
cacheMethod,
gzip = true,
},
},
},
res) => {
const loadAndGunzipFile = async (_lang) => {
const lang = typeof _lang === 'string' ? _lang : _lang.code;
const readCache = ['refresh', 'none'].includes(cacheMethod)
? () => Promise.resolve()
: adapter.readCache;
let data = null;
try {
const _data = await readCache(`${cachePath || '.'}/${lang}.traineddata`);
if (typeof _data !== 'undefined') {
log(`[${workerId}]: Load ${lang}.traineddata from cache`);
data = _data;
} else {
throw Error('Not found in cache');
}
} catch (e) {
log(`[${workerId}]: Load ${lang}.traineddata from ${langPath}`);
if (typeof _lang === 'string') {
let path = null;
if (isURL(langPath) || langPath.startsWith('chrome-extension://') || langPath.startsWith('file://')) { /** When langPath is an URL */
path = langPath;
}
if (path !== null) {
const { data: _data } = await axios.get(
`${path}/${lang}.traineddata${gzip ? '.gz' : ''}`,
{ responseType: 'arraybuffer' },
);
data = _data;
} else {
data = await adapter.readCache(`${langPath}/${lang}.traineddata${gzip ? '.gz' : ''}`);
}
} else {
data = _lang.data; // eslint-disable-line
}
}
data = new Uint8Array(data);
const type = fileType(data);
if (typeof type !== 'undefined' && type.mime === 'application/gzip') {
data = adapter.gunzip(data);
}
if (TessModule) {
if (dataPath) {
try {
TessModule.FS.mkdir(dataPath);
} catch (err) {
res.reject(err.toString());
}
}
TessModule.FS.writeFile(`${dataPath || '.'}/${lang}.traineddata`, data);
}
if (['write', 'refresh', undefined].includes(cacheMethod)) {
await adapter.writeCache(`${cachePath || '.'}/${lang}.traineddata`, data);
}
return Promise.resolve(data);
};
res.progress({ workerId, status: 'loading language traineddata', progress: 0 });
try {
await Promise.all((typeof langs === 'string' ? langs.split('+') : langs).map(loadAndGunzipFile));
res.progress({ workerId, status: 'loaded language traineddata', progress: 1 });
res.resolve(langs);
} catch (err) {
if (isBrowser && err instanceof DOMException) {
/*
* For some reason google chrome throw DOMException in loadLang,
* while other browser is OK, for now we ignore this exception
* and hopefully to find the root cause one day.
*/
} else {
res.reject(err.toString());
}
}
};
const setParameters = ({ payload: { params: _params } }, res) => {
Object.keys(_params)
.filter(k => !k.startsWith('tessjs_'))
.forEach((key) => {
api.SetVariable(key, _params[key]);
});
params = { ...params, ..._params };
if (typeof res !== 'undefined') {
res.resolve(params);
}
};
const initialize = ({
workerId,
payload: { langs: _langs, oem },
}, res) => {
const langs = (typeof _langs === 'string')
? _langs
: _langs.map(l => ((typeof l === 'string') ? l : l.data)).join('+');
try {
res.progress({
workerId, status: 'initializing api', progress: 0,
});
if (api !== null) {
api.End();
}
api = new TessModule.TessBaseAPI();
api.Init(null, langs, oem);
params = defaultParams;
setParameters({ payload: { params } });
res.progress({
workerId, status: 'initialized api', progress: 1,
});
res.resolve();
} catch (err) {
res.reject(err.toString());
}
};
const recognize = ({ payload: { image, options: { rectangles = [] } } }, res) => {
try {
const ptr = setImage(TessModule, api, image);
rectangles.forEach(({
left, top, width, height,
}) => {
api.SetRectangle(left, top, width, height);
});
api.Recognize(null);
res.resolve(dump(TessModule, api, params));
TessModule._free(ptr);
} catch (err) {
res.reject(err.toString());
}
};
const getPDF = ({ payload: { title, textonly } }, res) => {
const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
pdfRenderer.BeginDocument(title);
pdfRenderer.AddImage(api);
pdfRenderer.EndDocument();
TessModule._free(pdfRenderer);
res.resolve(TessModule.FS.readFile('/tesseract-ocr.pdf'));
};
const detect = ({ payload: { image } }, res) => {
try {
const ptr = setImage(TessModule, api, image);
const results = new TessModule.OSResults();
if (!api.DetectOS(results)) {
api.End();
TessModule._free(ptr);
res.reject('Failed to detect OS');
} else {
const best = results.best_result;
const oid = best.orientation_id;
const sid = best.script_id;
TessModule._free(ptr);
res.resolve({
tesseract_script_id: sid,
script: results.unicharset.get_script_from_script_id(sid),
script_confidence: best.sconfidence,
orientation_degrees: [0, 270, 180, 90][oid],
orientation_confidence: best.oconfidence,
});
}
} catch (err) {
res.reject(err.toString());
}
};
const terminate = (_, res) => {
try {
if (api !== null) {
api.End();
}
res.resolve({ terminated: true });
} catch (err) {
res.reject(err.toString());
}
};
/**
* dispatchHandlers
*
* @name dispatchHandlers
* @function worker data handler
* @access public
* @param {object} data
* @param {string} data.jobId - unique job id
* @param {string} data.action - action of the job, only recognize and detect for now
* @param {object} data.payload - data for the job
* @param {function} send - trigger job to work
*/
exports.dispatchHandlers = (packet, send) => {
const res = (status, data) => {
send({
...packet,
status,
data,
});
};
res.resolve = res.bind(this, 'resolve');
res.reject = res.bind(this, 'reject');
res.progress = res.bind(this, 'progress');
latestJob = res;
try {
({
load,
loadLanguage,
initialize,
setParameters,
recognize,
getPDF,
detect,
terminate,
})[packet.action](packet, res);
} catch (err) {
/** Prepare exception to travel through postMessage */
res.reject(err.toString());
}
};
/**
* setAdapter
*
* @name setAdapter
* @function
* @access public
* @param {object} adapter - implementation of the worker, different in browser and node environment
*/
exports.setAdapter = (_adapter) => {
adapter = _adapter;
};
| Enable Firefox extesions too
AFAIK this library has no particular reason to ditch Firefox extensions. I have tested with above changes applied and I can finally use OCR within Firefox too.
Thanks for considering this change. | src/worker-script/index.js | Enable Firefox extesions too | <ide><path>rc/worker-script/index.js
<ide> if (typeof _lang === 'string') {
<ide> let path = null;
<ide>
<del> if (isURL(langPath) || langPath.startsWith('chrome-extension://') || langPath.startsWith('file://')) { /** When langPath is an URL */
<add> if (isURL(langPath) || langPath.startsWith('moz-extension://') || langPath.startsWith('chrome-extension://') || langPath.startsWith('file://')) { /** When langPath is an URL */
<ide> path = langPath;
<ide> }
<ide> |
|
Java | lgpl-2.1 | b4a58f5c884e4ea40082412eb6e1c16dc5a2f530 | 0 | Zandorum/DimDoors,CannibalVox/DimDoors | package StevenDimDoors.mod_pocketDim.core;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import StevenDimDoors.mod_pocketDim.Point3D;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import StevenDimDoors.mod_pocketDim.config.DDProperties;
import StevenDimDoors.mod_pocketDim.helpers.Compactor;
import StevenDimDoors.mod_pocketDim.helpers.DeleteFolder;
import StevenDimDoors.mod_pocketDim.saving.DDSaveHandler;
import StevenDimDoors.mod_pocketDim.saving.IPackable;
import StevenDimDoors.mod_pocketDim.saving.OldSaveImporter;
import StevenDimDoors.mod_pocketDim.saving.PackedDimData;
import StevenDimDoors.mod_pocketDim.saving.PackedDungeonData;
import StevenDimDoors.mod_pocketDim.saving.PackedLinkData;
import StevenDimDoors.mod_pocketDim.saving.PackedLinkTail;
import StevenDimDoors.mod_pocketDim.util.Point4D;
import StevenDimDoors.mod_pocketDim.watcher.ClientDimData;
import StevenDimDoors.mod_pocketDim.watcher.ClientLinkData;
import StevenDimDoors.mod_pocketDim.watcher.IUpdateSource;
import StevenDimDoors.mod_pocketDim.watcher.IUpdateWatcher;
import StevenDimDoors.mod_pocketDim.watcher.UpdateWatcherProxy;
/**
* This class regulates all the operations involving the storage and manipulation of dimensions.
* It handles saving dim data, teleporting the player, and creating/registering new dimensions as
* well as loading old dimensions on startup
*/
public class PocketManager
{
private static class InnerDimData extends NewDimData implements IPackable<PackedDimData>
{
// This class allows us to instantiate NewDimData indirectly without exposing
// a public constructor from NewDimData. It's meant to stop us from constructing
// instances of NewDimData going through PocketManager. In turn, that enforces
// that any link destinations must be real dimensions controlled by PocketManager.
public InnerDimData(int id, InnerDimData parent, boolean isPocket, boolean isDungeon,
IUpdateWatcher<ClientLinkData> linkWatcher)
{
super(id, parent, isPocket, isDungeon, linkWatcher);
}
public InnerDimData(int id, InnerDimData root)
{
// This constructor is meant for client-side code only
super(id, root);
}
public void clear()
{
// If this dimension has a parent, remove it from its parent's list of children
if (parent != null)
{
parent.children.remove(this);
}
// Remove this dimension as the parent of its children
for (NewDimData child : children)
{
child.parent = null;
}
// Clear all fields
id = Integer.MIN_VALUE;
linkMapping.clear();
linkMapping = null;
linkList.clear();
linkList = null;
children.clear();
children = null;
isDungeon = false;
isFilled = false;
depth = Integer.MIN_VALUE;
packDepth = Integer.MIN_VALUE;
origin = null;
orientation = Integer.MIN_VALUE;
dungeon = null;
linkWatcher = null;
}
@Override
public String name()
{
return String.valueOf(id);
}
@Override
public PackedDimData pack()
{
ArrayList<Integer> ChildIDs = new ArrayList<Integer>();
ArrayList<PackedLinkData> Links = new ArrayList<PackedLinkData>();
ArrayList<PackedLinkTail> Tails = new ArrayList<PackedLinkTail>();
PackedDungeonData packedDungeon=null;
if(this.dungeon!=null)
{
packedDungeon= new PackedDungeonData(dungeon.weight(), dungeon.isOpen(), dungeon.isInternal(),
dungeon.schematicPath(), dungeon.schematicName(), dungeon.dungeonType().Name,
dungeon.dungeonType().Owner.getName());
}
//Make a list of children
for(NewDimData data : this.children)
{
ChildIDs.add(data.id);
}
for(DimLink link:this.links())
{
ArrayList<Point3D> children = new ArrayList<Point3D>();
Point3D parentPoint = new Point3D(-1,-1,-1);
if(link.parent!=null)
{
parentPoint=link.parent.link.point.toPoint3D();
}
for(DimLink childLink : link.children)
{
children.add(childLink.source().toPoint3D());
}
PackedLinkTail tail = new PackedLinkTail(link.tail.getDestination(),link.tail.getLinkType());
Links.add(new PackedLinkData(link.link.point,parentPoint,tail,link.link.orientation,children));
PackedLinkTail tempTail = new PackedLinkTail(link.tail.getDestination(),link.tail.getLinkType());
if(Tails.contains(tempTail))
{
Tails.add(tempTail);
}
}
int parentID=this.id;
Point3D originPoint=new Point3D(0,0,0);
if(this.parent!=null)
{
parentID = this.parent.id;
}
if(this.origin!=null)
{
originPoint=this.origin.toPoint3D();
}
return new PackedDimData(this.id, depth, this.packDepth, parentID, this.root().id(), orientation,
isDungeon, isFilled,packedDungeon, originPoint, ChildIDs, Links, Tails);
// FIXME: IMPLEMENTATION PLZTHX
//I tried
}
}
private static class ClientLinkWatcher implements IUpdateWatcher<ClientLinkData>
{
@Override
public void onCreated(ClientLinkData link)
{
Point4D source = link.point;
NewDimData dimension = getDimensionData(source.getDimension());
dimension.createLink(source.getX(), source.getY(), source.getZ(), LinkTypes.CLIENT_SIDE,link.orientation);
}
@Override
public void onDeleted(ClientLinkData link)
{
Point4D source = link.point;
NewDimData dimension = getDimensionData(source.getDimension());
dimension.deleteLink(source.getX(), source.getY(), source.getZ());
}
}
private static class ClientDimWatcher implements IUpdateWatcher<ClientDimData>
{
@Override
public void onCreated(ClientDimData data)
{
registerClientDimension(data.ID, data.RootID);
}
@Override
public void onDeleted(ClientDimData data)
{
deletePocket(getDimensionData(data.ID), false);
}
}
private static class DimRegistrationCallback implements IDimRegistrationCallback
{
// We use this class to provide Compactor with the ability to send us dim data without
// having to instantiate a bunch of data containers and without exposing an "unsafe"
// creation method for anyone to call. Integrity protection for the win! It's like
// exposing a private constructor ONLY to a very specific trusted class.
@Override
public NewDimData registerDimension(int dimensionID, int rootID)
{
return registerClientDimension(dimensionID, rootID);
}
}
private static int OVERWORLD_DIMENSION_ID = 0;
private static volatile boolean isLoading = false;
private static volatile boolean isLoaded = false;
private static volatile boolean isSaving = false;
/**
* Set as true if we are a client that has connected to a dedicated server
*/
public static volatile boolean isConnected = false;
private static final UpdateWatcherProxy<ClientLinkData> linkWatcher = new UpdateWatcherProxy<ClientLinkData>();
private static final UpdateWatcherProxy<ClientDimData> dimWatcher = new UpdateWatcherProxy<ClientDimData>();
private static ArrayList<NewDimData> rootDimensions = null;
//HashMap that maps all the dimension IDs registered with DimDoors to their DD data.
private static HashMap<Integer, InnerDimData> dimensionData = null;
//ArrayList that stores the dimension IDs of any dimension that has been deleted.
private static ArrayList<Integer> dimensionIDBlackList = null;
public static boolean isLoaded()
{
return isLoaded;
}
/**
* simple method called on startup to register all dims saved in the dim list. Only tries to register pocket dims, though. Also calls load()
* @return
*/
public static void load()
{
if (isLoaded)
{
throw new IllegalStateException("Pocket dimensions have already been loaded!");
}
if (isLoading)
{
return;
}
isLoading = true;
dimensionData = new HashMap<Integer, InnerDimData>();
rootDimensions = new ArrayList<NewDimData>();
dimensionIDBlackList = new ArrayList<Integer>();
if(FMLCommonHandler.instance().getEffectiveSide().isClient())
{
//Shouldnt try to load everything if we are a client
//This was preventing onPacket from loading properly
isLoading=false;
isLoaded=true;
return;
}
//Register Limbo
DDProperties properties = DDProperties.instance();
registerDimension(properties.LimboDimensionID, null, false, false);
loadInternal();
//Register pocket dimensions
registerPockets(properties);
isLoaded = true;
isLoading = false;
}
public static boolean registerPackedDimData(PackedDimData packedData)
{
InnerDimData dimData;
//register roots
if(packedData.ID==packedData.ParentID)
{
dimData = new InnerDimData(packedData.ID, null, false, false, linkWatcher);
dimData.root=dimData;
dimData.parent=dimData;
dimData.depth=packedData.Depth;
dimData.isFilled=packedData.IsFilled;
dimData.origin = new Point4D(packedData.Origin.getX(),packedData.Origin.getY(),packedData.Origin.getZ(),packedData.ID);
PocketManager.rootDimensions.add(dimData);
}
else //register children
{
InnerDimData test = PocketManager.dimensionData.get(packedData.ParentID);
dimData = new InnerDimData(packedData.ID, test,true, packedData.IsDungeon, linkWatcher);
dimData.isFilled=packedData.IsFilled;
dimData.origin = new Point4D(packedData.Origin.getX(),packedData.Origin.getY(),packedData.Origin.getZ(),packedData.ID);
dimData.root=PocketManager.getDimensionData(packedData.RootID);
if(packedData.DungeonData!=null)
{
dimData.dungeon=DDSaveHandler.unpackDungeonData(packedData.DungeonData);
}
}
PocketManager.dimensionData.put(dimData.id, dimData);
getDimwatcher().onCreated(new ClientDimData(dimData));
return true;
}
public static boolean deletePocket(NewDimData target, boolean deleteFolder)
{
// We can't delete the dimension if it's currently loaded or if it's not actually a pocket.
// We cast to InnerDimData so that if anyone tries to be a smartass and create their
// own version of NewDimData, this will throw an exception.
InnerDimData dimension = (InnerDimData) target;
if (dimension.isPocketDimension() && DimensionManager.getWorld(dimension.id()) == null)
{
if (deleteFolder)
{
deleteDimensionFiles(dimension);
}
dimensionIDBlackList.add(dimension.id);
deleteDimensionData(dimension);
return true;
}
return false;
}
private static void deleteDimensionFiles(InnerDimData dimension)
{
// We assume that the caller checks if the dimension is loaded, for the
// sake of efficiency. Don't call this on a loaded dimension or bad
// things will happen!
String saveRootPath = DimensionManager.getCurrentSaveRootDirectory().getAbsolutePath();
File saveDirectory = new File(saveRootPath + "/DimensionalDoors/pocketDimID" + dimension.id());
DeleteFolder.deleteFolder(saveDirectory);
File dataFile = new File(saveRootPath + "/DimensionalDoors/data/dim_" + dimension.id() + ".txt");
dataFile.delete();
}
private static void deleteDimensionData(InnerDimData dimension)
{
// We assume that the caller checks if the dimension is loaded, for the
// sake of efficiency. Don't call this on a loaded dimension or bad
// things will happen!
if (dimensionData.remove(dimension.id()) != null)
{
// Raise the dim deleted event
getDimwatcher().onDeleted(new ClientDimData(dimension));
dimension.clear();
}
else
{
// This should never happen. A simple sanity check.
throw new IllegalArgumentException("The specified dimension is not listed with PocketManager.");
}
}
private static void registerPockets(DDProperties properties)
{
for (NewDimData dimension : dimensionData.values())
{
if (dimension.isPocketDimension())
{
try
{
DimensionManager.registerDimension(dimension.id(), properties.PocketProviderID);
}
catch (Exception e)
{
System.err.println("Could not register pocket dimension #" + dimension.id() + ". Probably caused by a version update/save data corruption/other mods.");
e.printStackTrace();
}
}
}
}
private static void unregisterPockets()
{
for (NewDimData dimension : dimensionData.values())
{
if (dimension.isPocketDimension())
{
try
{
DimensionManager.unregisterDimension(dimension.id());
}
catch (Exception e)
{
System.err.println("An unexpected error occurred while unregistering pocket dimension #" + dimension.id() + ":");
e.printStackTrace();
}
}
}
for(Integer dimID : dimensionIDBlackList)
{
try
{
DimensionManager.unregisterDimension(dimID);
}
catch (Exception e)
{
System.err.println("An unexpected error occurred while unregistering blacklisted dim #" + dimID + ":");
e.printStackTrace();
}
}
}
/**
* loads the dim data from the saved hashMap. Also handles compatibility with old saves, see OldSaveHandler
*/
private static void loadInternal()
{
//System.out.println(!FMLCommonHandler.instance().getSide().isClient());
File saveDir = DimensionManager.getCurrentSaveRootDirectory();
if (saveDir != null)
{
//Try to import data from old DD versions
//TODO - remove this code in a few versions
File oldSaveData = new File(saveDir+"/DimensionalDoorsData");
if(oldSaveData.exists())
{
try
{
System.out.println("Importing old DD save data...");
OldSaveImporter.importOldSave(oldSaveData);
oldSaveData.renameTo(new File(oldSaveData.getAbsolutePath()+"_IMPORTED"));
System.out.println("Import Succesful!");
}
catch (Exception e)
{
//TODO handle fail cases
System.out.println("Import failed!");
e.printStackTrace();
}
return;
}
// Load save data
System.out.println("Loading Dimensional Doors save data...");
if (DDSaveHandler.loadAll())
{
System.out.println("Loaded successfully!");
}
}
}
public static void save(boolean checkModified)
{
if (!isLoaded)
{
return;
}
//Check this last to make sure we set the flag shortly after.
if (isSaving)
{
return;
}
isSaving = true;
try
{
DDSaveHandler.saveAll(dimensionData.values(), dimensionIDBlackList, checkModified);
}
catch (Exception e)
{
// Wrap the exception in a RuntimeException so functions that call
// PocketManager.save() don't need to catch it. We want MC to
// crash if something really bad happens rather than ignoring it!
throw new RuntimeException(e);
}
finally
{
isSaving = false;
}
}
public static WorldServer loadDimension(int id)
{
WorldServer world = DimensionManager.getWorld(id);
if (world == null)
{
DimensionManager.initDimension(id);
world = DimensionManager.getWorld(id);
}
else if (world.provider == null)
{
DimensionManager.initDimension(id);
world = DimensionManager.getWorld(id);
}
return world;
}
public static NewDimData registerDimension(World world)
{
return registerDimension(world.provider.dimensionId, null, false, false);
}
public static NewDimData registerPocket(NewDimData parent, boolean isDungeon)
{
if (parent == null)
{
throw new IllegalArgumentException("parent cannot be null. A pocket dimension must always have a parent dimension.");
}
DDProperties properties = DDProperties.instance();
int dimensionID = DimensionManager.getNextFreeDimId();
DimensionManager.registerDimension(dimensionID, properties.PocketProviderID);
return registerDimension(dimensionID, (InnerDimData) parent, true, isDungeon);
}
/**
* Registers a dimension with DD but NOT with forge.
* @param dimensionID
* @param parent
* @param isPocket
* @param isDungeon
* @return
*/
private static NewDimData registerDimension(int dimensionID, InnerDimData parent, boolean isPocket, boolean isDungeon)
{
if (dimensionData.containsKey(dimensionID))
{
if(PocketManager.dimensionIDBlackList.contains(dimensionID))
{
throw new IllegalArgumentException("Cannot register a dimension with ID = " + dimensionID + " because it has been blacklisted.");
}
throw new IllegalArgumentException("Cannot register a dimension with ID = " + dimensionID + " because it has already been registered.");
}
InnerDimData dimension = new InnerDimData(dimensionID, parent, isPocket, isDungeon, linkWatcher);
dimensionData.put(dimensionID, dimension);
if (!dimension.isPocketDimension())
{
rootDimensions.add(dimension);
}
getDimwatcher().onCreated(new ClientDimData(dimension));
return dimension;
}
@SideOnly(Side.CLIENT)
private static NewDimData registerClientDimension(int dimensionID, int rootID)
{
System.out.println("Registered dim "+dimensionID+" on the client.");
// No need to raise events heres since this code should only run on the client side
// getDimensionData() always handles root dimensions properly, even if the weren't defined before
// SenseiKiwi: I'm a little worried about how getDimensionData will raise
// an event when it creates any root dimensions... Needs checking later.
InnerDimData root = (InnerDimData) getDimensionData(rootID);
InnerDimData dimension;
if (rootID != dimensionID)
{
dimension = dimensionData.get(dimensionID);
if (dimension == null)
{
dimension = new InnerDimData(dimensionID, root);
dimensionData.put(dimension.id(), dimension);
}
}
else
{
dimension = root;
}
if(dimension.isPocketDimension()&&!DimensionManager.isDimensionRegistered(dimension.id()))
{
//Im registering pocket dims here. I *think* we can assume that if its a pocket and we are
//registering its dim data, we also need to register it with forge.
//New packet stuff prevents this from always being true, unfortuantly. I send the dimdata to the client when they teleport.
//Steven
DimensionManager.registerDimension(dimensionID, mod_pocketDim.properties.PocketProviderID);
}
return dimension;
}
public static NewDimData getDimensionData(World world)
{
return getDimensionData(world.provider.dimensionId);
}
public static NewDimData getDimensionData(int dimensionID)
{
//Retrieve the data for a dimension. If we don't have a record for that dimension,
//assume it's a non-pocket dimension that hasn't been initialized with us before
//and create a NewDimData instance for it.
//Any pocket dimension must be listed with PocketManager to have a dimension ID
//assigned, so it's safe to assume that any unknown dimensions don't belong to us.
//FIXME: What's the point of this condition? Most calls to this function will crash anyway! ~SenseiKiwi
if(PocketManager.dimensionData == null)
{
System.out.println("Something odd happend during shutdown");
return null;
}
NewDimData dimension = PocketManager.dimensionData.get(dimensionID);
if (dimension == null)
{
dimension = registerDimension(dimensionID, null, false, false);
}
return dimension;
}
public static Iterable<? extends NewDimData> getDimensions()
{
return dimensionData.values();
}
@SuppressWarnings("unchecked")
public static ArrayList<NewDimData> getRootDimensions()
{
return (ArrayList<NewDimData>) rootDimensions.clone();
}
public static void unload()
{
System.out.println("Unloading Pocket Dimensions...");
if (!isLoaded)
{
throw new IllegalStateException("Pocket dimensions have already been unloaded!");
}
unregisterPockets();
dimensionData = null;
rootDimensions = null;
isLoaded = false;
isConnected = false;
}
public static DimLink getLink(int x, int y, int z, World world)
{
return getLink(x, y, z, world.provider.dimensionId);
}
public static DimLink getLink(Point4D point)
{
return getLink(point.getX(), point.getY(), point.getZ(), point.getDimension());
}
public static DimLink getLink(int x, int y, int z, int dimensionID)
{
NewDimData dimension = dimensionData.get(dimensionID);
if (dimension != null)
{
return dimension.getLink(x, y, z);
}
return null;
}
public static boolean isBlackListed(int dimensionID)
{
return PocketManager.dimensionIDBlackList.contains(dimensionID);
}
public static void registerDimWatcher(IUpdateWatcher<ClientDimData> watcher)
{
getDimwatcher().registerReceiver(watcher);
}
public static boolean unregisterDimWatcher(IUpdateWatcher<ClientDimData> watcher)
{
return getDimwatcher().unregisterReceiver(watcher);
}
public static void registerLinkWatcher(IUpdateWatcher<ClientLinkData> watcher)
{
linkWatcher.registerReceiver(watcher);
}
public static boolean unregisterLinkWatcher(IUpdateWatcher<ClientLinkData> watcher)
{
return linkWatcher.unregisterReceiver(watcher);
}
public static void getWatchers(IUpdateSource updateSource)
{
updateSource.registerWatchers(new ClientDimWatcher(), new ClientLinkWatcher());
}
public static void writePacket(DataOutputStream output) throws IOException
{
// Write a very compact description of our dimensions and links to be sent to a client
Compactor.write(dimensionData.values(), output);
}
public static boolean isRegisteredInternally(int dimensionID)
{
return dimensionData.containsKey(dimensionID);
}
public static void createAndRegisterBlacklist(List<Integer> blacklist)
{
//TODO - create a special blacklist provider
for(Integer dimID : blacklist)
{
PocketManager.dimensionIDBlackList.add(dimID);
DimensionManager.registerDimension(dimID, DDProperties.instance().PocketProviderID);
}
}
public static void readPacket(DataInputStream input) throws IOException
{
//TODO- figure out why this is getting called so frequently
if (isLoaded)
{
return;
}
if (isLoading)
{
throw new IllegalStateException("Pocket dimensions are already loading!");
}
// Load compacted client-side dimension data
load();
Compactor.readDimensions(input, new DimRegistrationCallback());
isLoaded = true;
isLoading = false;
isConnected = true;
}
public static UpdateWatcherProxy<ClientDimData> getDimwatcher()
{
return dimWatcher;
}
}
| src/main/java/StevenDimDoors/mod_pocketDim/core/PocketManager.java | package StevenDimDoors.mod_pocketDim.core;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.DimensionManager;
import StevenDimDoors.mod_pocketDim.Point3D;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import StevenDimDoors.mod_pocketDim.config.DDProperties;
import StevenDimDoors.mod_pocketDim.helpers.Compactor;
import StevenDimDoors.mod_pocketDim.helpers.DeleteFolder;
import StevenDimDoors.mod_pocketDim.saving.DDSaveHandler;
import StevenDimDoors.mod_pocketDim.saving.IPackable;
import StevenDimDoors.mod_pocketDim.saving.OldSaveImporter;
import StevenDimDoors.mod_pocketDim.saving.PackedDimData;
import StevenDimDoors.mod_pocketDim.saving.PackedDungeonData;
import StevenDimDoors.mod_pocketDim.saving.PackedLinkData;
import StevenDimDoors.mod_pocketDim.saving.PackedLinkTail;
import StevenDimDoors.mod_pocketDim.util.Point4D;
import StevenDimDoors.mod_pocketDim.watcher.ClientDimData;
import StevenDimDoors.mod_pocketDim.watcher.ClientLinkData;
import StevenDimDoors.mod_pocketDim.watcher.IUpdateSource;
import StevenDimDoors.mod_pocketDim.watcher.IUpdateWatcher;
import StevenDimDoors.mod_pocketDim.watcher.UpdateWatcherProxy;
/**
* This class regulates all the operations involving the storage and manipulation of dimensions.
* It handles saving dim data, teleporting the player, and creating/registering new dimensions as
* well as loading old dimensions on startup
*/
public class PocketManager
{
private static class InnerDimData extends NewDimData implements IPackable<PackedDimData>
{
// This class allows us to instantiate NewDimData indirectly without exposing
// a public constructor from NewDimData. It's meant to stop us from constructing
// instances of NewDimData going through PocketManager. In turn, that enforces
// that any link destinations must be real dimensions controlled by PocketManager.
public InnerDimData(int id, InnerDimData parent, boolean isPocket, boolean isDungeon,
IUpdateWatcher<ClientLinkData> linkWatcher)
{
super(id, parent, isPocket, isDungeon, linkWatcher);
}
public InnerDimData(int id, InnerDimData root)
{
// This constructor is meant for client-side code only
super(id, root);
}
public void clear()
{
// If this dimension has a parent, remove it from its parent's list of children
if (parent != null)
{
parent.children.remove(this);
}
// Remove this dimension as the parent of its children
for (NewDimData child : children)
{
child.parent = null;
}
// Clear all fields
id = Integer.MIN_VALUE;
linkMapping.clear();
linkMapping = null;
linkList.clear();
linkList = null;
children.clear();
children = null;
isDungeon = false;
isFilled = false;
depth = Integer.MIN_VALUE;
packDepth = Integer.MIN_VALUE;
origin = null;
orientation = Integer.MIN_VALUE;
dungeon = null;
linkWatcher = null;
}
@Override
public String name()
{
return String.valueOf(id);
}
@Override
public PackedDimData pack()
{
ArrayList<Integer> ChildIDs = new ArrayList<Integer>();
ArrayList<PackedLinkData> Links = new ArrayList<PackedLinkData>();
ArrayList<PackedLinkTail> Tails = new ArrayList<PackedLinkTail>();
PackedDungeonData packedDungeon=null;
if(this.dungeon!=null)
{
packedDungeon= new PackedDungeonData(dungeon.weight(), dungeon.isOpen(), dungeon.isInternal(),
dungeon.schematicPath(), dungeon.schematicName(), dungeon.dungeonType().Name,
dungeon.dungeonType().Owner.getName());
}
//Make a list of children
for(NewDimData data : this.children)
{
ChildIDs.add(data.id);
}
for(DimLink link:this.links())
{
ArrayList<Point3D> children = new ArrayList<Point3D>();
Point3D parentPoint = new Point3D(-1,-1,-1);
if(link.parent!=null)
{
parentPoint=link.parent.link.point.toPoint3D();
}
for(DimLink childLink : link.children)
{
children.add(childLink.source().toPoint3D());
}
PackedLinkTail tail = new PackedLinkTail(link.tail.getDestination(),link.tail.getLinkType());
Links.add(new PackedLinkData(link.link.point,parentPoint,tail,link.link.orientation,children));
PackedLinkTail tempTail = new PackedLinkTail(link.tail.getDestination(),link.tail.getLinkType());
if(Tails.contains(tempTail))
{
Tails.add(tempTail);
}
}
int parentID=this.id;
Point3D originPoint=new Point3D(0,0,0);
if(this.parent!=null)
{
parentID = this.parent.id;
}
if(this.origin!=null)
{
originPoint=this.origin.toPoint3D();
}
return new PackedDimData(this.id, depth, this.packDepth, parentID, this.root().id(), orientation,
isDungeon, isFilled,packedDungeon, originPoint, ChildIDs, Links, Tails);
// FIXME: IMPLEMENTATION PLZTHX
//I tried
}
}
private static class ClientLinkWatcher implements IUpdateWatcher<ClientLinkData>
{
@Override
public void onCreated(ClientLinkData link)
{
Point4D source = link.point;
NewDimData dimension = getDimensionData(source.getDimension());
dimension.createLink(source.getX(), source.getY(), source.getZ(), LinkTypes.CLIENT_SIDE,link.orientation);
}
@Override
public void onDeleted(ClientLinkData link)
{
Point4D source = link.point;
NewDimData dimension = getDimensionData(source.getDimension());
dimension.deleteLink(source.getX(), source.getY(), source.getZ());
}
}
private static class ClientDimWatcher implements IUpdateWatcher<ClientDimData>
{
@Override
public void onCreated(ClientDimData data)
{
registerClientDimension(data.ID, data.RootID);
}
@Override
public void onDeleted(ClientDimData data)
{
deletePocket(getDimensionData(data.ID), false);
}
}
private static class DimRegistrationCallback implements IDimRegistrationCallback
{
// We use this class to provide Compactor with the ability to send us dim data without
// having to instantiate a bunch of data containers and without exposing an "unsafe"
// creation method for anyone to call. Integrity protection for the win! It's like
// exposing a private constructor ONLY to a very specific trusted class.
@Override
public NewDimData registerDimension(int dimensionID, int rootID)
{
return registerClientDimension(dimensionID, rootID);
}
}
private static int OVERWORLD_DIMENSION_ID = 0;
private static volatile boolean isLoading = false;
private static volatile boolean isLoaded = false;
private static volatile boolean isSaving = false;
/**
* Set as true if we are a client that has connected to a dedicated server
*/
public static volatile boolean isConnected = false;
private static final UpdateWatcherProxy<ClientLinkData> linkWatcher = new UpdateWatcherProxy<ClientLinkData>();
private static final UpdateWatcherProxy<ClientDimData> dimWatcher = new UpdateWatcherProxy<ClientDimData>();
private static ArrayList<NewDimData> rootDimensions = null;
//HashMap that maps all the dimension IDs registered with DimDoors to their DD data.
private static HashMap<Integer, InnerDimData> dimensionData = null;
//ArrayList that stores the dimension IDs of any dimension that has been deleted.
private static ArrayList<Integer> dimensionIDBlackList = null;
public static boolean isLoaded()
{
return isLoaded;
}
/**
* simple method called on startup to register all dims saved in the dim list. Only tries to register pocket dims, though. Also calls load()
* @return
*/
public static void load()
{
if (isLoaded)
{
throw new IllegalStateException("Pocket dimensions have already been loaded!");
}
if (isLoading)
{
return;
}
isLoading = true;
dimensionData = new HashMap<Integer, InnerDimData>();
rootDimensions = new ArrayList<NewDimData>();
dimensionIDBlackList = new ArrayList<Integer>();
if(FMLCommonHandler.instance().getEffectiveSide().isClient())
{
//Shouldnt try to load everything if we are a client
//This was preventing onPacket from loading properly
isLoading=false;
isLoaded=true;
return;
}
//Register Limbo
DDProperties properties = DDProperties.instance();
registerDimension(properties.LimboDimensionID, null, false, false);
loadInternal();
//Register pocket dimensions
registerPockets(properties);
isLoaded = true;
isLoading = false;
}
public static boolean registerPackedDimData(PackedDimData packedData)
{
InnerDimData dimData;
//register roots
if(packedData.ID==packedData.ParentID)
{
dimData = new InnerDimData(packedData.ID, null, false, false, linkWatcher);
dimData.root=dimData;
dimData.parent=dimData;
dimData.depth=packedData.Depth;
dimData.isFilled=packedData.IsFilled;
dimData.origin = new Point4D(packedData.Origin.getX(),packedData.Origin.getY(),packedData.Origin.getZ(),packedData.ID);
PocketManager.rootDimensions.add(dimData);
}
else //register children
{
InnerDimData test = PocketManager.dimensionData.get(packedData.ParentID);
dimData = new InnerDimData(packedData.ID, test,true, packedData.IsDungeon, linkWatcher);
dimData.isFilled=packedData.IsFilled;
dimData.origin = new Point4D(packedData.Origin.getX(),packedData.Origin.getY(),packedData.Origin.getZ(),packedData.ID);
dimData.root=PocketManager.getDimensionData(packedData.RootID);
if(packedData.DungeonData!=null)
{
dimData.dungeon=DDSaveHandler.unpackDungeonData(packedData.DungeonData);
}
}
PocketManager.dimensionData.put(dimData.id, dimData);
getDimwatcher().onCreated(new ClientDimData(dimData));
return true;
}
public static boolean deletePocket(NewDimData target, boolean deleteFolder)
{
// We can't delete the dimension if it's currently loaded or if it's not actually a pocket.
// We cast to InnerDimData so that if anyone tries to be a smartass and create their
// own version of NewDimData, this will throw an exception.
InnerDimData dimension = (InnerDimData) target;
if (dimension.isPocketDimension() && DimensionManager.getWorld(dimension.id()) == null)
{
if (deleteFolder)
{
deleteDimensionFiles(target);
}
dimensionIDBlackList.add(dimension.id);
deleteDimensionData(dimension.id);
return true;
}
return false;
}
private static boolean deleteDimensionFiles(NewDimData target)
{
InnerDimData dimension = (InnerDimData) target;
if (dimension.isPocketDimension() && DimensionManager.getWorld(dimension.id()) == null)
{
String saveRootPath = DimensionManager.getCurrentSaveRootDirectory().getAbsolutePath();
File saveDirectory = new File(saveRootPath + "/DimensionalDoors/pocketDimID" + dimension.id());
DeleteFolder.deleteFolder(saveDirectory);
File dataFile = new File(saveRootPath + "/DimensionalDoors/data/dim_" + dimension.id() + ".txt");
dataFile.delete();
return true;
}
return false;
}
private static boolean deleteDimensionData(int dimensionID)
{
if (dimensionData.containsKey(dimensionID) && DimensionManager.getWorld(dimensionID) == null)
{
NewDimData target = PocketManager.getDimensionData(dimensionID);
InnerDimData dimension = (InnerDimData) target;
dimensionData.remove(dimensionID);
// Raise the dim deleted event
getDimwatcher().onDeleted(new ClientDimData(dimension));
dimension.clear();
return true;
}
return false;
}
private static void registerPockets(DDProperties properties)
{
for (NewDimData dimension : dimensionData.values())
{
if (dimension.isPocketDimension())
{
try
{
DimensionManager.registerDimension(dimension.id(), properties.PocketProviderID);
}
catch (Exception e)
{
System.err.println("Could not register pocket dimension #" + dimension.id() + ". Probably caused by a version update/save data corruption/other mods.");
e.printStackTrace();
}
}
}
}
private static void unregisterPockets()
{
for (NewDimData dimension : dimensionData.values())
{
if (dimension.isPocketDimension())
{
try
{
DimensionManager.unregisterDimension(dimension.id());
}
catch (Exception e)
{
System.err.println("An unexpected error occurred while unregistering pocket dimension #" + dimension.id() + ":");
e.printStackTrace();
}
}
}
for(Integer dimID : dimensionIDBlackList)
{
try
{
DimensionManager.unregisterDimension(dimID);
}
catch (Exception e)
{
System.err.println("An unexpected error occurred while unregistering blacklisted dim #" + dimID + ":");
e.printStackTrace();
}
}
}
/**
* loads the dim data from the saved hashMap. Also handles compatibility with old saves, see OldSaveHandler
*/
private static void loadInternal()
{
//System.out.println(!FMLCommonHandler.instance().getSide().isClient());
File saveDir = DimensionManager.getCurrentSaveRootDirectory();
if (saveDir != null)
{
//Try to import data from old DD versions
//TODO - remove this code in a few versions
File oldSaveData = new File(saveDir+"/DimensionalDoorsData");
if(oldSaveData.exists())
{
try
{
System.out.println("Importing old DD save data...");
OldSaveImporter.importOldSave(oldSaveData);
oldSaveData.renameTo(new File(oldSaveData.getAbsolutePath()+"_IMPORTED"));
System.out.println("Import Succesful!");
}
catch (Exception e)
{
//TODO handle fail cases
System.out.println("Import failed!");
e.printStackTrace();
}
return;
}
// Load save data
System.out.println("Loading Dimensional Doors save data...");
if (DDSaveHandler.loadAll())
{
System.out.println("Loaded successfully!");
}
}
}
public static void save(boolean checkModified)
{
if (!isLoaded)
{
return;
}
//Check this last to make sure we set the flag shortly after.
if (isSaving)
{
return;
}
isSaving = true;
try
{
DDSaveHandler.saveAll(dimensionData.values(), dimensionIDBlackList, checkModified);
}
catch (Exception e)
{
// Wrap the exception in a RuntimeException so functions that call
// PocketManager.save() don't need to catch it. We want MC to
// crash if something really bad happens rather than ignoring it!
throw new RuntimeException(e);
}
finally
{
isSaving = false;
}
}
public static WorldServer loadDimension(int id)
{
WorldServer world = DimensionManager.getWorld(id);
if (world == null)
{
DimensionManager.initDimension(id);
world = DimensionManager.getWorld(id);
}
else if (world.provider == null)
{
DimensionManager.initDimension(id);
world = DimensionManager.getWorld(id);
}
return world;
}
public static NewDimData registerDimension(World world)
{
return registerDimension(world.provider.dimensionId, null, false, false);
}
public static NewDimData registerPocket(NewDimData parent, boolean isDungeon)
{
if (parent == null)
{
throw new IllegalArgumentException("parent cannot be null. A pocket dimension must always have a parent dimension.");
}
DDProperties properties = DDProperties.instance();
int dimensionID = DimensionManager.getNextFreeDimId();
DimensionManager.registerDimension(dimensionID, properties.PocketProviderID);
return registerDimension(dimensionID, (InnerDimData) parent, true, isDungeon);
}
/**
* Registers a dimension with DD but NOT with forge.
* @param dimensionID
* @param parent
* @param isPocket
* @param isDungeon
* @return
*/
private static NewDimData registerDimension(int dimensionID, InnerDimData parent, boolean isPocket, boolean isDungeon)
{
if (dimensionData.containsKey(dimensionID))
{
if(PocketManager.dimensionIDBlackList.contains(dimensionID))
{
throw new IllegalArgumentException("Cannot register a dimension with ID = " + dimensionID + " because it has been blacklisted.");
}
throw new IllegalArgumentException("Cannot register a dimension with ID = " + dimensionID + " because it has already been registered.");
}
InnerDimData dimension = new InnerDimData(dimensionID, parent, isPocket, isDungeon, linkWatcher);
dimensionData.put(dimensionID, dimension);
if (!dimension.isPocketDimension())
{
rootDimensions.add(dimension);
}
getDimwatcher().onCreated(new ClientDimData(dimension));
return dimension;
}
@SideOnly(Side.CLIENT)
private static NewDimData registerClientDimension(int dimensionID, int rootID)
{
System.out.println("Registered dim "+dimensionID+" on the client.");
// No need to raise events heres since this code should only run on the client side
// getDimensionData() always handles root dimensions properly, even if the weren't defined before
// SenseiKiwi: I'm a little worried about how getDimensionData will raise
// an event when it creates any root dimensions... Needs checking later.
InnerDimData root = (InnerDimData) getDimensionData(rootID);
InnerDimData dimension;
if (rootID != dimensionID)
{
dimension = dimensionData.get(dimensionID);
if (dimension == null)
{
dimension = new InnerDimData(dimensionID, root);
dimensionData.put(dimension.id(), dimension);
}
}
else
{
dimension = root;
}
if(dimension.isPocketDimension()&&!DimensionManager.isDimensionRegistered(dimension.id()))
{
//Im registering pocket dims here. I *think* we can assume that if its a pocket and we are
//registering its dim data, we also need to register it with forge.
//New packet stuff prevents this from always being true, unfortuantly. I send the dimdata to the client when they teleport.
//Steven
DimensionManager.registerDimension(dimensionID, mod_pocketDim.properties.PocketProviderID);
}
return dimension;
}
public static NewDimData getDimensionData(World world)
{
return getDimensionData(world.provider.dimensionId);
}
public static NewDimData getDimensionData(int dimensionID)
{
//Retrieve the data for a dimension. If we don't have a record for that dimension,
//assume it's a non-pocket dimension that hasn't been initialized with us before
//and create a NewDimData instance for it.
//Any pocket dimension must be listed with PocketManager to have a dimension ID
//assigned, so it's safe to assume that any unknown dimensions don't belong to us.
//FIXME: What's the point of this condition? Most calls to this function will crash anyway! ~SenseiKiwi
if(PocketManager.dimensionData == null)
{
System.out.println("Something odd happend during shutdown");
return null;
}
NewDimData dimension = PocketManager.dimensionData.get(dimensionID);
if (dimension == null)
{
dimension = registerDimension(dimensionID, null, false, false);
}
return dimension;
}
public static Iterable<? extends NewDimData> getDimensions()
{
return dimensionData.values();
}
@SuppressWarnings("unchecked")
public static ArrayList<NewDimData> getRootDimensions()
{
return (ArrayList<NewDimData>) rootDimensions.clone();
}
public static void unload()
{
System.out.println("Unloading Pocket Dimensions...");
if (!isLoaded)
{
throw new IllegalStateException("Pocket dimensions have already been unloaded!");
}
unregisterPockets();
dimensionData = null;
rootDimensions = null;
isLoaded = false;
isConnected = false;
}
public static DimLink getLink(int x, int y, int z, World world)
{
return getLink(x, y, z, world.provider.dimensionId);
}
public static DimLink getLink(Point4D point)
{
return getLink(point.getX(), point.getY(), point.getZ(), point.getDimension());
}
public static DimLink getLink(int x, int y, int z, int dimensionID)
{
NewDimData dimension = dimensionData.get(dimensionID);
if (dimension != null)
{
return dimension.getLink(x, y, z);
}
else
{
return null;
}
}
public static boolean isBlackListed(int dimensionID)
{
return PocketManager.dimensionIDBlackList.contains(dimensionID);
}
public static void registerDimWatcher(IUpdateWatcher<ClientDimData> watcher)
{
getDimwatcher().registerReceiver(watcher);
}
public static boolean unregisterDimWatcher(IUpdateWatcher<ClientDimData> watcher)
{
return getDimwatcher().unregisterReceiver(watcher);
}
public static void registerLinkWatcher(IUpdateWatcher<ClientLinkData> watcher)
{
linkWatcher.registerReceiver(watcher);
}
public static boolean unregisterLinkWatcher(IUpdateWatcher<ClientLinkData> watcher)
{
return linkWatcher.unregisterReceiver(watcher);
}
public static void getWatchers(IUpdateSource updateSource)
{
updateSource.registerWatchers(new ClientDimWatcher(), new ClientLinkWatcher());
}
public static void writePacket(DataOutputStream output) throws IOException
{
// Write a very compact description of our dimensions and links to be sent to a client
Compactor.write(dimensionData.values(), output);
}
public static boolean isRegisteredInternally(int dimensionID)
{
return dimensionData.containsKey(dimensionID);
}
public static void createAndRegisterBlacklist(List<Integer> blacklist)
{
//TODO - create a special blacklist provider
for(Integer dimID : blacklist)
{
PocketManager.dimensionIDBlackList.add(dimID);
DimensionManager.registerDimension(dimID, DDProperties.instance().PocketProviderID);
}
}
public static void readPacket(DataInputStream input) throws IOException
{
//TODO- figure out why this is getting called so frequently
if (isLoaded)
{
return;
}
if (isLoading)
{
throw new IllegalStateException("Pocket dimensions are already loading!");
}
// Load compacted client-side dimension data
load();
Compactor.readDimensions(input, new DimRegistrationCallback());
// Register pocket dimensions
DDProperties properties = DDProperties.instance();
isLoaded = true;
isLoading = false;
isConnected = true;
}
public static UpdateWatcherProxy<ClientDimData> getDimwatcher()
{
return dimWatcher;
}
}
| Simplified PocketManager
1. Rewrote or removed a few bits that were causing minor warnings.
2. Rewrote deleteDimensionFiles() and deleteDimensionData() to remove
unnecessary casts and checks. We can confirm that those checks are
unnecessary because those functions are only used inside PocketManager.
If they were ever exposed externally, then we would need to add checks
again.
| src/main/java/StevenDimDoors/mod_pocketDim/core/PocketManager.java | Simplified PocketManager | <ide><path>rc/main/java/StevenDimDoors/mod_pocketDim/core/PocketManager.java
<ide> {
<ide> if (deleteFolder)
<ide> {
<del> deleteDimensionFiles(target);
<add> deleteDimensionFiles(dimension);
<ide> }
<ide> dimensionIDBlackList.add(dimension.id);
<del> deleteDimensionData(dimension.id);
<add> deleteDimensionData(dimension);
<ide> return true;
<ide> }
<ide> return false;
<ide> }
<ide>
<del> private static boolean deleteDimensionFiles(NewDimData target)
<del> {
<del> InnerDimData dimension = (InnerDimData) target;
<del> if (dimension.isPocketDimension() && DimensionManager.getWorld(dimension.id()) == null)
<del> {
<del> String saveRootPath = DimensionManager.getCurrentSaveRootDirectory().getAbsolutePath();
<del> File saveDirectory = new File(saveRootPath + "/DimensionalDoors/pocketDimID" + dimension.id());
<del> DeleteFolder.deleteFolder(saveDirectory);
<del> File dataFile = new File(saveRootPath + "/DimensionalDoors/data/dim_" + dimension.id() + ".txt");
<del> dataFile.delete();
<del> return true;
<del> }
<del> return false;
<del> }
<del>
<del> private static boolean deleteDimensionData(int dimensionID)
<del> {
<del> if (dimensionData.containsKey(dimensionID) && DimensionManager.getWorld(dimensionID) == null)
<del> {
<del> NewDimData target = PocketManager.getDimensionData(dimensionID);
<del> InnerDimData dimension = (InnerDimData) target;
<del>
<del> dimensionData.remove(dimensionID);
<add> private static void deleteDimensionFiles(InnerDimData dimension)
<add> {
<add> // We assume that the caller checks if the dimension is loaded, for the
<add> // sake of efficiency. Don't call this on a loaded dimension or bad
<add> // things will happen!
<add> String saveRootPath = DimensionManager.getCurrentSaveRootDirectory().getAbsolutePath();
<add> File saveDirectory = new File(saveRootPath + "/DimensionalDoors/pocketDimID" + dimension.id());
<add> DeleteFolder.deleteFolder(saveDirectory);
<add> File dataFile = new File(saveRootPath + "/DimensionalDoors/data/dim_" + dimension.id() + ".txt");
<add> dataFile.delete();
<add> }
<add>
<add> private static void deleteDimensionData(InnerDimData dimension)
<add> {
<add> // We assume that the caller checks if the dimension is loaded, for the
<add> // sake of efficiency. Don't call this on a loaded dimension or bad
<add> // things will happen!
<add> if (dimensionData.remove(dimension.id()) != null)
<add> {
<ide> // Raise the dim deleted event
<ide> getDimwatcher().onDeleted(new ClientDimData(dimension));
<ide> dimension.clear();
<del> return true;
<del> }
<del> return false;
<add> }
<add> else
<add> {
<add> // This should never happen. A simple sanity check.
<add> throw new IllegalArgumentException("The specified dimension is not listed with PocketManager.");
<add> }
<ide> }
<ide>
<ide> private static void registerPockets(DDProperties properties)
<ide> {
<ide> return dimension.getLink(x, y, z);
<ide> }
<del> else
<del> {
<del> return null;
<del> }
<add> return null;
<ide> }
<ide>
<ide> public static boolean isBlackListed(int dimensionID)
<ide> // Load compacted client-side dimension data
<ide> load();
<ide> Compactor.readDimensions(input, new DimRegistrationCallback());
<del>
<del> // Register pocket dimensions
<del> DDProperties properties = DDProperties.instance();
<ide>
<ide> isLoaded = true;
<ide> isLoading = false; |
|
Java | apache-2.0 | 95fc9c8bb30197a951959c33d9874471012e8533 | 0 | yp-creative/yop-java-sdk-old,yp-creative/yop-java-sdk-old | package com.yeepay.g3.sdk.yop.client;
import com.yeepay.g3.sdk.yop.exception.YopClientException;
import com.yeepay.g3.sdk.yop.unmarshaller.JacksonJsonMarshaller;
import com.yeepay.g3.sdk.yop.utils.Assert;
import com.yeepay.g3.sdk.yop.utils.InternalConfig;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
public class AbstractClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractClient.class);
private static final String REST_PREFIX = "/rest/v";
private static CloseableHttpClient httpClient;
private static org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder;
private static CredentialsProvider credentialsProvider;
private static HttpHost proxyHttpHost;
static {
initApacheHttpClient();
}
// 创建包含connection pool与超时设置的client
public static void initApacheHttpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(InternalConfig.READ_TIMEOUT)
.setConnectTimeout(InternalConfig.CONNECT_TIMEOUT)
.build();
httpClient = HttpClientBuilder.create()
.setMaxConnTotal(InternalConfig.MAX_CONN_TOTAL)
.setMaxConnPerRoute(InternalConfig.MAX_CONN_PER_ROUTE)
.setSSLSocketFactory(InternalConfig.TRUST_ALL_CERTS ? getTrustedAllSSLConnectionSocketFactory() : null)
.setDefaultRequestConfig(requestConfig)
.evictExpiredConnections()
.evictIdleConnections(5000, TimeUnit.MILLISECONDS)
.setRetryHandler(new YopHttpRequestRetryHandler())
.build();
requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectTimeout(InternalConfig.CONNECT_TIMEOUT);
requestConfigBuilder.setStaleConnectionCheckEnabled(true);
/*if (InternalConfig.getLocalAddress() != null) {
requestConfigBuilder.setLocalAddress(config.getLocalAddress());
}*/
if (InternalConfig.proxy != null) {
String proxyHost = InternalConfig.proxy.getHost();
int proxyPort = InternalConfig.proxy.getPort();
if (proxyHost != null && proxyPort > 0) {
proxyHttpHost = new HttpHost(proxyHost, proxyPort);
requestConfigBuilder.setProxy(proxyHttpHost);
credentialsProvider = new BasicCredentialsProvider();
String proxyUsername = InternalConfig.proxy.getUsername();
String proxyPassword = InternalConfig.proxy.getPassword();
String proxyDomain = InternalConfig.proxy.getDomain();
String proxyWorkstation = InternalConfig.proxy.getWorkstation();
if (proxyUsername != null && proxyPassword != null) {
credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
new NTCredentials(proxyUsername, proxyPassword,
proxyWorkstation, proxyDomain));
}
}
}
}
public static void destroyApacheHttpClient() {
try {
httpClient.close();
} catch (IOException e) {
LOGGER.error("httpclient close fail", e);
}
}
private static SSLConnectionSocketFactory getTrustedAllSSLConnectionSocketFactory() {
LOGGER.warn("[yop-sdk]已设置信任所有证书。仅供内测使用,请勿在生产环境配置。");
SSLConnectionSocketFactory sslConnectionSocketFactory = null;
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
} catch (Exception e) {
LOGGER.error("error when get trust-all-certs request factory,will return normal request factory instead", e);
}
return sslConnectionSocketFactory;
}
protected static YopResponse fetchContentByApacheHttpClient(HttpUriRequest request) throws IOException {
HttpContext httpContext = createHttpContext();
CloseableHttpResponse remoteResponse = null;
try {
remoteResponse = getHttpClient().execute(request, httpContext);
return parseResponse(remoteResponse);
} finally {
HttpClientUtils.closeQuietly(remoteResponse);
}
}
protected static YopResponse parseResponse(CloseableHttpResponse response) throws IOException {
YopHttpResponse httpResponse = new YopHttpResponse(response);
if (httpResponse.getStatusCode() / 100 == HttpStatus.SC_OK / 100) {
//not a error
YopResponse yopResponse = new YopResponse();
yopResponse.setState("SUCCESS");
yopResponse.setRequestId(httpResponse.getHeader(Headers.YOP_REQUEST_ID));
if (httpResponse.getContent() != null) {
yopResponse.setStringResult(IOUtils.toString(httpResponse.getContent(), YopConstants.ENCODING));
}
if (StringUtils.isNotBlank(yopResponse.getStringResult())) {
yopResponse.setResult(JacksonJsonMarshaller.unmarshal(yopResponse.getStringResult(), Object.class));
}
yopResponse.setValidSign(true);
return yopResponse;
} else if (httpResponse.getStatusCode() >= 500) {
if (httpResponse.getContent() != null) {
YopResponse yopResponse = new YopResponse();
yopResponse.setState("FAILURE");
YopErrorResponse errorResponse = JacksonJsonMarshaller.unmarshal(httpResponse.getContent(),
YopErrorResponse.class);
yopResponse.setRequestId(errorResponse.getRequestId());
yopResponse.setError(YopError.Builder.anYopError()
.withCode(errorResponse.getCode())
.withSubCode(errorResponse.getSubCode())
.withMessage(errorResponse.getMessage())
.withSubMessage(errorResponse.getSubMessage())
.build());
yopResponse.setValidSign(true);
return yopResponse;
} else {
throw new YopClientException("empty result with httpStatusCode:" + httpResponse.getStatusCode());
}
}
throw new YopClientException("unexpected httpStatusCode:" + httpResponse.getStatusCode());
}
/**
* Creates HttpClient Context object based on the internal request.
*
* @return HttpClient Context object.
*/
private static HttpClientContext createHttpContext() {
HttpClientContext context = HttpClientContext.create();
context.setRequestConfig(requestConfigBuilder.build());
if (credentialsProvider != null) {
context.setCredentialsProvider(credentialsProvider);
}
/*if (config.isProxyPreemptiveAuthenticationEnabled()) {
AuthCache authCache = new BasicAuthCache();
authCache.put(proxyHttpHost, new BasicScheme());
context.setAuthCache(authCache);
}*/
return context;
}
public static CloseableHttpClient getHttpClient() {
return httpClient;
}
protected static String richRequest(String methodOrUri, YopRequest request) {
Assert.hasText(methodOrUri, "method name or rest uri");
String requestRoot = MapUtils.isNotEmpty(request.getMultipartFiles()) ? request.getAppSdkConfig().getYosServerRoot() :
request.getAppSdkConfig().getServerRoot();
String path = methodOrUri;
if (StringUtils.startsWith(methodOrUri, requestRoot)) {
path = StringUtils.substringAfter(methodOrUri, requestRoot);
}
if (!StringUtils.startsWith(path, REST_PREFIX)) {
throw new YopClientException("Unsupported request method.");
}
/*v and method are always needed because of old signature implementation...*/
request.setParam(YopConstants.VERSION, StringUtils.substringBetween(methodOrUri, REST_PREFIX, "/"));
request.setParam(YopConstants.METHOD, methodOrUri);
return requestRoot + path;
}
}
| src/main/java/com/yeepay/g3/sdk/yop/client/AbstractClient.java | package com.yeepay.g3.sdk.yop.client;
import com.yeepay.g3.sdk.yop.exception.YopClientException;
import com.yeepay.g3.sdk.yop.unmarshaller.JacksonJsonMarshaller;
import com.yeepay.g3.sdk.yop.utils.Assert;
import com.yeepay.g3.sdk.yop.utils.InternalConfig;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
public class AbstractClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractClient.class);
private static final String REST_PREFIX = "/rest/v";
private static CloseableHttpClient httpClient;
private static org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder;
private static CredentialsProvider credentialsProvider;
private static HttpHost proxyHttpHost;
static {
initApacheHttpClient();
}
// 创建包含connection pool与超时设置的client
public static void initApacheHttpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(InternalConfig.READ_TIMEOUT)
.setConnectTimeout(InternalConfig.CONNECT_TIMEOUT)
.build();
httpClient = HttpClientBuilder.create()
.setMaxConnTotal(InternalConfig.MAX_CONN_TOTAL)
.setMaxConnPerRoute(InternalConfig.MAX_CONN_PER_ROUTE)
.setSSLSocketFactory(InternalConfig.TRUST_ALL_CERTS ? getTrustedAllSSLConnectionSocketFactory() : null)
.setDefaultRequestConfig(requestConfig)
.evictExpiredConnections()
.evictIdleConnections(5000, TimeUnit.MILLISECONDS)
.setRetryHandler(new YopHttpRequestRetryHandler())
.build();
requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectTimeout(InternalConfig.CONNECT_TIMEOUT);
requestConfigBuilder.setStaleConnectionCheckEnabled(true);
/*if (InternalConfig.getLocalAddress() != null) {
requestConfigBuilder.setLocalAddress(config.getLocalAddress());
}*/
if (InternalConfig.proxy != null) {
String proxyHost = InternalConfig.proxy.getHost();
int proxyPort = InternalConfig.proxy.getPort();
if (proxyHost != null && proxyPort > 0) {
proxyHttpHost = new HttpHost(proxyHost, proxyPort);
requestConfigBuilder.setProxy(proxyHttpHost);
credentialsProvider = new BasicCredentialsProvider();
String proxyUsername = InternalConfig.proxy.getUsername();
String proxyPassword = InternalConfig.proxy.getPassword();
String proxyDomain = InternalConfig.proxy.getDomain();
String proxyWorkstation = InternalConfig.proxy.getWorkstation();
if (proxyUsername != null && proxyPassword != null) {
credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
new NTCredentials(proxyUsername, proxyPassword,
proxyWorkstation, proxyDomain));
}
}
}
}
public static void destroyApacheHttpClient() {
try {
httpClient.close();
} catch (IOException e) {
LOGGER.error("httpclient close fail", e);
}
}
private static SSLConnectionSocketFactory getTrustedAllSSLConnectionSocketFactory() {
LOGGER.warn("[yop-sdk]已设置信任所有证书。仅供内测使用,请勿在生产环境配置。");
SSLConnectionSocketFactory sslConnectionSocketFactory = null;
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
} catch (Exception e) {
LOGGER.error("error when get trust-all-certs request factory,will return normal request factory instead", e);
}
return sslConnectionSocketFactory;
}
protected static YopResponse fetchContentByApacheHttpClient(HttpUriRequest request) throws IOException {
HttpContext httpContext = createHttpContext();
CloseableHttpResponse remoteResponse = null;
try {
remoteResponse = getHttpClient().execute(request, httpContext);
return parseResponse(remoteResponse);
} finally {
HttpClientUtils.closeQuietly(remoteResponse);
}
}
protected static YopResponse parseResponse(CloseableHttpResponse response) throws IOException {
YopHttpResponse httpResponse = new YopHttpResponse(response);
if (httpResponse.getStatusCode() / 100 == HttpStatus.SC_OK / 100) {
//not a error
YopResponse yopResponse = new YopResponse();
yopResponse.setState("success");
yopResponse.setRequestId(httpResponse.getHeader(Headers.YOP_REQUEST_ID));
if (httpResponse.getContent() != null) {
yopResponse.setStringResult(IOUtils.toString(httpResponse.getContent(), YopConstants.ENCODING));
}
if (StringUtils.isNotBlank(yopResponse.getStringResult())) {
yopResponse.setResult(JacksonJsonMarshaller.unmarshal(yopResponse.getStringResult(), Object.class));
}
yopResponse.setValidSign(true);
return yopResponse;
} else if (httpResponse.getStatusCode() >= 500) {
if (httpResponse.getContent() != null) {
YopResponse yopResponse = new YopResponse();
yopResponse.setState("failure");
YopErrorResponse errorResponse = JacksonJsonMarshaller.unmarshal(httpResponse.getContent(),
YopErrorResponse.class);
yopResponse.setRequestId(errorResponse.getRequestId());
yopResponse.setError(YopError.Builder.anYopError()
.withCode(errorResponse.getCode())
.withSubCode(errorResponse.getSubCode())
.withMessage(errorResponse.getMessage())
.withSubMessage(errorResponse.getSubMessage())
.build());
yopResponse.setValidSign(true);
return yopResponse;
} else {
throw new YopClientException("empty result with httpStatusCode:" + httpResponse.getStatusCode());
}
}
throw new YopClientException("unexpected httpStatusCode:" + httpResponse.getStatusCode());
}
/**
* Creates HttpClient Context object based on the internal request.
*
* @return HttpClient Context object.
*/
private static HttpClientContext createHttpContext() {
HttpClientContext context = HttpClientContext.create();
context.setRequestConfig(requestConfigBuilder.build());
if (credentialsProvider != null) {
context.setCredentialsProvider(credentialsProvider);
}
/*if (config.isProxyPreemptiveAuthenticationEnabled()) {
AuthCache authCache = new BasicAuthCache();
authCache.put(proxyHttpHost, new BasicScheme());
context.setAuthCache(authCache);
}*/
return context;
}
public static CloseableHttpClient getHttpClient() {
return httpClient;
}
protected static String richRequest(String methodOrUri, YopRequest request) {
Assert.hasText(methodOrUri, "method name or rest uri");
String requestRoot = MapUtils.isNotEmpty(request.getMultipartFiles()) ? request.getAppSdkConfig().getYosServerRoot() :
request.getAppSdkConfig().getServerRoot();
String path = methodOrUri;
if (StringUtils.startsWith(methodOrUri, requestRoot)) {
path = StringUtils.substringAfter(methodOrUri, requestRoot);
}
if (!StringUtils.startsWith(path, REST_PREFIX)) {
throw new YopClientException("Unsupported request method.");
}
/*v and method are always needed because of old signature implementation...*/
request.setParam(YopConstants.VERSION, StringUtils.substringBetween(methodOrUri, REST_PREFIX, "/"));
request.setParam(YopConstants.METHOD, methodOrUri);
return requestRoot + path;
}
}
| fix: 返回结果状态大写,与以前保持一致
| src/main/java/com/yeepay/g3/sdk/yop/client/AbstractClient.java | fix: 返回结果状态大写,与以前保持一致 | <ide><path>rc/main/java/com/yeepay/g3/sdk/yop/client/AbstractClient.java
<ide> if (httpResponse.getStatusCode() / 100 == HttpStatus.SC_OK / 100) {
<ide> //not a error
<ide> YopResponse yopResponse = new YopResponse();
<del> yopResponse.setState("success");
<add> yopResponse.setState("SUCCESS");
<ide> yopResponse.setRequestId(httpResponse.getHeader(Headers.YOP_REQUEST_ID));
<ide> if (httpResponse.getContent() != null) {
<ide> yopResponse.setStringResult(IOUtils.toString(httpResponse.getContent(), YopConstants.ENCODING));
<ide> } else if (httpResponse.getStatusCode() >= 500) {
<ide> if (httpResponse.getContent() != null) {
<ide> YopResponse yopResponse = new YopResponse();
<del> yopResponse.setState("failure");
<add> yopResponse.setState("FAILURE");
<ide> YopErrorResponse errorResponse = JacksonJsonMarshaller.unmarshal(httpResponse.getContent(),
<ide> YopErrorResponse.class);
<ide> yopResponse.setRequestId(errorResponse.getRequestId()); |
|
Java | agpl-3.0 | 0c538a41d46bb3af52e776b0d76a7ee2a08292a3 | 0 | Audiveris/audiveris,Audiveris/audiveris | //----------------------------------------------------------------------------//
// //
// B a r s B u i l d e r //
// //
// Copyright (C) Herve Bitteur 2000-2006. All rights reserved. //
// This software is released under the terms of the GNU General Public //
// License. Please contact the author at [email protected] //
// to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
package omr.sheet;
import omr.Main;
import omr.ProcessingException;
import omr.check.CheckBoard;
import omr.check.CheckSuite;
import omr.check.FailureResult;
import omr.constant.Constant;
import omr.constant.ConstantSet;
import omr.glyph.Glyph;
import omr.glyph.GlyphLag;
import omr.glyph.GlyphModel;
import omr.glyph.GlyphSection;
import omr.glyph.Shape;
import omr.glyph.ui.GlyphBoard;
import omr.glyph.ui.GlyphLagView;
import omr.lag.JunctionDeltaPolicy;
import omr.lag.LagBuilder;
import omr.lag.RunBoard;
import omr.lag.ScrollLagView;
import omr.lag.SectionBoard;
import omr.lag.VerticalOrientation;
import omr.score.Barline;
import omr.score.Measure;
import omr.score.Score;
import omr.score.ScoreConstants;
import omr.score.Staff;
import omr.score.System;
import omr.score.SystemPart;
import omr.score.UnitDimension;
import omr.score.visitor.ComputingVisitor;
import omr.score.visitor.RenderingVisitor;
import omr.selection.Selection;
import omr.selection.SelectionHint;
import omr.selection.SelectionTag;
import static omr.selection.SelectionTag.*;
import omr.stick.Stick;
import omr.stick.StickSection;
import omr.ui.BoardsPane;
import omr.ui.PixelBoard;
import static omr.ui.field.SpinnerUtilities.*;
import omr.util.Dumper;
import omr.util.Logger;
import omr.util.TreeNode;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* Class <code>BarsBuilder</code> handles the vertical lines that are recognized
* as bar lines. This class uses a dedicated companion named {@link
* omr.sheet.BarsChecker} which handles physical checks.
*
* <p> Input is provided by the list of vertical sticks retrieved by the
* preceding step.
*
* <p> Output is the collection of detected Bar lines.
*
* @author Hervé Bitteur
* @version $Id$
*/
public class BarsBuilder
extends GlyphModel
{
//~ Static fields/initializers ---------------------------------------------
private static final Constants constants = new Constants();
private static final Logger logger = Logger.getLogger(
BarsBuilder.class);
/** Failure */
private static final FailureResult NOT_SYSTEM_ALIGNED = new FailureResult(
"Bar-NotSystemAligned");
private static final FailureResult SHORTER_THAN_STAFF_HEIGHT = new FailureResult(
"Bar-ShorterThanStaffHeight");
private static final FailureResult THICK_BAR_NOT_ALIGNED = new FailureResult(
"Bar-ThickBarNotAligned");
private static final FailureResult CANCELLED = new FailureResult(
"Bar-Cancelled");
//~ Instance fields --------------------------------------------------------
/** Companion physical stick checker */
private BarsChecker checker;
/** Lag view on bars, if so desired */
private GlyphLagView lagView;
/** List of found bar sticks */
private List<Stick> bars = new ArrayList<Stick>();
/** Unused vertical sticks */
private List<Stick> clutter;
/** Sheet scale */
private Scale scale;
/** Related score */
private Score score;
/** Bars area, with retrieved vertical sticks */
private VerticalArea barsArea;
//~ Constructors -----------------------------------------------------------
//-------------//
// BarsBuilder //
//-------------//
/**
* Prepare a bar retriever on the provided sheet
*
* @param sheet the sheet to process
*/
public BarsBuilder (Sheet sheet)
{
super(sheet, new GlyphLag(new VerticalOrientation()));
}
//~ Methods ----------------------------------------------------------------
//-----------//
// setBraces //
//-----------//
/**
* Pass the braces symbols found, so that score parts can be defined
*
* @param braceLists the braces, system per system
*/
public void setBraces (List<List<Glyph>> braceLists)
{
int is = 0;
for (SystemInfo systemInfo : sheet.getSystems()) {
setSystemBraces(systemInfo.getScoreSystem(), braceLists.get(is++));
}
// Repaint the score view, if any (TBI)
if (sheet.getScore()
.getView() != null) {
sheet.getScore()
.getView()
.getScrollPane()
.getView()
.repaint();
}
}
//-----------//
// buildInfo //
//-----------//
/**
* Retrieve and store the bars information on the provided sheet
*
* @throws ProcessingException raised when step processing must stop, due to
* encountered error
*/
public void buildInfo ()
throws ProcessingException
{
// Stuff to be made available
scale = sheet.getScale();
sheet.getHorizontals();
// Augment the vertical lag of runs
lag.setName("vLag");
lag.setVertexClass(StickSection.class);
new LagBuilder<GlyphLag, GlyphSection>().rip(
lag,
sheet.getPicture(),
0, // minRunLength
new JunctionDeltaPolicy(constants.maxDeltaLength.getValue())); // maxDeltaLength
sheet.setVerticalLag(lag);
// Retrieve (vertical) sticks
barsArea = new VerticalArea(
sheet,
lag,
scale.toPixels(constants.maxBarThickness));
clutter = new ArrayList<Stick>(barsArea.getSticks());
// Allocate score
createScore();
// Delegate to BarsChecker companion
checker = new BarsChecker(sheet);
checker.retrieveMeasures(clutter, bars);
// Assign bar line shape
for (Stick stick : bars) {
stick.setShape(
checker.isThickBar(stick) ? Shape.THICK_BAR_LINE
: Shape.THIN_BAR_LINE);
stick.setInterline(sheet.getScale().interline());
}
// Check Measures using only score parameters
checkMeasures();
// With now neat staff measures, let's allocate the systems measure frames
//////createMeasureFrames();
// Erase bar pixels from picture
//////eraseBars();
// Update score internal data
score.accept(new ComputingVisitor());
// Report number of measures retrieved
logger.info(
score.getLastSystem().getLastMeasureId() + " measure(s) found");
// Split everything, including horizontals, per system
SystemSplit.computeSystemLimits(sheet);
SystemSplit.splitHorizontals(sheet);
SystemSplit.splitBars(sheet, bars);
// Display the resulting stickarea if so asked for
if (constants.displayFrame.getValue() && (Main.getJui() != null)) {
displayFrame();
}
}
//--------------------//
// deassignGlyphShape //
//--------------------//
/**
* Remove a bar together with all its related entities. This means removing
* reference in the bars list of this builder, reference in the containing
* SystemInfo, reference in the Measure it ends, and removing this Measure
* itself if this (false) bar was the only ending bar left for the
* Measure. The related stick must also be assigned a failure result.
*
* @param glyph the (false) bar glyph to deassign
*/
@Override
public void deassignGlyphShape (Glyph glyph)
{
if ((glyph.getShape() == Shape.THICK_BAR_LINE) ||
(glyph.getShape() == Shape.THIN_BAR_LINE)) {
Stick bar = getBarOf(glyph);
if (bar == null) {
return;
} else {
logger.info("Deassigning a " + glyph.getShape());
}
// Related stick has to be freed
bar.setShape(null);
bar.setResult(CANCELLED);
// Remove from the internal all-bars list
bars.remove(bar);
// Remove from the containing SystemInfo
SystemInfo system = checker.getSystemOf(bar, sheet);
if (system == null) {
return;
} else {
system.getBars()
.remove(bar);
}
// Remove from the containing Measure
System scoreSystem = system.getScoreSystem();
for (Iterator it = scoreSystem.getStaves()
.iterator(); it.hasNext();) {
Staff staff = (Staff) it.next();
if (checker.isStaffEmbraced(staff, bar)) {
for (Iterator mit = staff.getMeasures()
.iterator(); mit.hasNext();) {
Measure measure = (Measure) mit.next();
// for (Iterator bit = measure.getInfos().iterator();
// bit.hasNext();) {
// BarInfo info = (BarInfo) bit.next();
// if (info == bar) {
// // Remove the bar info
// if (logger.isFineEnabled()) {
// logger.fine("Removing " + info +
// " from " + measure);
// }
// bit.remove();
//
// // Remove measure as well ?
// if (measure.getInfos().size() == 0) {
// if (logger.isFineEnabled()) {
// logger.fine("Removing " + measure);
// }
// mit.remove();
// }
//
// break;
// }
// }
}
}
}
assignGlyphShape(glyph, null);
// Update the view accordingly
if (lagView != null) {
lagView.colorize();
lagView.repaint();
}
} else {
BarsBuilder.logger.warning(
"No deassign meant for " + glyph.getShape() + " glyph");
}
}
//----------//
// getBarOf //
//----------//
private Stick getBarOf (Glyph glyph)
{
for (Stick bar : bars) {
if (bar == glyph) {
return bar;
}
}
logger.warning("Cannot find bar for " + glyph);
return null;
}
//-----------------//
// setSystemBraces //
//-----------------//
/**
* Pass the braces symbols found for one system
*
* @param braces list of braces for this system
*/
private void setSystemBraces (System system,
List<Glyph> braces)
{
// Map Staff -> its containing staves ensemble (= Part)
Map<Staff, List<Staff>> ensembles = new HashMap<Staff, List<Staff>>();
// Inspect each brace in turn
for (Glyph brace : braces) {
List<Staff> ensemble = new ArrayList<Staff>();
// Inspect all staves for this brace
for (TreeNode node : system.getStaves()) {
Staff staff = (Staff) node;
if (checker.isStaffEmbraced(staff, brace)) {
ensemble.add(staff);
ensembles.put(staff, ensemble);
}
}
if (ensemble.size() == 0) {
logger.warning(
"Brace with no embraced staves at all: " + brace.getId());
}
}
// Now build the parts by looking back at all staves
List<SystemPart> parts = new ArrayList<SystemPart>();
List<Staff> currentEnsemble = null;
for (TreeNode node : system.getStaves()) {
Staff staff = (Staff) node;
List<Staff> ensemble = ensembles.get(staff);
if (ensemble == null) {
// Standalone staff, a part by itself
parts.add(new SystemPart(Arrays.asList(staff)));
} else {
// Staff is in a part
if (ensemble != currentEnsemble) {
parts.add(new SystemPart(ensemble));
} else {
// Nothing to do
}
}
currentEnsemble = ensemble;
}
// Dump
StringBuilder sb = new StringBuilder();
for (SystemPart part : parts) {
sb.append("[");
for (Staff staff : part.getStaves()) {
sb.append(" ")
.append(staff.getStafflink());
}
sb.append("] ");
}
logger.info(system + " Parts: " + sb);
// Assign the parts to the system
system.setParts(parts);
}
//--------------------//
// checkBarAlignments //
//--------------------//
/**
* Check alignment of each measure of each staff with the other staff
* measures, a test that needs several staves in the system
*
* @param system the system to check
*/
private void checkBarAlignments (omr.score.System system)
{
if (system.getStaves()
.size() > 1) {
int maxShiftDx = scale.toPixels(constants.maxAlignShiftDx);
for (Iterator sit = system.getStaves()
.iterator(); sit.hasNext();) {
Staff staff = (Staff) sit.next();
for (Iterator mit = staff.getMeasures()
.iterator(); mit.hasNext();) {
Measure measure = (Measure) mit.next();
if (logger.isFineEnabled()) {
logger.fine("Checking alignment of " + measure);
}
// Compare the abscissa with corresponding position in
// the other staves
int x = measure.getBarline()
.getCenter().x;
for (Iterator it = system.getStaves()
.iterator(); it.hasNext();) {
Staff stv = (Staff) it.next();
if (stv == staff) {
continue;
}
if (!stv.barlineExists(x, maxShiftDx)) {
if (logger.isFineEnabled()) {
logger.fine(
"Singular measure removed: " +
Dumper.dumpOf(measure));
}
// Remove the false bar info
for (Stick stick : measure.getBarline()
.getSticks()) {
stick.setResult(NOT_SYSTEM_ALIGNED);
bars.remove(stick);
}
// Remove the false measure
mit.remove();
break;
}
}
}
}
}
}
//----------------//
// checkEndingBar //
//----------------//
/**
* Use ending bar line if any, to adjust the right abscissa of the system
* and its staves.
*
* @param system the system to check
*/
private void checkEndingBar (omr.score.System system)
{
Staff staff = system.getFirstStaff();
Measure measure = staff.getLastMeasure();
Barline barline = measure.getBarline();
int lastX = barline.getRightX();
int minWidth = scale.toPixels(constants.minMeasureWidth);
if ((staff.getWidth() - lastX) < minWidth) {
if (logger.isFineEnabled()) {
logger.fine("Adjusting EndingBar " + system);
}
// Adjust end of system & staff(s) to this one
UnitDimension dim = system.getDimension();
if (dim == null) {
system.setDimension(new UnitDimension(lastX, 0));
} else {
dim.width = lastX;
}
for (Iterator sit = system.getStaves()
.iterator(); sit.hasNext();) {
Staff stv = (Staff) sit.next();
stv.setWidth(system.getDimension().width);
}
}
}
//---------------//
// checkMeasures //
//---------------//
/**
* Check measure reality, using a set of additional tests.
*/
private void checkMeasures ()
{
// Check are performed on a system basis
for (TreeNode node : score.getSystems()) {
omr.score.System system = (omr.score.System) node;
// Check alignment of each measure of each staff with the other
// staff measures, a test that needs several staves in the system
checkBarAlignments(system);
// Detect very narrow measures which in fact indicate double bar
// lines.
mergeBarlines(system);
// First barline may be just the beginning of the staff, so do not
// count the very first bar line, which in general defines the
// beginning of the staff rather than the end of a measure, but use
// it to precisely define the left abscissa of the system and all
// its contained staves.
removeStartingBar(system);
// Similarly, use the very last bar line, which generally ends the
// system, to define the right abscissa of the system and its
// staves.
checkEndingBar(system);
}
}
//-------------//
// createScore //
//-------------//
private void createScore ()
{
if (logger.isFineEnabled()) {
logger.fine("Allocating score");
}
score = new Score(
scale.toUnits(
new PixelDimension(sheet.getWidth(), sheet.getHeight())),
(int) Math.rint(sheet.getSkew().angle() * ScoreConstants.BASE),
scale.spacing(),
sheet.getPath());
// Mutual referencing
score.setSheet(sheet);
sheet.setScore(score);
}
//--------------//
// displayFrame //
//--------------//
private void displayFrame ()
{
Selection glyphSelection = sheet.getSelection(VERTICAL_GLYPH);
lagView = new MyLagView(lag);
lagView.setGlyphSelection(glyphSelection);
glyphSelection.addObserver(lagView);
lagView.colorize();
final String unit = "BarsBuilder";
BoardsPane boardsPane = new BoardsPane(
sheet,
lagView,
new PixelBoard(unit),
new RunBoard(unit, sheet.getSelection(VERTICAL_RUN)),
new SectionBoard(
unit,
lag.getLastVertexId(),
sheet.getSelection(VERTICAL_SECTION),
sheet.getSelection(VERTICAL_SECTION_ID)),
new GlyphBoard(
unit,
this,
sheet.getSelection(VERTICAL_GLYPH),
sheet.getSelection(VERTICAL_GLYPH_ID),
sheet.getSelection(GLYPH_SET)),
new MyCheckBoard(
unit,
checker.getSuite(),
sheet.getSelection(VERTICAL_GLYPH)));
// Create a hosting frame for the view
ScrollLagView slv = new ScrollLagView(lagView);
sheet.getAssembly()
.addViewTab("Bars", slv, boardsPane);
}
//---------------//
// mergeBarlines //
//---------------//
/**
* Check whether two close bar lines are not in fact double lines (with
* variants)
*
* @param system the system to check
*/
private void mergeBarlines (omr.score.System system)
{
int maxDoubleDx = scale.toPixels(constants.maxDoubleBarDx);
for (Iterator sit = system.getStaves()
.iterator(); sit.hasNext();) {
Staff staff = (Staff) sit.next();
Measure prevMeasure = null;
for (Iterator mit = staff.getMeasures()
.iterator(); mit.hasNext();) {
Measure measure = (Measure) mit.next();
if (prevMeasure != null) {
final int measureWidth = measure.getBarline()
.getCenter().x -
prevMeasure.getBarline()
.getCenter().x;
if (measureWidth <= maxDoubleDx) {
// Merge the two bar lines into the first one
prevMeasure.getBarline()
.mergeWith(measure.getBarline());
if (logger.isFineEnabled()) {
logger.fine(
"Merged two barlines into " +
prevMeasure.getBarline());
}
mit.remove();
} else {
prevMeasure = measure;
}
} else {
prevMeasure = measure;
}
}
}
}
//-------------------//
// removeStartingBar //
//-------------------//
/**
* We associate measures only with their ending bar line(s), so the starting
* bar of a staff does not end a measure, we thus have to remove the measure
* that we first had associated with it.
*
* @param system the system whose staves starting measure has to be checked
*/
private void removeStartingBar (omr.score.System system)
{
int minWidth = scale.toPixels(constants.minMeasureWidth);
Barline firstBarline = system.getFirstStaff()
.getFirstMeasure()
.getBarline();
int firstX = firstBarline.getLeftX();
// Check is based on the width of this first measure
if (firstX < minWidth) {
// Adjust system parameters if needed : topLeft and dimension
if (firstX != 0) {
if (logger.isFineEnabled()) {
logger.fine("Adjusting firstX=" + firstX + " " + system);
}
system.getTopLeft()
.translate(firstX, 0);
system.getDimension().width -= -firstX;
}
// Adjust beginning of all staves to this one
// Remove this false "measure" in all staves of the system
for (TreeNode node : system.getStaves()) {
Staff staff = (Staff) node;
// Set the bar as starting bar for the staff
Measure measure = (Measure) staff.getMeasures()
.get(0);
staff.setStartingBar(measure.getBarline());
// Remove this first measure
staff.getMeasures()
.remove(0);
// Update abscissa of top-left corner of the staff
staff.getTopLeft()
.translate(staff.getStartingBarline().getLeftX(), 0);
// Update other bar lines abscissae accordingly
for (TreeNode mNode : staff.getMeasures()) {
Measure meas = (Measure) mNode;
meas.reset();
}
}
}
}
//~ Inner Classes ----------------------------------------------------------
//-----------//
// Constants //
//-----------//
private static final class Constants
extends ConstantSet
{
Constant.Boolean displayFrame = new Constant.Boolean(
false,
"Should we display a frame on the vertical sticks");
Scale.Fraction maxAlignShiftDx = new Scale.Fraction(
0.2,
"Maximum horizontal shift in bars between staves in a system");
Scale.Fraction maxBarThickness = new Scale.Fraction(
0.75,
"Maximum thickness of an interesting vertical stick");
Constant.Integer maxDeltaLength = new Constant.Integer(
4,
"Maximum difference in run length to be part of the same section");
Scale.Fraction maxDoubleBarDx = new Scale.Fraction(
0.75,
"Maximum horizontal distance between the two bars of a double bar");
Scale.Fraction minMeasureWidth = new Scale.Fraction(
0.75,
"Minimum width for a measure");
Constants ()
{
initialize();
}
}
//--------------//
// MyCheckBoard //
//--------------//
private class MyCheckBoard
extends CheckBoard<BarsChecker.Context>
{
public MyCheckBoard (String unit,
CheckSuite<BarsChecker.Context> suite,
Selection inputSelection)
{
super(unit, suite, inputSelection);
}
public void update (Selection selection,
SelectionHint hint)
{
BarsChecker.Context context = null;
Object entity = selection.getEntity();
if (entity instanceof Stick) {
// To get a fresh suite
setSuite(checker.new BarCheckSuite());
Stick stick = (Stick) entity;
context = new BarsChecker.Context(stick);
}
tellObject(context);
}
}
//-----------//
// MyLagView //
//-----------//
private class MyLagView
extends GlyphLagView
{
private MyLagView (GlyphLag lag)
{
super(lag, null, BarsBuilder.this);
setName("BarsBuilder-View");
// Pixel
setLocationSelection(sheet.getSelection(SelectionTag.PIXEL));
// Glyph set
Selection glyphSetSelection = sheet.getSelection(
SelectionTag.GLYPH_SET);
setGlyphSetSelection(glyphSetSelection);
glyphSetSelection.addObserver(this);
}
//----------//
// colorize //
//----------//
public void colorize ()
{
super.colorize();
// Determine my view index in the lag views
final int viewIndex = lag.getViews()
.indexOf(this);
// All remaining vertical sticks clutter
for (Stick stick : clutter) {
stick.colorize(lag, viewIndex, Color.red);
}
// Recognized bar lines
for (Stick stick : bars) {
stick.colorize(lag, viewIndex, Color.yellow);
}
}
//-------------//
// renderItems //
//-------------//
public void renderItems (Graphics g)
{
// Render all physical info known so far, which is just the staff
// line info, lineset by lineset
sheet.accept(new RenderingVisitor(g, getZoom()));
super.renderItems(g);
}
}
}
| src/main/omr/sheet/BarsBuilder.java | //----------------------------------------------------------------------------//
// //
// B a r s B u i l d e r //
// //
// Copyright (C) Herve Bitteur 2000-2006. All rights reserved. //
// This software is released under the terms of the GNU General Public //
// License. Please contact the author at [email protected] //
// to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
package omr.sheet;
import omr.Main;
import omr.ProcessingException;
import omr.check.CheckBoard;
import omr.check.CheckSuite;
import omr.check.FailureResult;
import omr.constant.Constant;
import omr.constant.ConstantSet;
import omr.glyph.Glyph;
import omr.glyph.GlyphLag;
import omr.glyph.GlyphModel;
import omr.glyph.GlyphSection;
import omr.glyph.Shape;
import omr.glyph.ui.GlyphBoard;
import omr.glyph.ui.GlyphLagView;
import omr.lag.JunctionDeltaPolicy;
import omr.lag.LagBuilder;
import omr.lag.RunBoard;
import omr.lag.ScrollLagView;
import omr.lag.SectionBoard;
import omr.lag.VerticalOrientation;
import omr.score.Barline;
import omr.score.Measure;
import omr.score.Score;
import omr.score.ScoreConstants;
import omr.score.Staff;
import omr.score.System;
import omr.score.SystemPart;
import omr.score.UnitDimension;
import omr.score.visitor.ComputingVisitor;
import omr.score.visitor.RenderingVisitor;
import omr.selection.Selection;
import omr.selection.SelectionHint;
import omr.selection.SelectionTag;
import static omr.selection.SelectionTag.*;
import omr.stick.Stick;
import omr.stick.StickSection;
import omr.ui.BoardsPane;
import omr.ui.PixelBoard;
import static omr.ui.field.SpinnerUtilities.*;
import omr.util.Dumper;
import omr.util.Logger;
import omr.util.TreeNode;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* Class <code>BarsBuilder</code> handles the vertical lines that are recognized
* as bar lines. This class uses a dedicated companion named {@link
* omr.sheet.BarsChecker} which handles physical checks.
*
* <p> Input is provided by the list of vertical sticks retrieved by the
* preceding step.
*
* <p> Output is the collection of detected Bar lines.
*
* @author Hervé Bitteur
* @version $Id$
*/
public class BarsBuilder
extends GlyphModel
{
//~ Static fields/initializers ---------------------------------------------
private static final Constants constants = new Constants();
private static final Logger logger = Logger.getLogger(
BarsBuilder.class);
/** Failure */
private static final FailureResult NOT_SYSTEM_ALIGNED = new FailureResult(
"Bar-NotSystemAligned");
private static final FailureResult SHORTER_THAN_STAFF_HEIGHT = new FailureResult(
"Bar-ShorterThanStaffHeight");
private static final FailureResult THICK_BAR_NOT_ALIGNED = new FailureResult(
"Bar-ThickBarNotAligned");
private static final FailureResult CANCELLED = new FailureResult(
"Bar-Cancelled");
//~ Instance fields --------------------------------------------------------
/** Companion physical stick checker */
private BarsChecker checker;
/** Lag view on bars, if so desired */
private GlyphLagView lagView;
/** List of found bar sticks */
private List<Stick> bars = new ArrayList<Stick>();
/** Unused vertical sticks */
private List<Stick> clutter;
/** Sheet scale */
private Scale scale;
/** Related score */
private Score score;
/** Bars area, with retrieved vertical sticks */
private VerticalArea barsArea;
//~ Constructors -----------------------------------------------------------
//-------------//
// BarsBuilder //
//-------------//
/**
* Prepare a bar retriever on the provided sheet
*
* @param sheet the sheet to process
*/
public BarsBuilder (Sheet sheet)
{
super(sheet, new GlyphLag(new VerticalOrientation()));
}
//~ Methods ----------------------------------------------------------------
//-----------//
// setBraces //
//-----------//
/**
* Pass the braces symbols found, so that score parts can be defined
*
* @param braceLists the braces, system per system
*/
public void setBraces (List<List<Glyph>> braceLists)
{
int is = 0;
for (SystemInfo systemInfo : sheet.getSystems()) {
setSystemBraces(systemInfo.getScoreSystem(), braceLists.get(is++));
}
}
//-----------//
// buildInfo //
//-----------//
/**
* Retrieve and store the bars information on the provided sheet
*
* @throws ProcessingException raised when step processing must stop, due to
* encountered error
*/
public void buildInfo ()
throws ProcessingException
{
// Stuff to be made available
scale = sheet.getScale();
sheet.getHorizontals();
// Augment the vertical lag of runs
lag.setName("vLag");
lag.setVertexClass(StickSection.class);
new LagBuilder<GlyphLag, GlyphSection>().rip(
lag,
sheet.getPicture(),
0, // minRunLength
new JunctionDeltaPolicy(constants.maxDeltaLength.getValue())); // maxDeltaLength
sheet.setVerticalLag(lag);
// Retrieve (vertical) sticks
barsArea = new VerticalArea(
sheet,
lag,
scale.toPixels(constants.maxBarThickness));
clutter = new ArrayList<Stick>(barsArea.getSticks());
// Allocate score
createScore();
// Delegate to BarsChecker companion
checker = new BarsChecker(sheet);
checker.retrieveMeasures(clutter, bars);
// Assign bar line shape
for (Stick stick : bars) {
stick.setShape(
checker.isThickBar(stick) ? Shape.THICK_BAR_LINE
: Shape.THIN_BAR_LINE);
stick.setInterline(sheet.getScale().interline());
}
// Check Measures using only score parameters
checkMeasures();
// With now neat staff measures, let's allocate the systems measure frames
//////createMeasureFrames();
// Erase bar pixels from picture
//////eraseBars();
// Update score internal data
score.accept(new ComputingVisitor());
// Report number of measures retrieved
logger.info(
score.getLastSystem().getLastMeasureId() + " measure(s) found");
// Split everything, including horizontals, per system
SystemSplit.computeSystemLimits(sheet);
SystemSplit.splitHorizontals(sheet);
SystemSplit.splitBars(sheet, bars);
// Display the resulting stickarea if so asked for
if (constants.displayFrame.getValue() && (Main.getJui() != null)) {
displayFrame();
}
}
//--------------------//
// deassignGlyphShape //
//--------------------//
/**
* Remove a bar together with all its related entities. This means removing
* reference in the bars list of this builder, reference in the containing
* SystemInfo, reference in the Measure it ends, and removing this Measure
* itself if this (false) bar was the only ending bar left for the
* Measure. The related stick must also be assigned a failure result.
*
* @param glyph the (false) bar glyph to deassign
*/
@Override
public void deassignGlyphShape (Glyph glyph)
{
if ((glyph.getShape() == Shape.THICK_BAR_LINE) ||
(glyph.getShape() == Shape.THIN_BAR_LINE)) {
Stick bar = getBarOf(glyph);
if (bar == null) {
return;
} else {
logger.info("Deassigning a " + glyph.getShape());
}
// Related stick has to be freed
bar.setShape(null);
bar.setResult(CANCELLED);
// Remove from the internal all-bars list
bars.remove(bar);
// Remove from the containing SystemInfo
SystemInfo system = checker.getSystemOf(bar, sheet);
if (system == null) {
return;
} else {
system.getBars()
.remove(bar);
}
// Remove from the containing Measure
System scoreSystem = system.getScoreSystem();
for (Iterator it = scoreSystem.getStaves()
.iterator(); it.hasNext();) {
Staff staff = (Staff) it.next();
if (checker.isStaffEmbraced(staff, bar)) {
for (Iterator mit = staff.getMeasures()
.iterator(); mit.hasNext();) {
Measure measure = (Measure) mit.next();
// for (Iterator bit = measure.getInfos().iterator();
// bit.hasNext();) {
// BarInfo info = (BarInfo) bit.next();
// if (info == bar) {
// // Remove the bar info
// if (logger.isFineEnabled()) {
// logger.fine("Removing " + info +
// " from " + measure);
// }
// bit.remove();
//
// // Remove measure as well ?
// if (measure.getInfos().size() == 0) {
// if (logger.isFineEnabled()) {
// logger.fine("Removing " + measure);
// }
// mit.remove();
// }
//
// break;
// }
// }
}
}
}
assignGlyphShape(glyph, null);
// Update the view accordingly
if (lagView != null) {
lagView.colorize();
lagView.repaint();
}
} else {
BarsBuilder.logger.warning(
"No deassign meant for " + glyph.getShape() + " glyph");
}
}
//----------//
// getBarOf //
//----------//
private Stick getBarOf (Glyph glyph)
{
for (Stick bar : bars) {
if (bar == glyph) {
return bar;
}
}
logger.warning("Cannot find bar for " + glyph);
return null;
}
//-----------------//
// setSystemBraces //
//-----------------//
/**
* Pass the braces symbols found for one system
*
* @param braces list of braces for this system
*/
private void setSystemBraces (System system,
List<Glyph> braces)
{
// Map Staff -> its containing staves ensemble (= Part)
Map<Staff, List<Staff>> ensembles = new HashMap<Staff, List<Staff>>();
// Inspect each brace in turn
for (Glyph brace : braces) {
List<Staff> ensemble = new ArrayList<Staff>();
// Inspect all staves for this brace
for (TreeNode node : system.getStaves()) {
Staff staff = (Staff) node;
if (checker.isStaffEmbraced(staff, brace)) {
ensemble.add(staff);
ensembles.put(staff, ensemble);
}
}
if (ensemble.size() == 0) {
logger.warning(
"Brace with no embraced staves at all: " + brace.getId());
}
}
// Now build the parts by looking back at all staves
List<SystemPart> parts = new ArrayList<SystemPart>();
List<Staff> currentEnsemble = null;
for (TreeNode node : system.getStaves()) {
Staff staff = (Staff) node;
List<Staff> ensemble = ensembles.get(staff);
if (ensemble == null) {
// Standalone staff, a part by itself
parts.add(new SystemPart(Arrays.asList(staff)));
} else {
// Staff is in a part
if (ensemble != currentEnsemble) {
parts.add(new SystemPart(ensemble));
} else {
// Nothing to do
}
}
currentEnsemble = ensemble;
}
// Dump
StringBuilder sb = new StringBuilder();
for (SystemPart part : parts) {
sb.append("[");
for (Staff staff : part.getStaves()) {
sb.append(" ").append(staff.getStafflink());
}
sb.append("] ");
}
logger.info(system + " Parts: " + sb);
// Assign the parts to the system
system.setParts(parts);
}
//--------------------//
// checkBarAlignments //
//--------------------//
/**
* Check alignment of each measure of each staff with the other staff
* measures, a test that needs several staves in the system
*
* @param system the system to check
*/
private void checkBarAlignments (omr.score.System system)
{
if (system.getStaves()
.size() > 1) {
int maxShiftDx = scale.toPixels(constants.maxAlignShiftDx);
for (Iterator sit = system.getStaves()
.iterator(); sit.hasNext();) {
Staff staff = (Staff) sit.next();
for (Iterator mit = staff.getMeasures()
.iterator(); mit.hasNext();) {
Measure measure = (Measure) mit.next();
if (logger.isFineEnabled()) {
logger.fine("Checking alignment of " + measure);
}
// Compare the abscissa with corresponding position in
// the other staves
int x = measure.getBarline()
.getCenter().x;
for (Iterator it = system.getStaves()
.iterator(); it.hasNext();) {
Staff stv = (Staff) it.next();
if (stv == staff) {
continue;
}
if (!stv.barlineExists(x, maxShiftDx)) {
if (logger.isFineEnabled()) {
logger.fine(
"Singular measure removed: " +
Dumper.dumpOf(measure));
}
// Remove the false bar info
for (Stick stick : measure.getBarline()
.getSticks()) {
stick.setResult(NOT_SYSTEM_ALIGNED);
bars.remove(stick);
}
// Remove the false measure
mit.remove();
break;
}
}
}
}
}
}
//----------------//
// checkEndingBar //
//----------------//
/**
* Use ending bar line if any, to adjust the right abscissa of the system
* and its staves.
*
* @param system the system to check
*/
private void checkEndingBar (omr.score.System system)
{
Staff staff = system.getFirstStaff();
Measure measure = staff.getLastMeasure();
Barline barline = measure.getBarline();
int lastX = barline.getRightX();
int minWidth = scale.toPixels(constants.minMeasureWidth);
if ((staff.getWidth() - lastX) < minWidth) {
if (logger.isFineEnabled()) {
logger.fine("Adjusting EndingBar " + system);
}
// Adjust end of system & staff(s) to this one
UnitDimension dim = system.getDimension();
if (dim == null) {
system.setDimension(new UnitDimension(lastX, 0));
} else {
dim.width = lastX;
}
for (Iterator sit = system.getStaves()
.iterator(); sit.hasNext();) {
Staff stv = (Staff) sit.next();
stv.setWidth(system.getDimension().width);
}
}
}
//---------------//
// checkMeasures //
//---------------//
/**
* Check measure reality, using a set of additional tests.
*/
private void checkMeasures ()
{
// Check are performed on a system basis
for (TreeNode node : score.getSystems()) {
omr.score.System system = (omr.score.System) node;
// Check alignment of each measure of each staff with the other
// staff measures, a test that needs several staves in the system
checkBarAlignments(system);
// Detect very narrow measures which in fact indicate double bar
// lines.
mergeBarlines(system);
// First barline may be just the beginning of the staff, so do not
// count the very first bar line, which in general defines the
// beginning of the staff rather than the end of a measure, but use
// it to precisely define the left abscissa of the system and all
// its contained staves.
removeStartingBar(system);
// Similarly, use the very last bar line, which generally ends the
// system, to define the right abscissa of the system and its
// staves.
checkEndingBar(system);
}
}
//-------------//
// createScore //
//-------------//
private void createScore ()
{
if (logger.isFineEnabled()) {
logger.fine("Allocating score");
}
score = new Score(
scale.toUnits(
new PixelDimension(sheet.getWidth(), sheet.getHeight())),
(int) Math.rint(sheet.getSkew().angle() * ScoreConstants.BASE),
scale.spacing(),
sheet.getPath());
// Mutual referencing
score.setSheet(sheet);
sheet.setScore(score);
}
//--------------//
// displayFrame //
//--------------//
private void displayFrame ()
{
Selection glyphSelection = sheet.getSelection(VERTICAL_GLYPH);
lagView = new MyLagView(lag);
lagView.setGlyphSelection(glyphSelection);
glyphSelection.addObserver(lagView);
lagView.colorize();
final String unit = "BarsBuilder";
BoardsPane boardsPane = new BoardsPane(
sheet,
lagView,
new PixelBoard(unit),
new RunBoard(unit, sheet.getSelection(VERTICAL_RUN)),
new SectionBoard(
unit,
lag.getLastVertexId(),
sheet.getSelection(VERTICAL_SECTION),
sheet.getSelection(VERTICAL_SECTION_ID)),
new GlyphBoard(
unit,
this,
sheet.getSelection(VERTICAL_GLYPH),
sheet.getSelection(VERTICAL_GLYPH_ID),
sheet.getSelection(GLYPH_SET)),
new MyCheckBoard(
unit,
checker.getSuite(),
sheet.getSelection(VERTICAL_GLYPH)));
// Create a hosting frame for the view
ScrollLagView slv = new ScrollLagView(lagView);
sheet.getAssembly()
.addViewTab("Bars", slv, boardsPane);
}
//---------------//
// mergeBarlines //
//---------------//
/**
* Check whether two close bar lines are not in fact double lines (with
* variants)
*
* @param system the system to check
*/
private void mergeBarlines (omr.score.System system)
{
int maxDoubleDx = scale.toPixels(constants.maxDoubleBarDx);
for (Iterator sit = system.getStaves()
.iterator(); sit.hasNext();) {
Staff staff = (Staff) sit.next();
Measure prevMeasure = null;
for (Iterator mit = staff.getMeasures()
.iterator(); mit.hasNext();) {
Measure measure = (Measure) mit.next();
if (prevMeasure != null) {
final int measureWidth = measure.getBarline()
.getCenter().x -
prevMeasure.getBarline()
.getCenter().x;
if (measureWidth <= maxDoubleDx) {
// Merge the two bar lines into the first one
prevMeasure.getBarline()
.mergeWith(measure.getBarline());
if (logger.isFineEnabled()) {
logger.fine(
"Merged two barlines into " +
prevMeasure.getBarline());
}
mit.remove();
} else {
prevMeasure = measure;
}
} else {
prevMeasure = measure;
}
}
}
}
//-------------------//
// removeStartingBar //
//-------------------//
/**
* We associate measures only with their ending bar line(s), so the starting
* bar of a staff does not end a measure, we thus have to remove the measure
* that we first had associated with it.
*
* @param system the system whose staves starting measure has to be checked
*/
private void removeStartingBar (omr.score.System system)
{
int minWidth = scale.toPixels(constants.minMeasureWidth);
Barline firstBarline = system.getFirstStaff()
.getFirstMeasure()
.getBarline();
int firstX = firstBarline.getLeftX();
// Check is based on the width of this first measure
if (firstX < minWidth) {
// Adjust system parameters if needed : topLeft and dimension
if (firstX != 0) {
if (logger.isFineEnabled()) {
logger.fine("Adjusting firstX=" + firstX + " " + system);
}
system.getTopLeft()
.translate(firstX, 0);
system.getDimension().width -= -firstX;
}
// Adjust beginning of all staves to this one
// Remove this false "measure" in all staves of the system
for (TreeNode node : system.getStaves()) {
Staff staff = (Staff) node;
// Set the bar as starting bar for the staff
Measure measure = (Measure) staff.getMeasures()
.get(0);
staff.setStartingBar(measure.getBarline());
// Remove this first measure
staff.getMeasures()
.remove(0);
// Update abscissa of top-left corner of the staff
staff.getTopLeft()
.translate(staff.getStartingBarline().getLeftX(), 0);
// Update other bar lines abscissae accordingly
for (TreeNode mNode : staff.getMeasures()) {
Measure meas = (Measure) mNode;
meas.reset();
}
}
}
}
//~ Inner Classes ----------------------------------------------------------
//-----------//
// Constants //
//-----------//
private static final class Constants
extends ConstantSet
{
Constant.Boolean displayFrame = new Constant.Boolean(
false,
"Should we display a frame on the vertical sticks");
Scale.Fraction maxAlignShiftDx = new Scale.Fraction(
0.2,
"Maximum horizontal shift in bars between staves in a system");
Scale.Fraction maxBarThickness = new Scale.Fraction(
0.75,
"Maximum thickness of an interesting vertical stick");
Constant.Integer maxDeltaLength = new Constant.Integer(
4,
"Maximum difference in run length to be part of the same section");
Scale.Fraction maxDoubleBarDx = new Scale.Fraction(
0.75,
"Maximum horizontal distance between the two bars of a double bar");
Scale.Fraction minMeasureWidth = new Scale.Fraction(
0.75,
"Minimum width for a measure");
Constants ()
{
initialize();
}
}
//--------------//
// MyCheckBoard //
//--------------//
private class MyCheckBoard
extends CheckBoard<BarsChecker.Context>
{
public MyCheckBoard (String unit,
CheckSuite<BarsChecker.Context> suite,
Selection inputSelection)
{
super(unit, suite, inputSelection);
}
public void update (Selection selection,
SelectionHint hint)
{
BarsChecker.Context context = null;
Object entity = selection.getEntity();
if (entity instanceof Stick) {
// To get a fresh suite
setSuite(checker.new BarCheckSuite());
Stick stick = (Stick) entity;
context = new BarsChecker.Context(stick);
}
tellObject(context);
}
}
//-----------//
// MyLagView //
//-----------//
private class MyLagView
extends GlyphLagView
{
private MyLagView (GlyphLag lag)
{
super(lag, null, BarsBuilder.this);
setName("BarsBuilder-View");
// Pixel
setLocationSelection(sheet.getSelection(SelectionTag.PIXEL));
// Glyph set
Selection glyphSetSelection = sheet.getSelection(
SelectionTag.GLYPH_SET);
setGlyphSetSelection(glyphSetSelection);
glyphSetSelection.addObserver(this);
}
//----------//
// colorize //
//----------//
public void colorize ()
{
super.colorize();
// Determine my view index in the lag views
final int viewIndex = lag.getViews()
.indexOf(this);
// All remaining vertical sticks clutter
for (Stick stick : clutter) {
stick.colorize(lag, viewIndex, Color.red);
}
// Recognized bar lines
for (Stick stick : bars) {
stick.colorize(lag, viewIndex, Color.yellow);
}
}
//-------------//
// renderItems //
//-------------//
public void renderItems (Graphics g)
{
// Render all physical info known so far, which is just the staff
// line info, lineset by lineset
sheet.accept(new RenderingVisitor(g, getZoom()));
super.renderItems(g);
}
}
}
| Add brutal repaint for score view
| src/main/omr/sheet/BarsBuilder.java | Add brutal repaint for score view | <ide><path>rc/main/omr/sheet/BarsBuilder.java
<ide>
<ide> for (SystemInfo systemInfo : sheet.getSystems()) {
<ide> setSystemBraces(systemInfo.getScoreSystem(), braceLists.get(is++));
<add> }
<add>
<add> // Repaint the score view, if any (TBI)
<add> if (sheet.getScore()
<add> .getView() != null) {
<add> sheet.getScore()
<add> .getView()
<add> .getScrollPane()
<add> .getView()
<add> .repaint();
<ide> }
<ide> }
<ide>
<ide>
<ide> currentEnsemble = ensemble;
<ide> }
<del>
<add>
<ide> // Dump
<ide> StringBuilder sb = new StringBuilder();
<add>
<ide> for (SystemPart part : parts) {
<ide> sb.append("[");
<add>
<ide> for (Staff staff : part.getStaves()) {
<del> sb.append(" ").append(staff.getStafflink());
<del> }
<add> sb.append(" ")
<add> .append(staff.getStafflink());
<add> }
<add>
<ide> sb.append("] ");
<ide> }
<add>
<ide> logger.info(system + " Parts: " + sb);
<ide>
<ide> // Assign the parts to the system |
|
Java | lgpl-2.1 | f715f936359b802d94472140aa7d3893aaa3caaa | 0 | cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl | /*
File: CytoscapeDesktop.java
Copyright (c) 2006, 2010, The Cytoscape Consortium (www.cytoscape.org)
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. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.internal.view;
import org.cytoscape.application.CytoscapeShutdown;
import org.cytoscape.application.events.CytoscapeStartEvent;
import org.cytoscape.application.events.CytoscapeStartListener;
import org.cytoscape.application.swing.CyAction;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.application.swing.CytoPanel;
import org.cytoscape.application.swing.CytoPanelComponent;
import org.cytoscape.application.swing.CytoPanelName;
import org.cytoscape.application.swing.CytoPanelState;
import org.cytoscape.application.swing.events.CytoPanelStateChangedListener;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.property.session.Cysession;
import org.cytoscape.property.session.Cytopanel;
import org.cytoscape.property.session.Cytopanels;
import org.cytoscape.property.session.Desktop;
import org.cytoscape.property.session.DesktopSize;
import org.cytoscape.property.session.SessionState;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.session.events.SessionAboutToBeSavedEvent;
import org.cytoscape.session.events.SessionAboutToBeSavedListener;
import org.cytoscape.session.events.SessionLoadedEvent;
import org.cytoscape.session.events.SessionLoadedListener;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import java.math.BigInteger;
import java.util.Dictionary;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.cytoscape.work.swing.DialogTaskManager;
import org.cytoscape.application.swing.ToolBarComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The CytoscapeDesktop is the central Window for working with Cytoscape
*/
public class CytoscapeDesktop extends JFrame implements CySwingApplication, CytoscapeStartListener,
SessionLoadedListener, SessionAboutToBeSavedListener {
private final static long serialVersionUID = 1202339866271348L;
private static final Dimension DEF_DESKTOP_SIZE = new Dimension(1150, 850);
private static final int DEF_DIVIDER_LOATION = 450;
private static final String SMALL_ICON = "/images/c16.png";
private static final int DEVIDER_SIZE = 4;
private static final Map<String, CytoPanelName> CYTOPANEL_NAMES = new LinkedHashMap<String, CytoPanelName>();
private static final Logger logger = LoggerFactory.getLogger(CytoscapeDesktop.class);
/**
* The network panel that sends out events when a network is selected from
* the Tree that it contains.
*/
protected NetworkPanel networkPanel;
/**
* The CyMenus object provides access to the all of the menus and toolbars
* that will be needed.
*/
protected CytoscapeMenus cyMenus;
/**
* The NetworkViewManager can support three types of interfaces.
* Tabbed/InternalFrame/ExternalFrame
*/
protected NetworkViewManager networkViewManager;
//
// CytoPanel Variables
//
private CytoPanelImp cytoPanelWest;
private CytoPanelImp cytoPanelEast;
private CytoPanelImp cytoPanelSouth;
private CytoPanelImp cytoPanelSouthWest;
// Status Bar TODO: Move this to log-swing to avoid cyclic dependency.
private JPanel main_panel;
private final CytoscapeShutdown shutdown;
private final CyEventHelper cyEventHelper;
private final CyServiceRegistrar registrar;
private final JToolBar statusToolBar;
static {
CYTOPANEL_NAMES.put("CytoPanel1", CytoPanelName.WEST);
CYTOPANEL_NAMES.put("CytoPanel2", CytoPanelName.SOUTH);
CYTOPANEL_NAMES.put("CytoPanel3", CytoPanelName.EAST);
}
/**
* Creates a new CytoscapeDesktop object.
*/
public CytoscapeDesktop(CytoscapeMenus cyMenus, NetworkViewManager networkViewManager, NetworkPanel networkPanel,
CytoscapeShutdown shut, CyEventHelper eh, CyServiceRegistrar registrar, DialogTaskManager taskManager) {
super("Cytoscape Desktop (New Session)");
this.cyMenus = cyMenus;
this.networkViewManager = networkViewManager;
this.networkPanel = networkPanel;
this.shutdown = shut;
this.cyEventHelper = eh;
this.registrar = registrar;
taskManager.setExecutionContext(this);
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(SMALL_ICON)));
main_panel = new JPanel();
main_panel.setLayout(new BorderLayout());
// create the CytoscapeDesktop
final BiModalJSplitPane masterPane = setupCytoPanels(networkPanel, networkViewManager);
main_panel.add(masterPane, BorderLayout.CENTER);
main_panel.add(cyMenus.getJToolBar(), BorderLayout.NORTH);
statusToolBar = new JToolBar();
main_panel.add(statusToolBar, BorderLayout.SOUTH);
setJMenuBar(cyMenus.getJMenuBar());
// update look and feel
try {
final String laf = UIManager.getSystemLookAndFeelClassName();
logger.debug("setting look and feel to: " + laf);
UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) { /* not really a problem if this fails */ }
//don't automatically close window. Let shutdown.exit(returnVal)
//handle this
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
shutdown.exit(0);
}
});
// Prepare to show the desktop...
setContentPane(main_panel);
pack();
setSize(DEF_DESKTOP_SIZE);
// Defines default divider location for the network panel to JDesktop
masterPane.setDividerLocation(400);
// Move it to the center
this.setLocationRelativeTo(null);
// ...but don't actually show it!!!!
// Once the system has fully started the JFrame will be set to
// visible by the StartupMostlyFinished class, found elsewhere.
}
/**
* Create the CytoPanels UI.
*
* @param networkPanel
* to load on left side of right bimodal.
* @param networkViewManager
* to load on left side (CytoPanel West).
* @return BiModalJSplitPane Object.
*/
private BiModalJSplitPane setupCytoPanels(NetworkPanel networkPanel,
NetworkViewManager networkViewManager) {
// bimodals that our Cytopanels Live within
final BiModalJSplitPane topRightPane = createTopRightPane(networkViewManager);
final BiModalJSplitPane rightPane = createRightPane(topRightPane);
final BiModalJSplitPane masterPane = createMasterPane(networkPanel, rightPane);
createBottomLeft();
return masterPane;
}
/**
* Creates the TopRight Pane.
*
* @param networkViewManager
* to load on left side of top right bimodal.
* @return BiModalJSplitPane Object.
*/
private BiModalJSplitPane createTopRightPane(NetworkViewManager networkViewManager) {
// create cytopanel with tabs along the top
cytoPanelEast = new CytoPanelImp(CytoPanelName.EAST, JTabbedPane.TOP, CytoPanelState.HIDE, cyEventHelper);
// determine proper network view manager component
Component networkViewComp = (Component) networkViewManager.getDesktopPane();
// create the split pane - we show this on startup
BiModalJSplitPane splitPane = new BiModalJSplitPane(this, JSplitPane.HORIZONTAL_SPLIT,
BiModalJSplitPane.MODE_HIDE_SPLIT,
networkViewComp, cytoPanelEast);
// set the cytopanelcontainer
cytoPanelEast.setCytoPanelContainer(splitPane);
// set the resize weight - left component gets extra space
splitPane.setResizeWeight(1.0);
// outta here
return splitPane;
}
/**
* Creates the Right Panel.
*
* @param topRightPane
* TopRightPane Object.
* @return BiModalJSplitPane Object
*/
private BiModalJSplitPane createRightPane(BiModalJSplitPane topRightPane) {
// create cytopanel with tabs along the bottom
cytoPanelSouth = new CytoPanelImp(CytoPanelName.SOUTH, JTabbedPane.BOTTOM,
CytoPanelState.DOCK, cyEventHelper);
// create the split pane - hidden by default
BiModalJSplitPane splitPane = new BiModalJSplitPane(this, JSplitPane.VERTICAL_SPLIT,
BiModalJSplitPane.MODE_HIDE_SPLIT,
topRightPane, cytoPanelSouth);
// set the cytopanel container
cytoPanelSouth.setCytoPanelContainer(splitPane);
splitPane.setDividerSize(DEVIDER_SIZE);
splitPane.setDividerLocation(DEF_DIVIDER_LOATION);
// set resize weight - top component gets all the extra space.
splitPane.setResizeWeight(1.0);
// outta here
return splitPane;
}
private void createBottomLeft() {
// create cytopanel with tabs along the top for manual layout
cytoPanelSouthWest = new CytoPanelImp(CytoPanelName.SOUTH_WEST,
JTabbedPane.TOP,
CytoPanelState.HIDE, cyEventHelper);
final BiModalJSplitPane split = new BiModalJSplitPane(this, JSplitPane.VERTICAL_SPLIT,
BiModalJSplitPane.MODE_HIDE_SPLIT, new JPanel(),
cytoPanelSouthWest);
split.setResizeWeight(0);
cytoPanelSouthWest.setCytoPanelContainer(split);
cytoPanelSouthWest.setMinimumSize(new Dimension(180, 330));
cytoPanelSouthWest.setMaximumSize(new Dimension(180, 330));
cytoPanelSouthWest.setPreferredSize(new Dimension(180, 330));
split.setDividerSize(DEVIDER_SIZE);
ToolCytoPanelListener t = new ToolCytoPanelListener( split, cytoPanelWest,
cytoPanelSouthWest );
registrar.registerService(t,CytoPanelStateChangedListener.class,new Properties());
}
/**
* Creates the Master Split Pane.
*
* @param networkPanel
* to load on left side of CytoPanel (cytoPanelWest).
* @param rightPane
* BiModalJSplitPane Object.
* @return BiModalJSplitPane Object.
*/
private BiModalJSplitPane createMasterPane(NetworkPanel networkPanel,
BiModalJSplitPane rightPane) {
// create cytopanel with tabs along the top
cytoPanelWest = new CytoPanelImp(CytoPanelName.WEST, JTabbedPane.TOP, CytoPanelState.DOCK, cyEventHelper);
// add the network panel to our tab
String tab1Name = new String("Network");
cytoPanelWest.add(tab1Name, new ImageIcon(getClass().getResource("/images/class_hi.gif")),
networkPanel, "Cytoscape Network List");
// create the split pane - hidden by default
BiModalJSplitPane splitPane = new BiModalJSplitPane(this, JSplitPane.HORIZONTAL_SPLIT,
BiModalJSplitPane.MODE_SHOW_SPLIT,
cytoPanelWest, rightPane);
splitPane.setDividerSize(DEVIDER_SIZE);
// set the cytopanel container
cytoPanelWest.setCytoPanelContainer(splitPane);
// outta here
return splitPane;
}
NetworkViewManager getNetworkViewManager() {
return networkViewManager;
}
public void addAction(CyAction action, Dictionary props) {
cyMenus.addAction(action);
}
public void addAction(CyAction action) {
cyMenus.addAction(action);
}
public void removeAction(CyAction action, Dictionary props) {
cyMenus.removeAction(action);
}
public void removeAction(CyAction action) {
cyMenus.removeAction(action);
}
public JMenu getJMenu(String name) {
return cyMenus.getJMenu(name);
}
public JMenuBar getJMenuBar() {
return cyMenus.getJMenuBar();
}
public JToolBar getJToolBar() {
return cyMenus.getJToolBar();
}
public JFrame getJFrame() {
return this;
}
public CytoPanel getCytoPanel(final CytoPanelName compassDirection) {
return getCytoPanelInternal(compassDirection);
}
private CytoPanelImp getCytoPanelInternal(final CytoPanelName compassDirection) {
// return appropriate cytoPanel based on compass direction
switch (compassDirection) {
case SOUTH:
return cytoPanelSouth;
case EAST:
return cytoPanelEast;
case WEST:
return cytoPanelWest;
case SOUTH_WEST:
return cytoPanelSouthWest;
}
// houston we have a problem
throw new IllegalArgumentException("Illegal Argument: " + compassDirection
+ ". Must be one of: {SOUTH,EAST,WEST,SOUTH_WEST}.");
}
public void addCytoPanelComponent(CytoPanelComponent cp, Dictionary props) {
CytoPanelImp impl = getCytoPanelInternal(cp.getCytoPanelName());
impl.add(cp);
}
public void removeCytoPanelComponent(CytoPanelComponent cp, Dictionary props) {
CytoPanelImp impl = getCytoPanelInternal(cp.getCytoPanelName());
impl.remove(cp);
}
public JToolBar getStatusToolBar() {
return statusToolBar;
}
public void addToolBarComponent(ToolBarComponent tp, Dictionary props) {
((CytoscapeToolBar)cyMenus.getJToolBar()).addToolBarComponent(tp);
}
public void removeToolBarComponent(ToolBarComponent tp, Dictionary props) {
((CytoscapeToolBar)cyMenus.getJToolBar()).removeToolBarComponent(tp);
}
// handle CytoscapeStartEvent
@Override
public void handleEvent(CytoscapeStartEvent e) {
this.setVisible(true);
this.toFront();
}
@Override
public void handleEvent(SessionLoadedEvent e) {
// restore the states of the CytoPanels
Cysession cysess = e.getLoadedSession().getCysession();
SessionState sessionState = cysess.getSessionState();
if (sessionState != null) {
Cytopanels cytopanels = sessionState.getCytopanels();
if (cytopanels != null) {
List<Cytopanel> cytopanelsList = cytopanels.getCytopanel();
for (Cytopanel cytopanel : cytopanelsList) {
String id = cytopanel.getId();
CytoPanelName panelName = CYTOPANEL_NAMES.get(id);
if (panelName != null) {
CytoPanel p = getCytoPanelInternal(panelName);
try {
p.setState(CytoPanelState.valueOf(cytopanel.getPanelState().toUpperCase().trim()));
} catch (Exception ex) {
logger.error("Cannot restore the state of panel \"" + panelName.getTitle() + "\"",
ex);
}
try {
p.setSelectedIndex(Integer.parseInt(cytopanel.getSelectedPanel()));
} catch (Exception ex) {
logger.error("Cannot restore the selected index of panel \"" + panelName.getTitle() + "\"",
ex);
}
}
}
}
}
}
@Override
public void handleEvent(SessionAboutToBeSavedEvent e) {
// save the desktop size
BigInteger w = BigInteger.valueOf(this.getWidth());
BigInteger h = BigInteger.valueOf(this.getHeight());
DesktopSize size = new DesktopSize();
size.setWidth(w);
size.setHeight(h);
Desktop desktop = e.getDesktop();
if (desktop == null) {
desktop = new Desktop();
e.setDesktop(desktop);
}
desktop.setDesktopSize(size);
// save the states of the CytoPanels
for (Map.Entry<String, CytoPanelName> entry : CYTOPANEL_NAMES.entrySet()) {
CytoPanel p = getCytoPanelInternal(entry.getValue());
Cytopanel cytopanel = new Cytopanel();
cytopanel.setId(entry.getKey());
cytopanel.setPanelState(p.getState().toString());
cytopanel.setSelectedPanel(Integer.toString(p.getSelectedIndex()));
try {
e.addCytopanel(cytopanel);
} catch (Exception ex) {
logger.error("Cannot add Cytopanel to SessionAboutToBeSavedEvent", ex);
}
}
}
}
| swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeDesktop.java | /*
File: CytoscapeDesktop.java
Copyright (c) 2006, 2010, The Cytoscape Consortium (www.cytoscape.org)
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. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.internal.view;
import org.cytoscape.application.CytoscapeShutdown;
import org.cytoscape.application.events.CytoscapeStartEvent;
import org.cytoscape.application.events.CytoscapeStartListener;
import org.cytoscape.application.swing.CyAction;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.application.swing.CytoPanel;
import org.cytoscape.application.swing.CytoPanelComponent;
import org.cytoscape.application.swing.CytoPanelName;
import org.cytoscape.application.swing.CytoPanelState;
import org.cytoscape.application.swing.events.CytoPanelStateChangedListener;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.property.session.Cysession;
import org.cytoscape.property.session.Cytopanel;
import org.cytoscape.property.session.Cytopanels;
import org.cytoscape.property.session.Desktop;
import org.cytoscape.property.session.DesktopSize;
import org.cytoscape.property.session.SessionState;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.session.events.SessionAboutToBeSavedEvent;
import org.cytoscape.session.events.SessionAboutToBeSavedListener;
import org.cytoscape.session.events.SessionLoadedEvent;
import org.cytoscape.session.events.SessionLoadedListener;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import java.math.BigInteger;
import java.util.Dictionary;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.cytoscape.work.swing.DialogTaskManager;
import org.cytoscape.application.swing.ToolBarComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The CytoscapeDesktop is the central Window for working with Cytoscape
*/
public class CytoscapeDesktop extends JFrame implements CySwingApplication, CytoscapeStartListener,
SessionLoadedListener, SessionAboutToBeSavedListener {
private final static long serialVersionUID = 1202339866271348L;
private static final Dimension DEF_DESKTOP_SIZE = new Dimension(1100, 800);
private static final int DEF_DIVIDER_LOATION = 450;
private static final String SMALL_ICON = "/images/c16.png";
private static final int DEVIDER_SIZE = 4;
private static final Map<String, CytoPanelName> CYTOPANEL_NAMES = new LinkedHashMap<String, CytoPanelName>();
private static final Logger logger = LoggerFactory.getLogger(CytoscapeDesktop.class);
/**
* The network panel that sends out events when a network is selected from
* the Tree that it contains.
*/
protected NetworkPanel networkPanel;
/**
* The CyMenus object provides access to the all of the menus and toolbars
* that will be needed.
*/
protected CytoscapeMenus cyMenus;
/**
* The NetworkViewManager can support three types of interfaces.
* Tabbed/InternalFrame/ExternalFrame
*/
protected NetworkViewManager networkViewManager;
//
// CytoPanel Variables
//
private CytoPanelImp cytoPanelWest;
private CytoPanelImp cytoPanelEast;
private CytoPanelImp cytoPanelSouth;
private CytoPanelImp cytoPanelSouthWest;
// Status Bar TODO: Move this to log-swing to avoid cyclic dependency.
private JPanel main_panel;
private final CytoscapeShutdown shutdown;
private final CyEventHelper cyEventHelper;
private final CyServiceRegistrar registrar;
private final JToolBar statusToolBar;
static {
CYTOPANEL_NAMES.put("CytoPanel1", CytoPanelName.WEST);
CYTOPANEL_NAMES.put("CytoPanel2", CytoPanelName.SOUTH);
CYTOPANEL_NAMES.put("CytoPanel3", CytoPanelName.EAST);
}
/**
* Creates a new CytoscapeDesktop object.
*/
public CytoscapeDesktop(CytoscapeMenus cyMenus, NetworkViewManager networkViewManager, NetworkPanel networkPanel,
CytoscapeShutdown shut, CyEventHelper eh, CyServiceRegistrar registrar, DialogTaskManager taskManager) {
super("Cytoscape Desktop (New Session)");
this.cyMenus = cyMenus;
this.networkViewManager = networkViewManager;
this.networkPanel = networkPanel;
this.shutdown = shut;
this.cyEventHelper = eh;
this.registrar = registrar;
taskManager.setExecutionContext(this);
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(SMALL_ICON)));
main_panel = new JPanel();
main_panel.setLayout(new BorderLayout());
// create the CytoscapeDesktop
final BiModalJSplitPane masterPane = setupCytoPanels(networkPanel, networkViewManager);
main_panel.add(masterPane, BorderLayout.CENTER);
main_panel.add(cyMenus.getJToolBar(), BorderLayout.NORTH);
statusToolBar = new JToolBar();
main_panel.add(statusToolBar, BorderLayout.SOUTH);
setJMenuBar(cyMenus.getJMenuBar());
// update look and feel
try {
final String laf = UIManager.getSystemLookAndFeelClassName();
logger.debug("setting look and feel to: " + laf);
UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) { /* not really a problem if this fails */ }
//don't automatically close window. Let shutdown.exit(returnVal)
//handle this
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
shutdown.exit(0);
}
});
// Prepare to show the desktop...
setContentPane(main_panel);
pack();
setSize(DEF_DESKTOP_SIZE);
// Move it to the center
this.setLocationRelativeTo(null);
// ...but don't actually show it!!!!
// Once the system has fully started the JFrame will be set to
// visible by the StartupMostlyFinished class, found elsewhere.
}
/**
* Create the CytoPanels UI.
*
* @param networkPanel
* to load on left side of right bimodal.
* @param networkViewManager
* to load on left side (CytoPanel West).
* @return BiModalJSplitPane Object.
*/
private BiModalJSplitPane setupCytoPanels(NetworkPanel networkPanel,
NetworkViewManager networkViewManager) {
// bimodals that our Cytopanels Live within
final BiModalJSplitPane topRightPane = createTopRightPane(networkViewManager);
final BiModalJSplitPane rightPane = createRightPane(topRightPane);
final BiModalJSplitPane masterPane = createMasterPane(networkPanel, rightPane);
createBottomLeft();
return masterPane;
}
/**
* Creates the TopRight Pane.
*
* @param networkViewManager
* to load on left side of top right bimodal.
* @return BiModalJSplitPane Object.
*/
private BiModalJSplitPane createTopRightPane(NetworkViewManager networkViewManager) {
// create cytopanel with tabs along the top
cytoPanelEast = new CytoPanelImp(CytoPanelName.EAST, JTabbedPane.TOP, CytoPanelState.HIDE, cyEventHelper);
// determine proper network view manager component
Component networkViewComp = (Component) networkViewManager.getDesktopPane();
// create the split pane - we show this on startup
BiModalJSplitPane splitPane = new BiModalJSplitPane(this, JSplitPane.HORIZONTAL_SPLIT,
BiModalJSplitPane.MODE_HIDE_SPLIT,
networkViewComp, cytoPanelEast);
// set the cytopanelcontainer
cytoPanelEast.setCytoPanelContainer(splitPane);
// set the resize weight - left component gets extra space
splitPane.setResizeWeight(1.0);
// outta here
return splitPane;
}
/**
* Creates the Right Panel.
*
* @param topRightPane
* TopRightPane Object.
* @return BiModalJSplitPane Object
*/
private BiModalJSplitPane createRightPane(BiModalJSplitPane topRightPane) {
// create cytopanel with tabs along the bottom
cytoPanelSouth = new CytoPanelImp(CytoPanelName.SOUTH, JTabbedPane.BOTTOM,
CytoPanelState.DOCK, cyEventHelper);
// create the split pane - hidden by default
BiModalJSplitPane splitPane = new BiModalJSplitPane(this, JSplitPane.VERTICAL_SPLIT,
BiModalJSplitPane.MODE_HIDE_SPLIT,
topRightPane, cytoPanelSouth);
// set the cytopanel container
cytoPanelSouth.setCytoPanelContainer(splitPane);
splitPane.setDividerSize(DEVIDER_SIZE);
splitPane.setDividerLocation(DEF_DIVIDER_LOATION);
// set resize weight - top component gets all the extra space.
splitPane.setResizeWeight(1.0);
// outta here
return splitPane;
}
private void createBottomLeft() {
// create cytopanel with tabs along the top for manual layout
cytoPanelSouthWest = new CytoPanelImp(CytoPanelName.SOUTH_WEST,
JTabbedPane.TOP,
CytoPanelState.HIDE, cyEventHelper);
final BiModalJSplitPane split = new BiModalJSplitPane(this, JSplitPane.VERTICAL_SPLIT,
BiModalJSplitPane.MODE_HIDE_SPLIT, new JPanel(),
cytoPanelSouthWest);
split.setResizeWeight(0);
cytoPanelSouthWest.setCytoPanelContainer(split);
cytoPanelSouthWest.setMinimumSize(new Dimension(180, 330));
cytoPanelSouthWest.setMaximumSize(new Dimension(180, 330));
cytoPanelSouthWest.setPreferredSize(new Dimension(180, 330));
split.setDividerSize(DEVIDER_SIZE);
ToolCytoPanelListener t = new ToolCytoPanelListener( split, cytoPanelWest,
cytoPanelSouthWest );
registrar.registerService(t,CytoPanelStateChangedListener.class,new Properties());
}
/**
* Creates the Master Split Pane.
*
* @param networkPanel
* to load on left side of CytoPanel (cytoPanelWest).
* @param rightPane
* BiModalJSplitPane Object.
* @return BiModalJSplitPane Object.
*/
private BiModalJSplitPane createMasterPane(NetworkPanel networkPanel,
BiModalJSplitPane rightPane) {
// create cytopanel with tabs along the top
cytoPanelWest = new CytoPanelImp(CytoPanelName.WEST, JTabbedPane.TOP, CytoPanelState.DOCK, cyEventHelper);
// add the network panel to our tab
String tab1Name = new String("Network");
cytoPanelWest.add(tab1Name, new ImageIcon(getClass().getResource("/images/class_hi.gif")),
networkPanel, "Cytoscape Network List");
// create the split pane - hidden by default
BiModalJSplitPane splitPane = new BiModalJSplitPane(this, JSplitPane.HORIZONTAL_SPLIT,
BiModalJSplitPane.MODE_SHOW_SPLIT,
cytoPanelWest, rightPane);
splitPane.setDividerSize(DEVIDER_SIZE);
// set the cytopanel container
cytoPanelWest.setCytoPanelContainer(splitPane);
// outta here
return splitPane;
}
NetworkViewManager getNetworkViewManager() {
return networkViewManager;
}
public void addAction(CyAction action, Dictionary props) {
cyMenus.addAction(action);
}
public void addAction(CyAction action) {
cyMenus.addAction(action);
}
public void removeAction(CyAction action, Dictionary props) {
cyMenus.removeAction(action);
}
public void removeAction(CyAction action) {
cyMenus.removeAction(action);
}
public JMenu getJMenu(String name) {
return cyMenus.getJMenu(name);
}
public JMenuBar getJMenuBar() {
return cyMenus.getJMenuBar();
}
public JToolBar getJToolBar() {
return cyMenus.getJToolBar();
}
public JFrame getJFrame() {
return this;
}
public CytoPanel getCytoPanel(final CytoPanelName compassDirection) {
return getCytoPanelInternal(compassDirection);
}
private CytoPanelImp getCytoPanelInternal(final CytoPanelName compassDirection) {
// return appropriate cytoPanel based on compass direction
switch (compassDirection) {
case SOUTH:
return cytoPanelSouth;
case EAST:
return cytoPanelEast;
case WEST:
return cytoPanelWest;
case SOUTH_WEST:
return cytoPanelSouthWest;
}
// houston we have a problem
throw new IllegalArgumentException("Illegal Argument: " + compassDirection
+ ". Must be one of: {SOUTH,EAST,WEST,SOUTH_WEST}.");
}
public void addCytoPanelComponent(CytoPanelComponent cp, Dictionary props) {
CytoPanelImp impl = getCytoPanelInternal(cp.getCytoPanelName());
impl.add(cp);
}
public void removeCytoPanelComponent(CytoPanelComponent cp, Dictionary props) {
CytoPanelImp impl = getCytoPanelInternal(cp.getCytoPanelName());
impl.remove(cp);
}
public JToolBar getStatusToolBar() {
return statusToolBar;
}
public void addToolBarComponent(ToolBarComponent tp, Dictionary props) {
((CytoscapeToolBar)cyMenus.getJToolBar()).addToolBarComponent(tp);
}
public void removeToolBarComponent(ToolBarComponent tp, Dictionary props) {
((CytoscapeToolBar)cyMenus.getJToolBar()).removeToolBarComponent(tp);
}
// handle CytoscapeStartEvent
@Override
public void handleEvent(CytoscapeStartEvent e) {
this.setVisible(true);
this.toFront();
}
@Override
public void handleEvent(SessionLoadedEvent e) {
// restore the states of the CytoPanels
Cysession cysess = e.getLoadedSession().getCysession();
SessionState sessionState = cysess.getSessionState();
if (sessionState != null) {
Cytopanels cytopanels = sessionState.getCytopanels();
if (cytopanels != null) {
List<Cytopanel> cytopanelsList = cytopanels.getCytopanel();
for (Cytopanel cytopanel : cytopanelsList) {
String id = cytopanel.getId();
CytoPanelName panelName = CYTOPANEL_NAMES.get(id);
if (panelName != null) {
CytoPanel p = getCytoPanelInternal(panelName);
try {
p.setState(CytoPanelState.valueOf(cytopanel.getPanelState().toUpperCase().trim()));
} catch (Exception ex) {
logger.error("Cannot restore the state of panel \"" + panelName.getTitle() + "\"",
ex);
}
try {
p.setSelectedIndex(Integer.parseInt(cytopanel.getSelectedPanel()));
} catch (Exception ex) {
logger.error("Cannot restore the selected index of panel \"" + panelName.getTitle() + "\"",
ex);
}
}
}
}
}
}
@Override
public void handleEvent(SessionAboutToBeSavedEvent e) {
// save the desktop size
BigInteger w = BigInteger.valueOf(this.getWidth());
BigInteger h = BigInteger.valueOf(this.getHeight());
DesktopSize size = new DesktopSize();
size.setWidth(w);
size.setHeight(h);
Desktop desktop = e.getDesktop();
if (desktop == null) {
desktop = new Desktop();
e.setDesktop(desktop);
}
desktop.setDesktopSize(size);
// save the states of the CytoPanels
for (Map.Entry<String, CytoPanelName> entry : CYTOPANEL_NAMES.entrySet()) {
CytoPanel p = getCytoPanelInternal(entry.getValue());
Cytopanel cytopanel = new Cytopanel();
cytopanel.setId(entry.getKey());
cytopanel.setPanelState(p.getState().toString());
cytopanel.setSelectedPanel(Integer.toString(p.getSelectedIndex()));
try {
e.addCytopanel(cytopanel);
} catch (Exception ex) {
logger.error("Cannot add Cytopanel to SessionAboutToBeSavedEvent", ex);
}
}
}
}
| Divider location modified.
| swing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeDesktop.java | Divider location modified. | <ide><path>wing-application-impl/src/main/java/org/cytoscape/internal/view/CytoscapeDesktop.java
<ide>
<ide> private final static long serialVersionUID = 1202339866271348L;
<ide>
<del> private static final Dimension DEF_DESKTOP_SIZE = new Dimension(1100, 800);
<add> private static final Dimension DEF_DESKTOP_SIZE = new Dimension(1150, 850);
<ide> private static final int DEF_DIVIDER_LOATION = 450;
<ide>
<ide> private static final String SMALL_ICON = "/images/c16.png";
<ide> setContentPane(main_panel);
<ide> pack();
<ide> setSize(DEF_DESKTOP_SIZE);
<add>
<add> // Defines default divider location for the network panel to JDesktop
<add> masterPane.setDividerLocation(400);
<ide>
<ide> // Move it to the center
<ide> this.setLocationRelativeTo(null); |
|
Java | bsd-3-clause | eb208c2e6e8d565ace7eb06a67c151cc771d811d | 0 | guywithnose/iCal4j,guywithnose/iCal4j,guywithnose/iCal4j | package net.fortuna.ical4j;
import junit.framework.Test;
import junit.framework.TestSuite;
import net.fortuna.ical4j.data.CalendarBuilderTest;
import net.fortuna.ical4j.data.CalendarParserImplTest;
import net.fortuna.ical4j.filter.FilterTest;
import net.fortuna.ical4j.filter.HasPropertyRuleTest;
import net.fortuna.ical4j.filter.PeriodRuleTest;
import net.fortuna.ical4j.model.AddressListTest;
import net.fortuna.ical4j.model.CalendarTest;
import net.fortuna.ical4j.model.DateTest;
import net.fortuna.ical4j.model.DateTimeTest;
import net.fortuna.ical4j.model.DurTest;
import net.fortuna.ical4j.model.IndexedComponentListTest;
import net.fortuna.ical4j.model.IndexedPropertyListTest;
import net.fortuna.ical4j.model.NumberListTest;
import net.fortuna.ical4j.model.ParameterFactoryImplTest;
import net.fortuna.ical4j.model.PeriodListTest;
import net.fortuna.ical4j.model.PeriodTest;
import net.fortuna.ical4j.model.PropertyTest;
import net.fortuna.ical4j.model.RecurTest;
import net.fortuna.ical4j.model.ResourceListTest;
import net.fortuna.ical4j.model.TimeZoneTest;
import net.fortuna.ical4j.model.UtcOffsetTest;
import net.fortuna.ical4j.model.WeekDayTest;
import net.fortuna.ical4j.model.component.VAlarmTest;
import net.fortuna.ical4j.model.component.VEventTest;
import net.fortuna.ical4j.model.component.VFreeBusyTest;
import net.fortuna.ical4j.model.component.VTimeZoneTest;
import net.fortuna.ical4j.model.component.XComponentTest;
import net.fortuna.ical4j.model.parameter.AltRepTest;
import net.fortuna.ical4j.model.parameter.CnTest;
import net.fortuna.ical4j.model.parameter.CuTypeTest;
import net.fortuna.ical4j.model.parameter.TzIdTest;
import net.fortuna.ical4j.model.property.AttachTest;
import net.fortuna.ical4j.model.property.CalScaleTest;
import net.fortuna.ical4j.model.property.DtEndTest;
import net.fortuna.ical4j.model.property.DtStartTest;
import net.fortuna.ical4j.model.property.ExDateTest;
import net.fortuna.ical4j.model.property.GeoTest;
import net.fortuna.ical4j.model.property.LocationTest;
import net.fortuna.ical4j.model.property.OrganizerTest;
import net.fortuna.ical4j.model.property.SummaryTest;
import net.fortuna.ical4j.model.property.TriggerTest;
import net.fortuna.ical4j.model.property.VersionTest;
import net.fortuna.ical4j.model.property.XPropertyTest;
import net.fortuna.ical4j.util.StringsTest;
/**
* User: tobli
* Date: Apr 13, 2005
* Time: 11:22:55 AM
*/
public class AllTests extends TestSuite{
/**
* Test suite.
* @return test suite
*/
public static Test suite() {
TestSuite suite = new TestSuite();
// data tests
suite.addTest(CalendarBuilderTest.suite());
// suite.addTest(CalendarOutputterTest.suite());
suite.addTestSuite(CalendarParserImplTest.class);
// filter tests..
suite.addTestSuite(FilterTest.class);
suite.addTestSuite(HasPropertyRuleTest.class);
suite.addTestSuite(PeriodRuleTest.class);
// model tests
suite.addTestSuite(AddressListTest.class);
suite.addTestSuite(CalendarTest.class);
suite.addTestSuite(DateTest.class);
suite.addTestSuite(DateTimeTest.class);
suite.addTestSuite(DurTest.class);
suite.addTestSuite(IndexedComponentListTest.class);
suite.addTestSuite(IndexedPropertyListTest.class);
suite.addTestSuite(NumberListTest.class);
suite.addTestSuite(ParameterFactoryImplTest.class);
suite.addTestSuite(PeriodListTest.class);
suite.addTestSuite(PeriodTest.class);
suite.addTestSuite(RecurTest.class);
suite.addTestSuite(ResourceListTest.class);
suite.addTestSuite(TimeZoneTest.class);
suite.addTestSuite(WeekDayTest.class);
suite.addTestSuite(PropertyTest.class);
suite.addTestSuite(UtcOffsetTest.class);
// component tests
suite.addTestSuite(VAlarmTest.class);
suite.addTestSuite(VEventTest.class);
suite.addTestSuite(VFreeBusyTest.class);
suite.addTestSuite(VTimeZoneTest.class);
suite.addTestSuite(XComponentTest.class);
// parameter tests
suite.addTestSuite(AltRepTest.class);
suite.addTestSuite(CnTest.class);
suite.addTestSuite(CuTypeTest.class);
suite.addTestSuite(TzIdTest.class);
// property tests
suite.addTestSuite(AttachTest.class);
suite.addTestSuite(CalScaleTest.class);
suite.addTestSuite(DtEndTest.class);
suite.addTestSuite(DtStartTest.class);
suite.addTestSuite(ExDateTest.class);
suite.addTestSuite(LocationTest.class);
suite.addTestSuite(OrganizerTest.class);
suite.addTestSuite(SummaryTest.class);
suite.addTestSuite(TriggerTest.class);
suite.addTestSuite(VersionTest.class);
suite.addTestSuite(GeoTest.class);
suite.addTestSuite(XPropertyTest.class);
// util tests
suite.addTestSuite(StringsTest.class);
return suite;
}
}
| test/net/fortuna/ical4j/AllTests.java | package net.fortuna.ical4j;
import junit.framework.Test;
import junit.framework.TestSuite;
import net.fortuna.ical4j.data.CalendarBuilderTest;
import net.fortuna.ical4j.data.CalendarParserImplTest;
import net.fortuna.ical4j.filter.FilterTest;
import net.fortuna.ical4j.filter.HasPropertyRuleTest;
import net.fortuna.ical4j.filter.PeriodRuleTest;
import net.fortuna.ical4j.model.AddressListTest;
import net.fortuna.ical4j.model.CalendarTest;
import net.fortuna.ical4j.model.DateTest;
import net.fortuna.ical4j.model.DateTimeTest;
import net.fortuna.ical4j.model.DurTest;
import net.fortuna.ical4j.model.IndexedComponentListTest;
import net.fortuna.ical4j.model.IndexedPropertyListTest;
import net.fortuna.ical4j.model.NumberListTest;
import net.fortuna.ical4j.model.ParameterFactoryImplTest;
import net.fortuna.ical4j.model.PeriodListTest;
import net.fortuna.ical4j.model.PeriodTest;
import net.fortuna.ical4j.model.PropertyTest;
import net.fortuna.ical4j.model.RecurTest;
import net.fortuna.ical4j.model.ResourceListTest;
import net.fortuna.ical4j.model.TimeZoneTest;
import net.fortuna.ical4j.model.UtcOffsetTest;
import net.fortuna.ical4j.model.WeekDayTest;
import net.fortuna.ical4j.model.component.VAlarmTest;
import net.fortuna.ical4j.model.component.VEventTest;
import net.fortuna.ical4j.model.component.VFreeBusyTest;
import net.fortuna.ical4j.model.component.VTimeZoneTest;
import net.fortuna.ical4j.model.component.XComponentTest;
import net.fortuna.ical4j.model.parameter.AltRepTest;
import net.fortuna.ical4j.model.parameter.CnTest;
import net.fortuna.ical4j.model.parameter.CuTypeTest;
import net.fortuna.ical4j.model.parameter.TzIdTest;
import net.fortuna.ical4j.model.property.AttachTest;
import net.fortuna.ical4j.model.property.CalScaleTest;
import net.fortuna.ical4j.model.property.DtEndTest;
import net.fortuna.ical4j.model.property.DtStartTest;
import net.fortuna.ical4j.model.property.ExDateTest;
import net.fortuna.ical4j.model.property.GeoTest;
import net.fortuna.ical4j.model.property.LocationTest;
import net.fortuna.ical4j.model.property.OrganizerTest;
import net.fortuna.ical4j.model.property.SummaryTest;
import net.fortuna.ical4j.model.property.TriggerTest;
import net.fortuna.ical4j.model.property.VersionTest;
import net.fortuna.ical4j.util.StringsTest;
/**
* User: tobli
* Date: Apr 13, 2005
* Time: 11:22:55 AM
*/
public class AllTests extends TestSuite{
/**
* Test suite.
* @return test suite
*/
public static Test suite() {
TestSuite suite = new TestSuite();
// data tests
suite.addTest(CalendarBuilderTest.suite());
// suite.addTest(CalendarOutputterTest.suite());
suite.addTestSuite(CalendarParserImplTest.class);
// filter tests..
suite.addTestSuite(FilterTest.class);
suite.addTestSuite(HasPropertyRuleTest.class);
suite.addTestSuite(PeriodRuleTest.class);
// model tests
suite.addTestSuite(AddressListTest.class);
suite.addTestSuite(CalendarTest.class);
suite.addTestSuite(DateTest.class);
suite.addTestSuite(DateTimeTest.class);
suite.addTestSuite(DurTest.class);
suite.addTestSuite(IndexedComponentListTest.class);
suite.addTestSuite(IndexedPropertyListTest.class);
suite.addTestSuite(NumberListTest.class);
suite.addTestSuite(ParameterFactoryImplTest.class);
suite.addTestSuite(PeriodListTest.class);
suite.addTestSuite(PeriodTest.class);
suite.addTestSuite(RecurTest.class);
suite.addTestSuite(ResourceListTest.class);
suite.addTestSuite(TimeZoneTest.class);
suite.addTestSuite(WeekDayTest.class);
suite.addTestSuite(PropertyTest.class);
suite.addTestSuite(UtcOffsetTest.class);
// component tests
suite.addTestSuite(VAlarmTest.class);
suite.addTestSuite(VEventTest.class);
suite.addTestSuite(VFreeBusyTest.class);
suite.addTestSuite(VTimeZoneTest.class);
suite.addTestSuite(XComponentTest.class);
// parameter tests
suite.addTestSuite(AltRepTest.class);
suite.addTestSuite(CnTest.class);
suite.addTestSuite(CuTypeTest.class);
suite.addTestSuite(TzIdTest.class);
// property tests
suite.addTestSuite(AttachTest.class);
suite.addTestSuite(CalScaleTest.class);
suite.addTestSuite(DtEndTest.class);
suite.addTestSuite(DtStartTest.class);
suite.addTestSuite(ExDateTest.class);
suite.addTestSuite(LocationTest.class);
suite.addTestSuite(OrganizerTest.class);
suite.addTestSuite(SummaryTest.class);
suite.addTestSuite(TriggerTest.class);
suite.addTestSuite(VersionTest.class);
suite.addTestSuite(GeoTest.class);
// util tests
suite.addTestSuite(StringsTest.class);
return suite;
}
}
| Added xproperty unit tests
| test/net/fortuna/ical4j/AllTests.java | Added xproperty unit tests | <ide><path>est/net/fortuna/ical4j/AllTests.java
<ide> import net.fortuna.ical4j.model.property.SummaryTest;
<ide> import net.fortuna.ical4j.model.property.TriggerTest;
<ide> import net.fortuna.ical4j.model.property.VersionTest;
<add>import net.fortuna.ical4j.model.property.XPropertyTest;
<ide> import net.fortuna.ical4j.util.StringsTest;
<ide>
<ide> /**
<ide> suite.addTestSuite(TriggerTest.class);
<ide> suite.addTestSuite(VersionTest.class);
<ide> suite.addTestSuite(GeoTest.class);
<add> suite.addTestSuite(XPropertyTest.class);
<ide>
<ide> // util tests
<ide> suite.addTestSuite(StringsTest.class); |
|
Java | apache-2.0 | 0553e91a0fd773f6a2ff796b8dfeba26f2189b64 | 0 | jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/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 com.fasterxml.jackson.core.util.VersionUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.mutable.MutableInt;
import org.apache.lucene.analysis.CharArraySet;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.jetbrains.annotations.NotNull;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.cpe.CpeMemoryIndex;
import org.owasp.dependencycheck.data.cpe.Fields;
import org.owasp.dependencycheck.data.cpe.IndexEntry;
import org.owasp.dependencycheck.data.cpe.IndexException;
import org.owasp.dependencycheck.data.cpe.MemoryIndex;
import org.owasp.dependencycheck.data.lucene.LuceneUtils;
import org.owasp.dependencycheck.data.lucene.SearchFieldAnalyzer;
import org.owasp.dependencycheck.data.nvd.ecosystem.Ecosystem;
import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.data.update.cpe.CpePlus;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
import org.owasp.dependencycheck.dependency.EvidenceType;
import org.owasp.dependencycheck.dependency.naming.CpeIdentifier;
import org.owasp.dependencycheck.dependency.naming.Identifier;
import org.owasp.dependencycheck.dependency.naming.PurlIdentifier;
import org.owasp.dependencycheck.exception.InitializationException;
import org.owasp.dependencycheck.utils.DependencyVersion;
import org.owasp.dependencycheck.utils.DependencyVersionUtil;
import org.owasp.dependencycheck.utils.Pair;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.springett.parsers.cpe.Cpe;
import us.springett.parsers.cpe.CpeBuilder;
import us.springett.parsers.cpe.exceptions.CpeValidationException;
import us.springett.parsers.cpe.values.Part;
/**
* CPEAnalyzer is a utility class that takes a project dependency and attempts
* to discern if there is an associated CPE. It uses the evidence contained
* within the dependency to search the Lucene index.
*
* @author Jeremy Long
*/
@ThreadSafe
public class CPEAnalyzer extends AbstractAnalyzer {
/**
* The Logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(CPEAnalyzer.class);
/**
* The weighting boost to give terms when constructing the Lucene query.
*/
private static final int WEIGHTING_BOOST = 1;
/**
* A string representation of a regular expression defining characters
* utilized within the CPE Names. Note, the :/ are included so URLs are
* passed into the Lucene query so that the specialized tokenizer can parse
* them.
*/
private static final String CLEANSE_CHARACTER_RX = "[^A-Za-z0-9 ._:/-]";
/**
* A string representation of a regular expression used to remove all but
* alpha characters.
*/
private static final String CLEANSE_NONALPHA_RX = "[^A-Za-z]*";
/**
* UTF-8 character set name.
*/
private static final String UTF8 = StandardCharsets.UTF_8.name();
/**
* The URL to search the NVD CVE data at NIST. This is used by calling:
* <pre>String.format(NVD_SEARCH_URL, vendor, product, version);</pre>
*/
public static final String NVD_SEARCH_URL = "https://nvd.nist.gov/vuln/search/results?form_type=Advanced&"
+ "results_type=overview&search_type=all&cpe_vendor=cpe%%3A%%2F%%3A%1$s&cpe_product=cpe%%3A%%2F%%3A%1$s%%3A%2$s&"
+ "cpe_version=cpe%%3A%%2F%%3A%1$s%%3A%2$s%%3A%3$s";
/**
* The URL to search the NVD CVE data at NIST. This is used by calling:
* <pre>String.format(NVD_SEARCH_URL, vendor, product);</pre>
*/
public static final String NVD_SEARCH_BROAD_URL = "https://nvd.nist.gov/vuln/search/results?form_type=Advanced&"
+ "results_type=overview&search_type=all&cpe_vendor=cpe%%3A%%2F%%3A%1$s&cpe_product=cpe%%3A%%2F%%3A%1$s%%3A%2$s";
/**
* The CPE in memory index.
*/
private MemoryIndex cpe;
/**
* The CVE Database.
*/
private CveDB cve;
/**
* The list of ecosystems to skip during analysis. These are skipped because
* there is generally a more accurate vulnerability analyzer in the
* pipeline.
*/
private List<String> skipEcosystems;
/**
* A reference to the ecosystem object; used to obtain the max query results
* for each ecosystem.
*/
private Ecosystem ecosystemTools;
/**
* A reference to the suppression analyzer; for timing reasons we need to
* test for suppressions immediately after identifying the match because a
* higher confidence match on a FP can mask a lower confidence, yet valid
* match.
*/
private CpeSuppressionAnalyzer suppression;
/**
* Returns the name of this analyzer.
*
* @return the name of this analyzer.
*/
@Override
public String getName() {
return "CPE Analyzer";
}
/**
* Returns the analysis phase that this analyzer should run in.
*
* @return the analysis phase that this analyzer should run in.
*/
@Override
public AnalysisPhase getAnalysisPhase() {
return AnalysisPhase.IDENTIFIER_ANALYSIS;
}
/**
* Creates the CPE Lucene Index.
*
* @param engine a reference to the dependency-check engine
* @throws InitializationException is thrown if there is an issue opening
* the index.
*/
@Override
public void prepareAnalyzer(Engine engine) throws InitializationException {
super.prepareAnalyzer(engine);
try {
this.open(engine.getDatabase());
} catch (IOException ex) {
LOGGER.debug("Exception initializing the Lucene Index", ex);
throw new InitializationException("An exception occurred initializing the Lucene Index", ex);
} catch (DatabaseException ex) {
LOGGER.debug("Exception accessing the database", ex);
throw new InitializationException("An exception occurred accessing the database", ex);
}
final String[] tmp = engine.getSettings().getArray(Settings.KEYS.ECOSYSTEM_SKIP_CPEANALYZER);
if (tmp == null) {
skipEcosystems = new ArrayList<>();
} else {
LOGGER.debug("Skipping CPE Analysis for {}", StringUtils.join(tmp, ","));
skipEcosystems = Arrays.asList(tmp);
}
ecosystemTools = new Ecosystem(engine.getSettings());
suppression = new CpeSuppressionAnalyzer();
suppression.initialize(engine.getSettings());
suppression.prepareAnalyzer(engine);
}
/**
* Opens the data source.
*
* @param cve a reference to the NVD CVE database
* @throws IOException when the Lucene directory to be queried does not
* exist or is corrupt.
* @throws DatabaseException when the database throws an exception. This
* usually occurs when the database is in use by another process.
*/
public void open(CveDB cve) throws IOException, DatabaseException {
this.cve = cve;
this.cpe = CpeMemoryIndex.getInstance();
try {
final long creationStart = System.currentTimeMillis();
cpe.open(cve.getVendorProductList(), this.getSettings());
final long creationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - creationStart);
LOGGER.info("Created CPE Index ({} seconds)", creationSeconds);
} catch (IndexException ex) {
LOGGER.debug("IndexException", ex);
throw new DatabaseException(ex);
}
}
/**
* Closes the data sources.
*/
@Override
public void closeAnalyzer() {
if (cpe != null) {
cpe.close();
cpe = null;
}
}
/**
* Searches the data store of CPE entries, trying to identify the CPE for
* the given dependency based on the evidence contained within. The
* dependency passed in is updated with any identified CPE values.
*
* @param dependency the dependency to search for CPE entries on
* @throws CorruptIndexException is thrown when the Lucene index is corrupt
* @throws IOException is thrown when an IOException occurs
* @throws ParseException is thrown when the Lucene query cannot be parsed
* @throws AnalysisException thrown if the suppression rules failed
*/
protected void determineCPE(Dependency dependency) throws CorruptIndexException, IOException, ParseException, AnalysisException {
boolean identifierAdded;
Set<String> majorVersions = dependency.getSoftwareIdentifiers()
.stream()
.filter(i -> i instanceof PurlIdentifier)
.map(i -> {
PurlIdentifier p = (PurlIdentifier) i;
DependencyVersion depVersion = DependencyVersionUtil.parseVersion(p.getVersion(), false);
if (depVersion != null) {
return depVersion.getVersionParts().get(0);
}
return null;
}).collect(Collectors.toSet());
final Map<String, MutableInt> vendors = new HashMap<>();
final Map<String, MutableInt> products = new HashMap<>();
final Set<Integer> previouslyFound = new HashSet<>();
for (Confidence confidence : Confidence.values()) {
collectTerms(vendors, dependency.getIterator(EvidenceType.VENDOR, confidence));
LOGGER.debug("vendor search: {}", vendors);
collectTerms(products, dependency.getIterator(EvidenceType.PRODUCT, confidence));
addMajorVersionToTerms(majorVersions, products);
LOGGER.debug("product search: {}", products);
if (!vendors.isEmpty() && !products.isEmpty()) {
final List<IndexEntry> entries = searchCPE(vendors, products,
dependency.getVendorWeightings(), dependency.getProductWeightings(),
dependency.getEcosystem());
if (entries == null) {
continue;
}
identifierAdded = false;
for (IndexEntry e : entries) {
if (previouslyFound.contains(e.getDocumentId()) /*|| (filter > 0 && e.getSearchScore() < filter)*/) {
continue;
}
previouslyFound.add(e.getDocumentId());
if (verifyEntry(e, dependency, majorVersions)) {
final String vendor = e.getVendor();
final String product = e.getProduct();
LOGGER.debug("identified vendor/product: {}/{}", vendor, product);
identifierAdded |= determineIdentifiers(dependency, vendor, product, confidence);
}
}
if (identifierAdded) {
break;
}
}
}
}
/**
* <p>
* Returns the text created by concatenating the text and the values from
* the EvidenceCollection (filtered for a specific confidence). This
* attempts to prevent duplicate terms from being added.</p>
* <p>
* Note, if the evidence is longer then 1000 characters it will be
* truncated.</p>
*
* @param terms the collection of terms
* @param evidence an iterable set of evidence to concatenate
*/
@SuppressWarnings("null")
protected void collectTerms(Map<String, MutableInt> terms, Iterable<Evidence> evidence) {
for (Evidence e : evidence) {
String value = cleanseText(e.getValue());
if (StringUtils.isBlank(value)) {
continue;
}
if (value.length() > 1000) {
boolean trimmed = false;
int pos = value.lastIndexOf(" ", 1000);
if (pos > 0) {
value = value.substring(0, pos);
trimmed = true;
} else {
pos = value.lastIndexOf(".", 1000);
}
if (!trimmed) {
if (pos > 0) {
value = value.substring(0, pos);
trimmed = true;
} else {
pos = value.lastIndexOf("-", 1000);
}
}
if (!trimmed) {
if (pos > 0) {
value = value.substring(0, pos);
trimmed = true;
} else {
pos = value.lastIndexOf("_", 1000);
}
}
if (!trimmed) {
if (pos > 0) {
value = value.substring(0, pos);
trimmed = true;
} else {
pos = value.lastIndexOf("/", 1000);
}
}
if (!trimmed && pos > 0) {
value = value.substring(0, pos);
trimmed = true;
}
if (!trimmed) {
value = value.substring(0, 1000);
}
}
addTerm(terms, value);
}
}
private void addMajorVersionToTerms(Set<String> majorVersions, Map<String, MutableInt> products) {
Map<String, MutableInt> temp = new HashMap<>();
products.entrySet().stream()
.filter(term -> term.getKey() != null)
.forEach(term -> {
majorVersions.stream()
.filter(version -> version != null
&& (!term.getKey().endsWith(version)
&& !Character.isDigit(term.getKey().charAt(term.getKey().length() - 1))
&& !products.containsKey(term.getKey() + version)))
.forEach(version -> {
addTerm(temp, term.getKey() + version);
});
});
products.putAll(temp);
}
/**
* Adds a term to the map of terms.
*
* @param terms the map of terms
* @param value the value of the term to add
*/
private void addTerm(Map<String, MutableInt> terms, String value) {
final MutableInt count = terms.get(value);
if (count == null) {
terms.put(value, new MutableInt(1));
} else {
count.add(1);
}
}
/**
* <p>
* Searches the Lucene CPE index to identify possible CPE entries associated
* with the supplied vendor, product, and version.</p>
*
* <p>
* If either the vendorWeightings or productWeightings lists have been
* populated this data is used to add weighting factors to the search.</p>
*
* @param vendor the text used to search the vendor field
* @param product the text used to search the product field
* @param vendorWeightings a list of strings to use to add weighting factors
* to the vendor field
* @param productWeightings Adds a list of strings that will be used to add
* weighting factors to the product search
* @param ecosystem the dependency's ecosystem
* @return a list of possible CPE values
*/
protected List<IndexEntry> searchCPE(Map<String, MutableInt> vendor, Map<String, MutableInt> product,
Set<String> vendorWeightings, Set<String> productWeightings, String ecosystem) {
final int maxQueryResults = ecosystemTools.getLuceneMaxQueryLimitFor(ecosystem);
final List<IndexEntry> ret = new ArrayList<>(maxQueryResults);
final String searchString = buildSearch(vendor, product, vendorWeightings, productWeightings);
if (searchString == null) {
return ret;
}
try {
final Query query = cpe.parseQuery(searchString);
final TopDocs docs = cpe.search(query, maxQueryResults);
for (ScoreDoc d : docs.scoreDocs) {
//if (d.score >= minLuceneScore) {
final Document doc = cpe.getDocument(d.doc);
final IndexEntry entry = new IndexEntry();
entry.setDocumentId(d.doc);
entry.setVendor(doc.get(Fields.VENDOR));
entry.setProduct(doc.get(Fields.PRODUCT));
entry.setSearchScore(d.score);
// LOGGER.error("Explanation: ---------------------");
// LOGGER.error("Explanation: " + entry.getVendor() + " " + entry.getProduct() + " " + entry.getSearchScore());
// LOGGER.error("Explanation: " + searchString);
// LOGGER.error("Explanation: " + cpe.explain(query, d.doc));
if (!ret.contains(entry)) {
ret.add(entry);
}
//}
}
return ret;
} catch (ParseException ex) {
LOGGER.warn("An error occurred querying the CPE data. See the log for more details.");
LOGGER.info("Unable to parse: {}", searchString, ex);
} catch (IndexException ex) {
LOGGER.warn("An error occurred resetting the CPE index searcher. See the log for more details.");
LOGGER.info("Unable to reset the search analyzer", ex);
} catch (IOException ex) {
LOGGER.warn("An error occurred reading CPE data. See the log for more details.");
LOGGER.info("IO Error with search string: {}", searchString, ex);
}
return null;
}
/**
* <p>
* Builds a Lucene search string by properly escaping data and constructing
* a valid search query.</p>
*
* <p>
* If either the possibleVendor or possibleProducts lists have been
* populated this data is used to add weighting factors to the search string
* generated.</p>
*
* @param vendor text to search the vendor field
* @param product text to search the product field
* @param vendorWeighting a list of strings to apply to the vendor to boost
* the terms weight
* @param productWeightings a list of strings to apply to the product to
* boost the terms weight
* @return the Lucene query
*/
protected String buildSearch(Map<String, MutableInt> vendor, Map<String, MutableInt> product,
Set<String> vendorWeighting, Set<String> productWeightings) {
final StringBuilder sb = new StringBuilder();
if (!appendWeightedSearch(sb, Fields.PRODUCT, product, productWeightings)) {
return null;
}
sb.append(" AND ");
if (!appendWeightedSearch(sb, Fields.VENDOR, vendor, vendorWeighting)) {
return null;
}
return sb.toString();
}
/**
* This method constructs a Lucene query for a given field. The searchText
* is split into separate words and if the word is within the list of
* weighted words then an additional weighting is applied to the term as it
* is appended into the query.
*
* @param sb a StringBuilder that the query text will be appended to.
* @param field the field within the Lucene index that the query is
* searching.
* @param terms text used to construct the query.
* @param weightedText a list of terms that will be considered higher
* importance when searching.
* @return if the append was successful.
*/
@SuppressWarnings("StringSplitter")
private boolean appendWeightedSearch(StringBuilder sb, String field, Map<String, MutableInt> terms, Set<String> weightedText) {
if (terms.isEmpty()) {
return false;
}
sb.append(field).append(":(");
boolean addSpace = false;
boolean addedTerm = false;
for (Map.Entry<String, MutableInt> entry : terms.entrySet()) {
final StringBuilder boostedTerms = new StringBuilder();
final int weighting = entry.getValue().intValue();
final String[] text = entry.getKey().split(" ");
for (String word : text) {
if (word.isEmpty()) {
continue;
}
if (addSpace) {
sb.append(" ");
} else {
addSpace = true;
}
addedTerm = true;
if (LuceneUtils.isKeyword(word)) {
sb.append("\"");
LuceneUtils.appendEscapedLuceneQuery(sb, word);
sb.append("\"");
} else {
LuceneUtils.appendEscapedLuceneQuery(sb, word);
}
final String boostTerm = findBoostTerm(word, weightedText);
//The weighting is on a full phrase rather then at a term level for vendor or products
//TODO - should the weighting be at a "word" level as opposed to phrase level? Or combined word and phrase?
//remember the reason we are counting the frequency of "phrases" as opposed to terms is that
//we need to keep the correct sequence of terms from the evidence so the term concatenating analyzer
//works correctly and will causes searches to take spring framework and produce: spring springframework framework
if (boostTerm != null) {
sb.append("^").append(weighting + WEIGHTING_BOOST);
if (!boostTerm.equals(word)) {
boostedTerms.append(" ").append(boostTerm).append("^").append(weighting + WEIGHTING_BOOST);
}
} else if (weighting > 1) {
sb.append("^").append(weighting);
}
}
if (boostedTerms.length() > 0) {
sb.append(boostedTerms);
}
}
sb.append(")");
return addedTerm;
}
/**
* Removes characters from the input text that are not used within the CPE
* index.
*
* @param text is the text to remove the characters from.
* @return the text having removed some characters.
*/
private String cleanseText(String text) {
return text.replaceAll(CLEANSE_CHARACTER_RX, " ");
}
/**
* Searches the collection of boost terms for the given term. The elements
* are case insensitive matched using only the alpha-numeric contents of the
* terms; all other characters are removed.
*
* @param term the term to search for
* @param boost the collection of boost terms
* @return the value identified
*/
private String findBoostTerm(String term, Set<String> boost) {
for (String entry : boost) {
if (equalsIgnoreCaseAndNonAlpha(term, entry)) {
return entry;
}
}
return null;
}
/**
* Compares two strings after lower casing them and removing the non-alpha
* characters.
*
* @param l string one to compare.
* @param r string two to compare.
* @return whether or not the two strings are similar.
*/
private boolean equalsIgnoreCaseAndNonAlpha(String l, String r) {
if (l == null || r == null) {
return false;
}
final String left = l.replaceAll(CLEANSE_NONALPHA_RX, "");
final String right = r.replaceAll(CLEANSE_NONALPHA_RX, "");
return left.equalsIgnoreCase(right);
}
/**
* Ensures that the CPE Identified matches the dependency. This validates
* that the product, vendor, and version information for the CPE are
* contained within the dependencies evidence.
*
* @param entry a CPE entry.
* @param dependency the dependency that the CPE entries could be for.
* @return whether or not the entry is valid.
*/
private boolean verifyEntry(final IndexEntry entry, final Dependency dependency,
final Set<String> majorVersions) {
boolean isValid = false;
//TODO - does this nullify some of the fuzzy matching that happens in the lucene search?
// for instance CPE some-component and in the evidence we have SomeComponent.
//TODO - should this have a package manager only flag instead of just looking for NPM
if (Ecosystem.NODEJS.equals(dependency.getEcosystem())) {
for (Identifier i : dependency.getSoftwareIdentifiers()) {
if (i instanceof PurlIdentifier) {
final PurlIdentifier p = (PurlIdentifier) i;
if (cleanPackageName(p.getName()).equals(cleanPackageName(entry.getProduct()))) {
isValid = true;
}
}
}
} else if (collectionContainsString(dependency.getEvidence(EvidenceType.VENDOR), entry.getVendor())) {
if (collectionContainsString(dependency.getEvidence(EvidenceType.PRODUCT), entry.getProduct())) {
isValid = true;
} else {
isValid = majorVersions.stream().filter(version -> entry.getProduct().endsWith(version) && entry.getProduct().length() > version.length())
.anyMatch(version
-> collectionContainsString(dependency.getEvidence(EvidenceType.PRODUCT), entry.getProduct().substring(0, entry.getProduct().length() - version.length()))
);
}
}
return isValid;
}
/**
* Only returns alpha numeric characters contained in a given package name.
*
* @param name the package name to cleanse
* @return the cleansed packaage name
*/
private String cleanPackageName(String name) {
if (name == null) {
return "";
}
return name.replaceAll("[^a-zA-Z0-9]+", "");
}
/**
* Used to determine if the EvidenceCollection contains a specific string.
*
* @param evidence an of evidence object to check
* @param text the text to search for
* @return whether or not the EvidenceCollection contains the string
*/
@SuppressWarnings("StringSplitter")
private boolean collectionContainsString(Set<Evidence> evidence, String text) {
//TODO - likely need to change the split... not sure if this will work for CPE with special chars
if (text == null) {
return false;
}
// Check if we have an exact match
final String textLC = text.toLowerCase();
for (Evidence e : evidence) {
if (e.getValue().toLowerCase().equals(textLC)) {
return true;
}
}
final String[] words = text.split("[\\s_-]+");
final List<String> list = new ArrayList<>();
String tempWord = null;
final CharArraySet stopWords = SearchFieldAnalyzer.getStopWords();
for (String word : words) {
/*
single letter words should be concatenated with the next word.
so { "m", "core", "sample" } -> { "mcore", "sample" }
*/
if (tempWord != null) {
list.add(tempWord + word);
tempWord = null;
} else if (word.length() <= 2) {
tempWord = word;
} else {
if (stopWords.contains(word)) {
continue;
}
list.add(word);
}
}
if (tempWord != null) {
if (!list.isEmpty()) {
final String tmp = list.get(list.size() - 1) + tempWord;
list.add(tmp);
} else {
list.add(tempWord);
}
}
if (list.isEmpty()) {
return false;
}
boolean isValid = true;
// Prepare the evidence values, e.g. remove the characters we used for splitting
final List<String> evidenceValues = new ArrayList<>(evidence.size());
evidence.forEach((e) -> {
evidenceValues.add(e.getValue().toLowerCase().replaceAll("[\\s_-]+", ""));
});
for (String word : list) {
word = word.toLowerCase();
boolean found = false;
for (String e : evidenceValues) {
if (e.contains(word)) {
if ("http".equals(word) && e.contains("http:")) {
continue;
}
found = true;
break;
}
}
isValid &= found;
// if (!isValid) {
// break;
// }
}
return isValid;
}
/**
* Analyzes a dependency and attempts to determine if there are any CPE
* identifiers for this dependency.
*
* @param dependency The Dependency to analyze.
* @param engine The analysis engine
* @throws AnalysisException is thrown if there is an issue analyzing the
* dependency.
*/
@Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
if (skipEcosystems.contains(dependency.getEcosystem())) {
return;
}
try {
determineCPE(dependency);
} catch (CorruptIndexException ex) {
throw new AnalysisException("CPE Index is corrupt.", ex);
} catch (IOException ex) {
throw new AnalysisException("Failure opening the CPE Index.", ex);
} catch (ParseException ex) {
throw new AnalysisException("Unable to parse the generated Lucene query for this dependency.", ex);
}
}
/**
* Retrieves a list of CPE values from the CveDB based on the vendor and
* product passed in. The list is then validated to find only CPEs that are
* valid for the given dependency. It is possible that the CPE identified is
* a best effort "guess" based on the vendor, product, and version
* information.
*
* @param dependency the Dependency being analyzed
* @param vendor the vendor for the CPE being analyzed
* @param product the product for the CPE being analyzed
* @param currentConfidence the current confidence being used during
* analysis
* @return <code>true</code> if an identifier was added to the dependency;
* otherwise <code>false</code>
* @throws UnsupportedEncodingException is thrown if UTF-8 is not supported
* @throws AnalysisException thrown if the suppression rules failed
*/
@SuppressWarnings("StringSplitter")
protected boolean determineIdentifiers(Dependency dependency, String vendor, String product,
Confidence currentConfidence) throws UnsupportedEncodingException, AnalysisException {
final CpeBuilder cpeBuilder = new CpeBuilder();
final Set<CpePlus> cpePlusEntries = cve.getCPEs(vendor, product);
final Set<Cpe> cpes = filterEcosystem(dependency.getEcosystem(), cpePlusEntries);
if (cpes == null || cpes.isEmpty()) {
return false;
}
DependencyVersion bestGuess;
if ("Golang".equals(dependency.getEcosystem()) && dependency.getVersion() == null) {
bestGuess = new DependencyVersion("*");
} else {
bestGuess = new DependencyVersion("-");
}
String bestGuessUpdate = null;
Confidence bestGuessConf = null;
String bestGuessURL = null;
final Set<IdentifierMatch> collected = new HashSet<>();
if (dependency.getVersion() != null && !dependency.getVersion().isEmpty()) {
//we shouldn't always use the dependency version - in some cases this causes FP
boolean useDependencyVersion = true;
final CharArraySet stopWords = SearchFieldAnalyzer.getStopWords();
if (dependency.getName() != null && !dependency.getName().isEmpty()) {
final String name = dependency.getName();
for (String word : product.split("[^a-zA-Z0-9]")) {
useDependencyVersion &= name.contains(word) || stopWords.contains(word);
}
}
if (useDependencyVersion) {
//TODO - we need to filter this so that we only use this if something in the
//dependency.getName() matches the vendor/product in some way
final DependencyVersion depVersion = new DependencyVersion(dependency.getVersion());
if (depVersion.getVersionParts().size() > 0) {
cpeBuilder.part(Part.APPLICATION).vendor(vendor).product(product);
addVersionAndUpdate(depVersion, cpeBuilder);
try {
final Cpe depCpe = cpeBuilder.build();
final String url = String.format(NVD_SEARCH_URL, URLEncoder.encode(vendor, UTF8),
URLEncoder.encode(product, UTF8), URLEncoder.encode(depCpe.getVersion(), UTF8));
final IdentifierMatch match = new IdentifierMatch(depCpe, url, IdentifierConfidence.EXACT_MATCH, currentConfidence);
collected.add(match);
} catch (CpeValidationException ex) {
throw new AnalysisException(String.format("Unable to create a CPE for %s:%s:%s", vendor, product, bestGuess.toString()));
}
}
}
}
//TODO the following algorithm incorrectly identifies things as a lower version
// if there lower confidence evidence when the current (highest) version number
// is newer then anything in the NVD.
for (Confidence conf : Confidence.values()) {
for (Evidence evidence : dependency.getIterator(EvidenceType.VERSION, conf)) {
final DependencyVersion evVer = DependencyVersionUtil.parseVersion(evidence.getValue(), true);
if (evVer == null) {
continue;
}
DependencyVersion evBaseVer = null;
String evBaseVerUpdate = null;
final int idx = evVer.getVersionParts().size() - 1;
if (evVer.getVersionParts().get(idx)
.matches("^(v|release|final|snapshot|beta|alpha|u|rc|m|20\\d\\d).*$")) {
//store the update version
final String checkUpdate = evVer.getVersionParts().get(idx);
if (checkUpdate.matches("^(v|release|final|snapshot|beta|alpha|u|rc|m|20\\d\\d).*$")) {
evBaseVerUpdate = checkUpdate;
evBaseVer = new DependencyVersion();
evBaseVer.setVersionParts(evVer.getVersionParts().subList(0, idx));
}
}
//TODO - review and update for new JSON data
for (Cpe vs : cpes) {
final DependencyVersion dbVer = DependencyVersionUtil.parseVersion(vs.getVersion());
DependencyVersion dbVerUpdate = dbVer;
if (vs.getUpdate() != null && !vs.getUpdate().isEmpty() && !vs.getUpdate().startsWith("*") && !vs.getUpdate().startsWith("-")) {
dbVerUpdate = DependencyVersionUtil.parseVersion(vs.getVersion() + '.' + vs.getUpdate(), true);
}
if (dbVer == null) { //special case, no version specified - everything is vulnerable
final String url = String.format(NVD_SEARCH_BROAD_URL, URLEncoder.encode(vs.getVendor(), UTF8),
URLEncoder.encode(vs.getProduct(), UTF8));
final IdentifierMatch match = new IdentifierMatch(vs, url, IdentifierConfidence.BROAD_MATCH, conf);
collected.add(match);
} else if (evVer.equals(dbVer)) { //yeah! exact match
final String url = String.format(NVD_SEARCH_URL, URLEncoder.encode(vs.getVendor(), UTF8),
URLEncoder.encode(vs.getProduct(), UTF8), URLEncoder.encode(vs.getVersion(), UTF8));
Cpe useCpe;
if (evBaseVerUpdate != null && "*".equals(vs.getUpdate())) {
try {
useCpe = cpeBuilder.part(vs.getPart()).wfVendor(vs.getWellFormedVendor())
.wfProduct(vs.getWellFormedProduct()).wfVersion(vs.getWellFormedVersion())
.wfEdition(vs.getWellFormedEdition()).wfLanguage(vs.getWellFormedLanguage())
.wfOther(vs.getWellFormedOther()).wfSwEdition(vs.getWellFormedSwEdition())
.update(evBaseVerUpdate).build();
} catch (CpeValidationException ex) {
LOGGER.debug("Error building cpe with update:" + evBaseVerUpdate, ex);
useCpe = vs;
}
} else {
useCpe = vs;
}
final IdentifierMatch match = new IdentifierMatch(useCpe, url, IdentifierConfidence.EXACT_MATCH, conf);
collected.add(match);
} else if (evBaseVer != null && evBaseVer.equals(dbVer)
&& (bestGuessConf == null || bestGuessConf.compareTo(conf) > 0)) {
bestGuessConf = conf;
bestGuess = dbVer;
bestGuessUpdate = evBaseVerUpdate;
bestGuessURL = String.format(NVD_SEARCH_URL, URLEncoder.encode(vs.getVendor(), UTF8),
URLEncoder.encode(vs.getProduct(), UTF8), URLEncoder.encode(vs.getVersion(), UTF8));
} else if (dbVerUpdate != null && evVer.getVersionParts().size() <= dbVerUpdate.getVersionParts().size()
&& evVer.matchesAtLeastThreeLevels(dbVerUpdate)) {
if (bestGuessConf == null || bestGuessConf.compareTo(conf) > 0) {
if (bestGuess.getVersionParts().size() < dbVer.getVersionParts().size()) {
bestGuess = dbVer;
bestGuessUpdate = evBaseVerUpdate;
bestGuessConf = conf;
}
}
}
}
if ((bestGuessConf == null || bestGuessConf.compareTo(conf) > 0)
&& bestGuess.getVersionParts().size() < evVer.getVersionParts().size()) {
bestGuess = evVer;
bestGuessUpdate = evBaseVerUpdate;
bestGuessConf = conf;
}
}
}
cpeBuilder.part(Part.APPLICATION).vendor(vendor).product(product);
final int idx = bestGuess.getVersionParts().size() - 1;
if (bestGuess.getVersionParts().get(idx)
.matches("^(v|release|final|snapshot|beta|alpha|u|rc|m|20\\d\\d).*$")) {
cpeBuilder.version(StringUtils.join(bestGuess.getVersionParts().subList(0, idx), "."));
//when written - no update versions in the NVD start with v### - they all strip the v off
if (bestGuess.getVersionParts().get(idx).matches("^v\\d.*$")) {
cpeBuilder.update(bestGuess.getVersionParts().get(idx).substring(1));
} else {
cpeBuilder.update(bestGuess.getVersionParts().get(idx));
}
} else {
cpeBuilder.version(bestGuess.toString());
if (bestGuessUpdate != null) {
cpeBuilder.update(bestGuessUpdate);
}
}
final Cpe guessCpe;
try {
guessCpe = cpeBuilder.build();
} catch (CpeValidationException ex) {
throw new AnalysisException(String.format("Unable to create a CPE for %s:%s:%s", vendor, product, bestGuess.toString()));
}
if (!"-".equals(guessCpe.getVersion())) {
String url = null;
if (bestGuessURL != null) {
url = bestGuessURL;
}
if (bestGuessConf == null) {
bestGuessConf = Confidence.LOW;
}
final IdentifierMatch match = new IdentifierMatch(guessCpe, url, IdentifierConfidence.BEST_GUESS, bestGuessConf);
collected.add(match);
}
boolean identifierAdded = false;
if (!collected.isEmpty()) {
final List<IdentifierMatch> items = new ArrayList<>(collected);
Collections.sort(items);
final IdentifierConfidence bestIdentifierQuality = items.get(0).getIdentifierConfidence();
final Confidence bestEvidenceQuality = items.get(0).getEvidenceConfidence();
boolean addedNonGuess = false;
final Confidence prevAddedConfidence = dependency.getVulnerableSoftwareIdentifiers().stream().map(id -> id.getConfidence())
.min(Comparator.comparing(Confidence::ordinal))
.orElse(Confidence.LOW);
for (IdentifierMatch m : items) {
if (bestIdentifierQuality.equals(m.getIdentifierConfidence())
&& bestEvidenceQuality.equals(m.getEvidenceConfidence())) {
final CpeIdentifier i = m.getIdentifier();
if (bestIdentifierQuality == IdentifierConfidence.BEST_GUESS) {
if (addedNonGuess) {
continue;
}
i.setConfidence(Confidence.LOW);
} else {
i.setConfidence(bestEvidenceQuality);
}
if (prevAddedConfidence.compareTo(i.getConfidence()) < 0) {
continue;
}
//TODO - while this gets the job down it is slow; consider refactoring
dependency.addVulnerableSoftwareIdentifier(i);
suppression.analyze(dependency, null);
if (dependency.getVulnerableSoftwareIdentifiers().contains(i)) {
identifierAdded = true;
if (!addedNonGuess && bestIdentifierQuality != IdentifierConfidence.BEST_GUESS) {
addedNonGuess = true;
}
}
}
}
}
return identifierAdded;
}
/**
* <p>
* Returns the setting key to determine if the analyzer is enabled.</p>
*
* @return the key for the analyzer's enabled property
*/
@Override
protected String getAnalyzerEnabledSettingKey() {
return Settings.KEYS.ANALYZER_CPE_ENABLED;
}
/**
* Filters the given list of CPE Entries (plus ecosystem) for the given
* dependencies ecosystem.
*
* @param ecosystem the dependencies ecosystem
* @param entries the CPE Entries (plus ecosystem)
* @return the filtered list of CPE entries
*/
private Set<Cpe> filterEcosystem(String ecosystem, Set<CpePlus> entries) {
if (entries == null || entries.isEmpty()) {
return null;
}
if (ecosystem != null) {
return entries.stream().filter(c -> c.getEcosystem() == null || c.getEcosystem().equals(ecosystem))
.map(c -> c.getCpe())
.collect(Collectors.toSet());
}
return entries.stream()
.map(c -> c.getCpe())
.collect(Collectors.toSet());
}
/**
* Add the given version to the CpeBuilder - this method attempts to parse
* out the update from the version and correctly set the value in the CPE.
*
* @param depVersion the version to add
* @param cpeBuilder a reference to the CPE Builder
*/
private void addVersionAndUpdate(DependencyVersion depVersion, final CpeBuilder cpeBuilder) {
final int idx = depVersion.getVersionParts().size() - 1;
if (idx > 0 && depVersion.getVersionParts().get(idx)
.matches("^(v|final|release|snapshot|r|b|beta|a|alpha|u|rc|sp|dev|revision|service|build|pre|p|patch|update|m|20\\d\\d).*$")) {
cpeBuilder.version(StringUtils.join(depVersion.getVersionParts().subList(0, idx), "."));
//when written - no update versions in the NVD start with v### - they all strip the v off
if (depVersion.getVersionParts().get(idx).matches("^v\\d.*$")) {
cpeBuilder.update(depVersion.getVersionParts().get(idx).substring(1));
} else {
cpeBuilder.update(depVersion.getVersionParts().get(idx));
}
} else {
cpeBuilder.version(depVersion.toString());
}
}
/**
* The confidence whether the identifier is an exact match, or a best guess.
*/
private enum IdentifierConfidence {
/**
* An exact match for the CPE.
*/
EXACT_MATCH,
/**
* A best guess for the CPE.
*/
BEST_GUESS,
/**
* The entire vendor/product group must be added (without a guess at
* version) because there is a CVE with a VS that only specifies
* vendor/product.
*/
BROAD_MATCH
}
/**
* A simple object to hold an identifier and carry information about the
* confidence in the identifier.
*/
private static class IdentifierMatch implements Comparable<IdentifierMatch> {
/**
* The confidence whether this is an exact match, or a best guess.
*/
private IdentifierConfidence identifierConfidence;
/**
* The CPE identifier.
*/
private CpeIdentifier identifier;
/**
* Constructs an IdentifierMatch.
*
* @param cpe the CPE value for the match
* @param url the URL of the identifier
* @param identifierConfidence the confidence in the identifier: best
* guess or exact match
* @param evidenceConfidence the confidence of the evidence used to find
* the identifier
*/
IdentifierMatch(Cpe cpe, String url, IdentifierConfidence identifierConfidence, Confidence evidenceConfidence) {
this.identifier = new CpeIdentifier(cpe, url, evidenceConfidence);
this.identifierConfidence = identifierConfidence;
}
//<editor-fold defaultstate="collapsed" desc="Property implementations: evidenceConfidence, confidence, identifier">
/**
* Get the value of evidenceConfidence
*
* @return the value of evidenceConfidence
*/
public Confidence getEvidenceConfidence() {
return this.identifier.getConfidence();
}
/**
* Set the value of evidenceConfidence
*
* @param evidenceConfidence new value of evidenceConfidence
*/
public void setEvidenceConfidence(Confidence evidenceConfidence) {
this.identifier.setConfidence(evidenceConfidence);
}
/**
* Get the value of confidence.
*
* @return the value of confidence
*/
public IdentifierConfidence getIdentifierConfidence() {
return identifierConfidence;
}
/**
* Set the value of confidence.
*
* @param confidence new value of confidence
*/
public void setIdentifierConfidence(IdentifierConfidence confidence) {
this.identifierConfidence = confidence;
}
/**
* Get the value of identifier.
*
* @return the value of identifier
*/
public CpeIdentifier getIdentifier() {
return identifier;
}
/**
* Set the value of identifier.
*
* @param identifier new value of identifier
*/
public void setIdentifier(CpeIdentifier identifier) {
this.identifier = identifier;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Standard implementations of toString, hashCode, and equals">
/**
* Standard toString() implementation.
*
* @return the string representation of the object
*/
@Override
public String toString() {
return "IdentifierMatch{ IdentifierConfidence=" + identifierConfidence + ", identifier=" + identifier + '}';
}
/**
* Standard hashCode() implementation.
*
* @return the hashCode
*/
@Override
public int hashCode() {
return new HashCodeBuilder(115, 303)
.append(identifierConfidence)
.append(identifier)
.toHashCode();
}
/**
* Standard equals implementation.
*
* @param obj the object to compare
* @return true if the objects are equal, otherwise false
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof IdentifierMatch)) {
return false;
}
if (this == obj) {
return true;
}
final IdentifierMatch other = (IdentifierMatch) obj;
return new EqualsBuilder()
.append(identifierConfidence, other.identifierConfidence)
.append(identifier, other.identifier)
.build();
}
//</editor-fold>
/**
* Standard implementation of compareTo that compares identifier
* confidence, evidence confidence, and then the identifier.
*
* @param o the IdentifierMatch to compare to
* @return the natural ordering of IdentifierMatch
*/
@Override
public int compareTo(@NotNull IdentifierMatch o) {
return new CompareToBuilder()
.append(identifierConfidence, o.identifierConfidence)
.append(identifier, o.identifier)
.toComparison();
}
}
/**
* Command line tool for querying the Lucene CPE Index.
*
* @param args not used
*/
public static void main(String[] args) {
final Settings props = new Settings();
try (Engine en = new Engine(Engine.Mode.EVIDENCE_PROCESSING, props)) {
en.openDatabase(false, false);
final CPEAnalyzer analyzer = new CPEAnalyzer();
analyzer.initialize(props);
analyzer.prepareAnalyzer(en);
LOGGER.error("test");
System.out.println("Memory index query for ODC");
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
while (true) {
final Map<String, MutableInt> vendor = new HashMap<>();
final Map<String, MutableInt> product = new HashMap<>();
System.out.print("Vendor: ");
String[] parts = br.readLine().split(" ");
for (String term : parts) {
final MutableInt count = vendor.get(term);
if (count == null) {
vendor.put(term, new MutableInt(0));
} else {
count.add(1);
}
}
System.out.print("Product: ");
parts = br.readLine().split(" ");
for (String term : parts) {
final MutableInt count = product.get(term);
if (count == null) {
product.put(term, new MutableInt(0));
} else {
count.add(1);
}
}
final List<IndexEntry> list = analyzer.searchCPE(vendor, product, new HashSet<>(), new HashSet<>(), "default");
if (list == null || list.isEmpty()) {
System.out.println("No results found");
} else {
list.forEach((e) -> System.out.println(String.format("%s:%s (%f)", e.getVendor(), e.getProduct(),
e.getSearchScore())));
}
System.out.println();
System.out.println();
}
}
} catch (InitializationException | IOException ex) {
System.err.println("Lucene ODC search tool failed:");
System.err.println(ex.getMessage());
}
}
/**
* Sets the reference to the CveDB.
*
* @param cveDb the CveDB
*/
protected void setCveDB(CveDB cveDb) {
this.cve = cveDb;
}
/**
* returns a reference to the CveDB.
*
* @return a reference to the CveDB
*/
protected CveDB getCveDB() {
return this.cve;
}
/**
* Sets the MemoryIndex.
*
* @param idx the memory index
*/
protected void setMemoryIndex(MemoryIndex idx) {
cpe = idx;
}
/**
* Returns the memory index.
*
* @return the memory index
*/
protected MemoryIndex getMemoryIndex() {
return cpe;
}
/**
* Sets the CPE Suppression Analyzer.
*
* @param suppression the CPE Suppression Analyzer
*/
protected void setCpeSuppressionAnalyzer(CpeSuppressionAnalyzer suppression) {
this.suppression = suppression;
}
}
| core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.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 com.fasterxml.jackson.core.util.VersionUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.mutable.MutableInt;
import org.apache.lucene.analysis.CharArraySet;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.jetbrains.annotations.NotNull;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.cpe.CpeMemoryIndex;
import org.owasp.dependencycheck.data.cpe.Fields;
import org.owasp.dependencycheck.data.cpe.IndexEntry;
import org.owasp.dependencycheck.data.cpe.IndexException;
import org.owasp.dependencycheck.data.cpe.MemoryIndex;
import org.owasp.dependencycheck.data.lucene.LuceneUtils;
import org.owasp.dependencycheck.data.lucene.SearchFieldAnalyzer;
import org.owasp.dependencycheck.data.nvd.ecosystem.Ecosystem;
import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.data.update.cpe.CpePlus;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
import org.owasp.dependencycheck.dependency.EvidenceType;
import org.owasp.dependencycheck.dependency.naming.CpeIdentifier;
import org.owasp.dependencycheck.dependency.naming.Identifier;
import org.owasp.dependencycheck.dependency.naming.PurlIdentifier;
import org.owasp.dependencycheck.exception.InitializationException;
import org.owasp.dependencycheck.utils.DependencyVersion;
import org.owasp.dependencycheck.utils.DependencyVersionUtil;
import org.owasp.dependencycheck.utils.Pair;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.springett.parsers.cpe.Cpe;
import us.springett.parsers.cpe.CpeBuilder;
import us.springett.parsers.cpe.exceptions.CpeValidationException;
import us.springett.parsers.cpe.values.Part;
/**
* CPEAnalyzer is a utility class that takes a project dependency and attempts
* to discern if there is an associated CPE. It uses the evidence contained
* within the dependency to search the Lucene index.
*
* @author Jeremy Long
*/
@ThreadSafe
public class CPEAnalyzer extends AbstractAnalyzer {
/**
* The Logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(CPEAnalyzer.class);
/**
* The weighting boost to give terms when constructing the Lucene query.
*/
private static final int WEIGHTING_BOOST = 1;
/**
* A string representation of a regular expression defining characters
* utilized within the CPE Names. Note, the :/ are included so URLs are
* passed into the Lucene query so that the specialized tokenizer can parse
* them.
*/
private static final String CLEANSE_CHARACTER_RX = "[^A-Za-z0-9 ._:/-]";
/**
* A string representation of a regular expression used to remove all but
* alpha characters.
*/
private static final String CLEANSE_NONALPHA_RX = "[^A-Za-z]*";
/**
* UTF-8 character set name.
*/
private static final String UTF8 = StandardCharsets.UTF_8.name();
/**
* The URL to search the NVD CVE data at NIST. This is used by calling:
* <pre>String.format(NVD_SEARCH_URL, vendor, product, version);</pre>
*/
public static final String NVD_SEARCH_URL = "https://nvd.nist.gov/vuln/search/results?form_type=Advanced&"
+ "results_type=overview&search_type=all&cpe_vendor=cpe%%3A%%2F%%3A%1$s&cpe_product=cpe%%3A%%2F%%3A%1$s%%3A%2$s&"
+ "cpe_version=cpe%%3A%%2F%%3A%1$s%%3A%2$s%%3A%3$s";
/**
* The URL to search the NVD CVE data at NIST. This is used by calling:
* <pre>String.format(NVD_SEARCH_URL, vendor, product);</pre>
*/
public static final String NVD_SEARCH_BROAD_URL = "https://nvd.nist.gov/vuln/search/results?form_type=Advanced&"
+ "results_type=overview&search_type=all&cpe_vendor=cpe%%3A%%2F%%3A%1$s&cpe_product=cpe%%3A%%2F%%3A%1$s%%3A%2$s";
/**
* The CPE in memory index.
*/
private MemoryIndex cpe;
/**
* The CVE Database.
*/
private CveDB cve;
/**
* The list of ecosystems to skip during analysis. These are skipped because
* there is generally a more accurate vulnerability analyzer in the
* pipeline.
*/
private List<String> skipEcosystems;
/**
* A reference to the ecosystem object; used to obtain the max query results
* for each ecosystem.
*/
private Ecosystem ecosystemTools;
/**
* A reference to the suppression analyzer; for timing reasons we need to
* test for suppressions immediately after identifying the match because a
* higher confidence match on a FP can mask a lower confidence, yet valid
* match.
*/
private CpeSuppressionAnalyzer suppression;
/**
* Returns the name of this analyzer.
*
* @return the name of this analyzer.
*/
@Override
public String getName() {
return "CPE Analyzer";
}
/**
* Returns the analysis phase that this analyzer should run in.
*
* @return the analysis phase that this analyzer should run in.
*/
@Override
public AnalysisPhase getAnalysisPhase() {
return AnalysisPhase.IDENTIFIER_ANALYSIS;
}
/**
* Creates the CPE Lucene Index.
*
* @param engine a reference to the dependency-check engine
* @throws InitializationException is thrown if there is an issue opening
* the index.
*/
@Override
public void prepareAnalyzer(Engine engine) throws InitializationException {
super.prepareAnalyzer(engine);
try {
this.open(engine.getDatabase());
} catch (IOException ex) {
LOGGER.debug("Exception initializing the Lucene Index", ex);
throw new InitializationException("An exception occurred initializing the Lucene Index", ex);
} catch (DatabaseException ex) {
LOGGER.debug("Exception accessing the database", ex);
throw new InitializationException("An exception occurred accessing the database", ex);
}
final String[] tmp = engine.getSettings().getArray(Settings.KEYS.ECOSYSTEM_SKIP_CPEANALYZER);
if (tmp == null) {
skipEcosystems = new ArrayList<>();
} else {
LOGGER.debug("Skipping CPE Analysis for {}", StringUtils.join(tmp, ","));
skipEcosystems = Arrays.asList(tmp);
}
ecosystemTools = new Ecosystem(engine.getSettings());
suppression = new CpeSuppressionAnalyzer();
suppression.initialize(engine.getSettings());
suppression.prepareAnalyzer(engine);
}
/**
* Opens the data source.
*
* @param cve a reference to the NVD CVE database
* @throws IOException when the Lucene directory to be queried does not
* exist or is corrupt.
* @throws DatabaseException when the database throws an exception. This
* usually occurs when the database is in use by another process.
*/
public void open(CveDB cve) throws IOException, DatabaseException {
this.cve = cve;
this.cpe = CpeMemoryIndex.getInstance();
try {
final long creationStart = System.currentTimeMillis();
cpe.open(cve.getVendorProductList(), this.getSettings());
final long creationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - creationStart);
LOGGER.info("Created CPE Index ({} seconds)", creationSeconds);
} catch (IndexException ex) {
LOGGER.debug("IndexException", ex);
throw new DatabaseException(ex);
}
}
/**
* Closes the data sources.
*/
@Override
public void closeAnalyzer() {
if (cpe != null) {
cpe.close();
cpe = null;
}
}
/**
* Searches the data store of CPE entries, trying to identify the CPE for
* the given dependency based on the evidence contained within. The
* dependency passed in is updated with any identified CPE values.
*
* @param dependency the dependency to search for CPE entries on
* @throws CorruptIndexException is thrown when the Lucene index is corrupt
* @throws IOException is thrown when an IOException occurs
* @throws ParseException is thrown when the Lucene query cannot be parsed
* @throws AnalysisException thrown if the suppression rules failed
*/
protected void determineCPE(Dependency dependency) throws CorruptIndexException, IOException, ParseException, AnalysisException {
boolean identifierAdded;
Set<String> majorVersions = dependency.getSoftwareIdentifiers()
.stream()
.filter(i -> i instanceof PurlIdentifier)
.map(i -> {
PurlIdentifier p = (PurlIdentifier) i;
DependencyVersion depVersion = DependencyVersionUtil.parseVersion(p.getVersion(), false);
if (depVersion != null) {
return depVersion.getVersionParts().get(0);
}
return null;
}).collect(Collectors.toSet());
final Map<String, MutableInt> vendors = new HashMap<>();
final Map<String, MutableInt> products = new HashMap<>();
final Set<Integer> previouslyFound = new HashSet<>();
for (Confidence confidence : Confidence.values()) {
collectTerms(vendors, dependency.getIterator(EvidenceType.VENDOR, confidence));
LOGGER.debug("vendor search: {}", vendors);
collectTerms(products, dependency.getIterator(EvidenceType.PRODUCT, confidence));
addMajorVersionToTerms(majorVersions, products);
LOGGER.debug("product search: {}", products);
if (!vendors.isEmpty() && !products.isEmpty()) {
final List<IndexEntry> entries = searchCPE(vendors, products,
dependency.getVendorWeightings(), dependency.getProductWeightings(),
dependency.getEcosystem());
if (entries == null) {
continue;
}
identifierAdded = false;
for (IndexEntry e : entries) {
if (previouslyFound.contains(e.getDocumentId()) /*|| (filter > 0 && e.getSearchScore() < filter)*/) {
continue;
}
previouslyFound.add(e.getDocumentId());
if (verifyEntry(e, dependency, majorVersions)) {
final String vendor = e.getVendor();
final String product = e.getProduct();
LOGGER.debug("identified vendor/product: {}/{}", vendor, product);
identifierAdded |= determineIdentifiers(dependency, vendor, product, confidence);
}
}
if (identifierAdded) {
break;
}
}
}
}
/**
* <p>
* Returns the text created by concatenating the text and the values from
* the EvidenceCollection (filtered for a specific confidence). This
* attempts to prevent duplicate terms from being added.</p>
* <p>
* Note, if the evidence is longer then 1000 characters it will be
* truncated.</p>
*
* @param terms the collection of terms
* @param evidence an iterable set of evidence to concatenate
*/
@SuppressWarnings("null")
protected void collectTerms(Map<String, MutableInt> terms, Iterable<Evidence> evidence) {
for (Evidence e : evidence) {
String value = cleanseText(e.getValue());
if (StringUtils.isBlank(value)) {
continue;
}
if (value.length() > 1000) {
boolean trimmed = false;
int pos = value.lastIndexOf(" ", 1000);
if (pos > 0) {
value = value.substring(0, pos);
trimmed = true;
} else {
pos = value.lastIndexOf(".", 1000);
}
if (!trimmed) {
if (pos > 0) {
value = value.substring(0, pos);
trimmed = true;
} else {
pos = value.lastIndexOf("-", 1000);
}
}
if (!trimmed) {
if (pos > 0) {
value = value.substring(0, pos);
trimmed = true;
} else {
pos = value.lastIndexOf("_", 1000);
}
}
if (!trimmed) {
if (pos > 0) {
value = value.substring(0, pos);
trimmed = true;
} else {
pos = value.lastIndexOf("/", 1000);
}
}
if (!trimmed && pos > 0) {
value = value.substring(0, pos);
trimmed = true;
}
if (!trimmed) {
value = value.substring(0, 1000);
}
}
addTerm(terms, value);
}
}
private void addMajorVersionToTerms(Set<String> majorVersions, Map<String, MutableInt> products) {
Map<String, MutableInt> temp = new HashMap<>();
products.entrySet().stream()
.filter(term -> term.getKey() != null)
.forEach(term -> {
majorVersions.stream()
.filter(version -> (!term.getKey().endsWith(version)
&& !Character.isDigit(term.getKey().charAt(term.getKey().length() - 1))
&& !products.containsKey(term.getKey() + version)))
.forEach(version -> {
addTerm(temp, term.getKey() + version);
});
});
products.putAll(temp);
}
/**
* Adds a term to the map of terms.
*
* @param terms the map of terms
* @param value the value of the term to add
*/
private void addTerm(Map<String, MutableInt> terms, String value) {
final MutableInt count = terms.get(value);
if (count == null) {
terms.put(value, new MutableInt(1));
} else {
count.add(1);
}
}
/**
* <p>
* Searches the Lucene CPE index to identify possible CPE entries associated
* with the supplied vendor, product, and version.</p>
*
* <p>
* If either the vendorWeightings or productWeightings lists have been
* populated this data is used to add weighting factors to the search.</p>
*
* @param vendor the text used to search the vendor field
* @param product the text used to search the product field
* @param vendorWeightings a list of strings to use to add weighting factors
* to the vendor field
* @param productWeightings Adds a list of strings that will be used to add
* weighting factors to the product search
* @param ecosystem the dependency's ecosystem
* @return a list of possible CPE values
*/
protected List<IndexEntry> searchCPE(Map<String, MutableInt> vendor, Map<String, MutableInt> product,
Set<String> vendorWeightings, Set<String> productWeightings, String ecosystem) {
final int maxQueryResults = ecosystemTools.getLuceneMaxQueryLimitFor(ecosystem);
final List<IndexEntry> ret = new ArrayList<>(maxQueryResults);
final String searchString = buildSearch(vendor, product, vendorWeightings, productWeightings);
if (searchString == null) {
return ret;
}
try {
final Query query = cpe.parseQuery(searchString);
final TopDocs docs = cpe.search(query, maxQueryResults);
for (ScoreDoc d : docs.scoreDocs) {
//if (d.score >= minLuceneScore) {
final Document doc = cpe.getDocument(d.doc);
final IndexEntry entry = new IndexEntry();
entry.setDocumentId(d.doc);
entry.setVendor(doc.get(Fields.VENDOR));
entry.setProduct(doc.get(Fields.PRODUCT));
entry.setSearchScore(d.score);
// LOGGER.error("Explanation: ---------------------");
// LOGGER.error("Explanation: " + entry.getVendor() + " " + entry.getProduct() + " " + entry.getSearchScore());
// LOGGER.error("Explanation: " + searchString);
// LOGGER.error("Explanation: " + cpe.explain(query, d.doc));
if (!ret.contains(entry)) {
ret.add(entry);
}
//}
}
return ret;
} catch (ParseException ex) {
LOGGER.warn("An error occurred querying the CPE data. See the log for more details.");
LOGGER.info("Unable to parse: {}", searchString, ex);
} catch (IndexException ex) {
LOGGER.warn("An error occurred resetting the CPE index searcher. See the log for more details.");
LOGGER.info("Unable to reset the search analyzer", ex);
} catch (IOException ex) {
LOGGER.warn("An error occurred reading CPE data. See the log for more details.");
LOGGER.info("IO Error with search string: {}", searchString, ex);
}
return null;
}
/**
* <p>
* Builds a Lucene search string by properly escaping data and constructing
* a valid search query.</p>
*
* <p>
* If either the possibleVendor or possibleProducts lists have been
* populated this data is used to add weighting factors to the search string
* generated.</p>
*
* @param vendor text to search the vendor field
* @param product text to search the product field
* @param vendorWeighting a list of strings to apply to the vendor to boost
* the terms weight
* @param productWeightings a list of strings to apply to the product to
* boost the terms weight
* @return the Lucene query
*/
protected String buildSearch(Map<String, MutableInt> vendor, Map<String, MutableInt> product,
Set<String> vendorWeighting, Set<String> productWeightings) {
final StringBuilder sb = new StringBuilder();
if (!appendWeightedSearch(sb, Fields.PRODUCT, product, productWeightings)) {
return null;
}
sb.append(" AND ");
if (!appendWeightedSearch(sb, Fields.VENDOR, vendor, vendorWeighting)) {
return null;
}
return sb.toString();
}
/**
* This method constructs a Lucene query for a given field. The searchText
* is split into separate words and if the word is within the list of
* weighted words then an additional weighting is applied to the term as it
* is appended into the query.
*
* @param sb a StringBuilder that the query text will be appended to.
* @param field the field within the Lucene index that the query is
* searching.
* @param terms text used to construct the query.
* @param weightedText a list of terms that will be considered higher
* importance when searching.
* @return if the append was successful.
*/
@SuppressWarnings("StringSplitter")
private boolean appendWeightedSearch(StringBuilder sb, String field, Map<String, MutableInt> terms, Set<String> weightedText) {
if (terms.isEmpty()) {
return false;
}
sb.append(field).append(":(");
boolean addSpace = false;
boolean addedTerm = false;
for (Map.Entry<String, MutableInt> entry : terms.entrySet()) {
final StringBuilder boostedTerms = new StringBuilder();
final int weighting = entry.getValue().intValue();
final String[] text = entry.getKey().split(" ");
for (String word : text) {
if (word.isEmpty()) {
continue;
}
if (addSpace) {
sb.append(" ");
} else {
addSpace = true;
}
addedTerm = true;
if (LuceneUtils.isKeyword(word)) {
sb.append("\"");
LuceneUtils.appendEscapedLuceneQuery(sb, word);
sb.append("\"");
} else {
LuceneUtils.appendEscapedLuceneQuery(sb, word);
}
final String boostTerm = findBoostTerm(word, weightedText);
//The weighting is on a full phrase rather then at a term level for vendor or products
//TODO - should the weighting be at a "word" level as opposed to phrase level? Or combined word and phrase?
//remember the reason we are counting the frequency of "phrases" as opposed to terms is that
//we need to keep the correct sequence of terms from the evidence so the term concatenating analyzer
//works correctly and will causes searches to take spring framework and produce: spring springframework framework
if (boostTerm != null) {
sb.append("^").append(weighting + WEIGHTING_BOOST);
if (!boostTerm.equals(word)) {
boostedTerms.append(" ").append(boostTerm).append("^").append(weighting + WEIGHTING_BOOST);
}
} else if (weighting > 1) {
sb.append("^").append(weighting);
}
}
if (boostedTerms.length() > 0) {
sb.append(boostedTerms);
}
}
sb.append(")");
return addedTerm;
}
/**
* Removes characters from the input text that are not used within the CPE
* index.
*
* @param text is the text to remove the characters from.
* @return the text having removed some characters.
*/
private String cleanseText(String text) {
return text.replaceAll(CLEANSE_CHARACTER_RX, " ");
}
/**
* Searches the collection of boost terms for the given term. The elements
* are case insensitive matched using only the alpha-numeric contents of the
* terms; all other characters are removed.
*
* @param term the term to search for
* @param boost the collection of boost terms
* @return the value identified
*/
private String findBoostTerm(String term, Set<String> boost) {
for (String entry : boost) {
if (equalsIgnoreCaseAndNonAlpha(term, entry)) {
return entry;
}
}
return null;
}
/**
* Compares two strings after lower casing them and removing the non-alpha
* characters.
*
* @param l string one to compare.
* @param r string two to compare.
* @return whether or not the two strings are similar.
*/
private boolean equalsIgnoreCaseAndNonAlpha(String l, String r) {
if (l == null || r == null) {
return false;
}
final String left = l.replaceAll(CLEANSE_NONALPHA_RX, "");
final String right = r.replaceAll(CLEANSE_NONALPHA_RX, "");
return left.equalsIgnoreCase(right);
}
/**
* Ensures that the CPE Identified matches the dependency. This validates
* that the product, vendor, and version information for the CPE are
* contained within the dependencies evidence.
*
* @param entry a CPE entry.
* @param dependency the dependency that the CPE entries could be for.
* @return whether or not the entry is valid.
*/
private boolean verifyEntry(final IndexEntry entry, final Dependency dependency,
final Set<String> majorVersions) {
boolean isValid = false;
//TODO - does this nullify some of the fuzzy matching that happens in the lucene search?
// for instance CPE some-component and in the evidence we have SomeComponent.
//TODO - should this have a package manager only flag instead of just looking for NPM
if (Ecosystem.NODEJS.equals(dependency.getEcosystem())) {
for (Identifier i : dependency.getSoftwareIdentifiers()) {
if (i instanceof PurlIdentifier) {
final PurlIdentifier p = (PurlIdentifier) i;
if (cleanPackageName(p.getName()).equals(cleanPackageName(entry.getProduct()))) {
isValid = true;
}
}
}
} else if (collectionContainsString(dependency.getEvidence(EvidenceType.VENDOR), entry.getVendor())) {
if (collectionContainsString(dependency.getEvidence(EvidenceType.PRODUCT), entry.getProduct())) {
isValid = true;
} else {
isValid = majorVersions.stream().filter(version->entry.getProduct().endsWith(version) && entry.getProduct().length()>version.length())
.anyMatch(version ->
collectionContainsString(dependency.getEvidence(EvidenceType.PRODUCT), entry.getProduct().substring(0, entry.getProduct().length()-version.length()))
);
}
}
return isValid;
}
/**
* Only returns alpha numeric characters contained in a given package name.
*
* @param name the package name to cleanse
* @return the cleansed packaage name
*/
private String cleanPackageName(String name) {
if (name == null) {
return "";
}
return name.replaceAll("[^a-zA-Z0-9]+", "");
}
/**
* Used to determine if the EvidenceCollection contains a specific string.
*
* @param evidence an of evidence object to check
* @param text the text to search for
* @return whether or not the EvidenceCollection contains the string
*/
@SuppressWarnings("StringSplitter")
private boolean collectionContainsString(Set<Evidence> evidence, String text) {
//TODO - likely need to change the split... not sure if this will work for CPE with special chars
if (text == null) {
return false;
}
// Check if we have an exact match
final String textLC = text.toLowerCase();
for (Evidence e : evidence) {
if (e.getValue().toLowerCase().equals(textLC)) {
return true;
}
}
final String[] words = text.split("[\\s_-]+");
final List<String> list = new ArrayList<>();
String tempWord = null;
final CharArraySet stopWords = SearchFieldAnalyzer.getStopWords();
for (String word : words) {
/*
single letter words should be concatenated with the next word.
so { "m", "core", "sample" } -> { "mcore", "sample" }
*/
if (tempWord != null) {
list.add(tempWord + word);
tempWord = null;
} else if (word.length() <= 2) {
tempWord = word;
} else {
if (stopWords.contains(word)) {
continue;
}
list.add(word);
}
}
if (tempWord != null) {
if (!list.isEmpty()) {
final String tmp = list.get(list.size() - 1) + tempWord;
list.add(tmp);
} else {
list.add(tempWord);
}
}
if (list.isEmpty()) {
return false;
}
boolean isValid = true;
// Prepare the evidence values, e.g. remove the characters we used for splitting
final List<String> evidenceValues = new ArrayList<>(evidence.size());
evidence.forEach((e) -> {
evidenceValues.add(e.getValue().toLowerCase().replaceAll("[\\s_-]+", ""));
});
for (String word : list) {
word = word.toLowerCase();
boolean found = false;
for (String e : evidenceValues) {
if (e.contains(word)) {
if ("http".equals(word) && e.contains("http:")) {
continue;
}
found = true;
break;
}
}
isValid &= found;
// if (!isValid) {
// break;
// }
}
return isValid;
}
/**
* Analyzes a dependency and attempts to determine if there are any CPE
* identifiers for this dependency.
*
* @param dependency The Dependency to analyze.
* @param engine The analysis engine
* @throws AnalysisException is thrown if there is an issue analyzing the
* dependency.
*/
@Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
if (skipEcosystems.contains(dependency.getEcosystem())) {
return;
}
try {
determineCPE(dependency);
} catch (CorruptIndexException ex) {
throw new AnalysisException("CPE Index is corrupt.", ex);
} catch (IOException ex) {
throw new AnalysisException("Failure opening the CPE Index.", ex);
} catch (ParseException ex) {
throw new AnalysisException("Unable to parse the generated Lucene query for this dependency.", ex);
}
}
/**
* Retrieves a list of CPE values from the CveDB based on the vendor and
* product passed in. The list is then validated to find only CPEs that are
* valid for the given dependency. It is possible that the CPE identified is
* a best effort "guess" based on the vendor, product, and version
* information.
*
* @param dependency the Dependency being analyzed
* @param vendor the vendor for the CPE being analyzed
* @param product the product for the CPE being analyzed
* @param currentConfidence the current confidence being used during
* analysis
* @return <code>true</code> if an identifier was added to the dependency;
* otherwise <code>false</code>
* @throws UnsupportedEncodingException is thrown if UTF-8 is not supported
* @throws AnalysisException thrown if the suppression rules failed
*/
@SuppressWarnings("StringSplitter")
protected boolean determineIdentifiers(Dependency dependency, String vendor, String product,
Confidence currentConfidence) throws UnsupportedEncodingException, AnalysisException {
final CpeBuilder cpeBuilder = new CpeBuilder();
final Set<CpePlus> cpePlusEntries = cve.getCPEs(vendor, product);
final Set<Cpe> cpes = filterEcosystem(dependency.getEcosystem(), cpePlusEntries);
if (cpes == null || cpes.isEmpty()) {
return false;
}
DependencyVersion bestGuess;
if ("Golang".equals(dependency.getEcosystem()) && dependency.getVersion() == null) {
bestGuess = new DependencyVersion("*");
} else {
bestGuess = new DependencyVersion("-");
}
String bestGuessUpdate = null;
Confidence bestGuessConf = null;
String bestGuessURL = null;
final Set<IdentifierMatch> collected = new HashSet<>();
if (dependency.getVersion() != null && !dependency.getVersion().isEmpty()) {
//we shouldn't always use the dependency version - in some cases this causes FP
boolean useDependencyVersion = true;
final CharArraySet stopWords = SearchFieldAnalyzer.getStopWords();
if (dependency.getName() != null && !dependency.getName().isEmpty()) {
final String name = dependency.getName();
for (String word : product.split("[^a-zA-Z0-9]")) {
useDependencyVersion &= name.contains(word) || stopWords.contains(word);
}
}
if (useDependencyVersion) {
//TODO - we need to filter this so that we only use this if something in the
//dependency.getName() matches the vendor/product in some way
final DependencyVersion depVersion = new DependencyVersion(dependency.getVersion());
if (depVersion.getVersionParts().size() > 0) {
cpeBuilder.part(Part.APPLICATION).vendor(vendor).product(product);
addVersionAndUpdate(depVersion, cpeBuilder);
try {
final Cpe depCpe = cpeBuilder.build();
final String url = String.format(NVD_SEARCH_URL, URLEncoder.encode(vendor, UTF8),
URLEncoder.encode(product, UTF8), URLEncoder.encode(depCpe.getVersion(), UTF8));
final IdentifierMatch match = new IdentifierMatch(depCpe, url, IdentifierConfidence.EXACT_MATCH, currentConfidence);
collected.add(match);
} catch (CpeValidationException ex) {
throw new AnalysisException(String.format("Unable to create a CPE for %s:%s:%s", vendor, product, bestGuess.toString()));
}
}
}
}
//TODO the following algorithm incorrectly identifies things as a lower version
// if there lower confidence evidence when the current (highest) version number
// is newer then anything in the NVD.
for (Confidence conf : Confidence.values()) {
for (Evidence evidence : dependency.getIterator(EvidenceType.VERSION, conf)) {
final DependencyVersion evVer = DependencyVersionUtil.parseVersion(evidence.getValue(), true);
if (evVer == null) {
continue;
}
DependencyVersion evBaseVer = null;
String evBaseVerUpdate = null;
final int idx = evVer.getVersionParts().size() - 1;
if (evVer.getVersionParts().get(idx)
.matches("^(v|release|final|snapshot|beta|alpha|u|rc|m|20\\d\\d).*$")) {
//store the update version
final String checkUpdate = evVer.getVersionParts().get(idx);
if (checkUpdate.matches("^(v|release|final|snapshot|beta|alpha|u|rc|m|20\\d\\d).*$")) {
evBaseVerUpdate = checkUpdate;
evBaseVer = new DependencyVersion();
evBaseVer.setVersionParts(evVer.getVersionParts().subList(0, idx));
}
}
//TODO - review and update for new JSON data
for (Cpe vs : cpes) {
final DependencyVersion dbVer = DependencyVersionUtil.parseVersion(vs.getVersion());
DependencyVersion dbVerUpdate = dbVer;
if (vs.getUpdate() != null && !vs.getUpdate().isEmpty() && !vs.getUpdate().startsWith("*") && !vs.getUpdate().startsWith("-")) {
dbVerUpdate = DependencyVersionUtil.parseVersion(vs.getVersion() + '.' + vs.getUpdate(), true);
}
if (dbVer == null) { //special case, no version specified - everything is vulnerable
final String url = String.format(NVD_SEARCH_BROAD_URL, URLEncoder.encode(vs.getVendor(), UTF8),
URLEncoder.encode(vs.getProduct(), UTF8));
final IdentifierMatch match = new IdentifierMatch(vs, url, IdentifierConfidence.BROAD_MATCH, conf);
collected.add(match);
} else if (evVer.equals(dbVer)) { //yeah! exact match
final String url = String.format(NVD_SEARCH_URL, URLEncoder.encode(vs.getVendor(), UTF8),
URLEncoder.encode(vs.getProduct(), UTF8), URLEncoder.encode(vs.getVersion(), UTF8));
Cpe useCpe;
if (evBaseVerUpdate != null && "*".equals(vs.getUpdate())) {
try {
useCpe = cpeBuilder.part(vs.getPart()).wfVendor(vs.getWellFormedVendor())
.wfProduct(vs.getWellFormedProduct()).wfVersion(vs.getWellFormedVersion())
.wfEdition(vs.getWellFormedEdition()).wfLanguage(vs.getWellFormedLanguage())
.wfOther(vs.getWellFormedOther()).wfSwEdition(vs.getWellFormedSwEdition())
.update(evBaseVerUpdate).build();
} catch (CpeValidationException ex) {
LOGGER.debug("Error building cpe with update:" + evBaseVerUpdate, ex);
useCpe = vs;
}
} else {
useCpe = vs;
}
final IdentifierMatch match = new IdentifierMatch(useCpe, url, IdentifierConfidence.EXACT_MATCH, conf);
collected.add(match);
} else if (evBaseVer != null && evBaseVer.equals(dbVer)
&& (bestGuessConf == null || bestGuessConf.compareTo(conf) > 0)) {
bestGuessConf = conf;
bestGuess = dbVer;
bestGuessUpdate = evBaseVerUpdate;
bestGuessURL = String.format(NVD_SEARCH_URL, URLEncoder.encode(vs.getVendor(), UTF8),
URLEncoder.encode(vs.getProduct(), UTF8), URLEncoder.encode(vs.getVersion(), UTF8));
} else if (dbVerUpdate != null && evVer.getVersionParts().size() <= dbVerUpdate.getVersionParts().size()
&& evVer.matchesAtLeastThreeLevels(dbVerUpdate)) {
if (bestGuessConf == null || bestGuessConf.compareTo(conf) > 0) {
if (bestGuess.getVersionParts().size() < dbVer.getVersionParts().size()) {
bestGuess = dbVer;
bestGuessUpdate = evBaseVerUpdate;
bestGuessConf = conf;
}
}
}
}
if ((bestGuessConf == null || bestGuessConf.compareTo(conf) > 0)
&& bestGuess.getVersionParts().size() < evVer.getVersionParts().size()) {
bestGuess = evVer;
bestGuessUpdate = evBaseVerUpdate;
bestGuessConf = conf;
}
}
}
cpeBuilder.part(Part.APPLICATION).vendor(vendor).product(product);
final int idx = bestGuess.getVersionParts().size() - 1;
if (bestGuess.getVersionParts().get(idx)
.matches("^(v|release|final|snapshot|beta|alpha|u|rc|m|20\\d\\d).*$")) {
cpeBuilder.version(StringUtils.join(bestGuess.getVersionParts().subList(0, idx), "."));
//when written - no update versions in the NVD start with v### - they all strip the v off
if (bestGuess.getVersionParts().get(idx).matches("^v\\d.*$")) {
cpeBuilder.update(bestGuess.getVersionParts().get(idx).substring(1));
} else {
cpeBuilder.update(bestGuess.getVersionParts().get(idx));
}
} else {
cpeBuilder.version(bestGuess.toString());
if (bestGuessUpdate != null) {
cpeBuilder.update(bestGuessUpdate);
}
}
final Cpe guessCpe;
try {
guessCpe = cpeBuilder.build();
} catch (CpeValidationException ex) {
throw new AnalysisException(String.format("Unable to create a CPE for %s:%s:%s", vendor, product, bestGuess.toString()));
}
if (!"-".equals(guessCpe.getVersion())) {
String url = null;
if (bestGuessURL != null) {
url = bestGuessURL;
}
if (bestGuessConf == null) {
bestGuessConf = Confidence.LOW;
}
final IdentifierMatch match = new IdentifierMatch(guessCpe, url, IdentifierConfidence.BEST_GUESS, bestGuessConf);
collected.add(match);
}
boolean identifierAdded = false;
if (!collected.isEmpty()) {
final List<IdentifierMatch> items = new ArrayList<>(collected);
Collections.sort(items);
final IdentifierConfidence bestIdentifierQuality = items.get(0).getIdentifierConfidence();
final Confidence bestEvidenceQuality = items.get(0).getEvidenceConfidence();
boolean addedNonGuess = false;
final Confidence prevAddedConfidence = dependency.getVulnerableSoftwareIdentifiers().stream().map(id -> id.getConfidence())
.min(Comparator.comparing(Confidence::ordinal))
.orElse(Confidence.LOW);
for (IdentifierMatch m : items) {
if (bestIdentifierQuality.equals(m.getIdentifierConfidence())
&& bestEvidenceQuality.equals(m.getEvidenceConfidence())) {
final CpeIdentifier i = m.getIdentifier();
if (bestIdentifierQuality == IdentifierConfidence.BEST_GUESS) {
if (addedNonGuess) {
continue;
}
i.setConfidence(Confidence.LOW);
} else {
i.setConfidence(bestEvidenceQuality);
}
if (prevAddedConfidence.compareTo(i.getConfidence()) < 0) {
continue;
}
//TODO - while this gets the job down it is slow; consider refactoring
dependency.addVulnerableSoftwareIdentifier(i);
suppression.analyze(dependency, null);
if (dependency.getVulnerableSoftwareIdentifiers().contains(i)) {
identifierAdded = true;
if (!addedNonGuess && bestIdentifierQuality != IdentifierConfidence.BEST_GUESS) {
addedNonGuess = true;
}
}
}
}
}
return identifierAdded;
}
/**
* <p>
* Returns the setting key to determine if the analyzer is enabled.</p>
*
* @return the key for the analyzer's enabled property
*/
@Override
protected String getAnalyzerEnabledSettingKey() {
return Settings.KEYS.ANALYZER_CPE_ENABLED;
}
/**
* Filters the given list of CPE Entries (plus ecosystem) for the given
* dependencies ecosystem.
*
* @param ecosystem the dependencies ecosystem
* @param entries the CPE Entries (plus ecosystem)
* @return the filtered list of CPE entries
*/
private Set<Cpe> filterEcosystem(String ecosystem, Set<CpePlus> entries) {
if (entries == null || entries.isEmpty()) {
return null;
}
if (ecosystem != null) {
return entries.stream().filter(c -> c.getEcosystem() == null || c.getEcosystem().equals(ecosystem))
.map(c -> c.getCpe())
.collect(Collectors.toSet());
}
return entries.stream()
.map(c -> c.getCpe())
.collect(Collectors.toSet());
}
/**
* Add the given version to the CpeBuilder - this method attempts to parse
* out the update from the version and correctly set the value in the CPE.
*
* @param depVersion the version to add
* @param cpeBuilder a reference to the CPE Builder
*/
private void addVersionAndUpdate(DependencyVersion depVersion, final CpeBuilder cpeBuilder) {
final int idx = depVersion.getVersionParts().size() - 1;
if (idx > 0 && depVersion.getVersionParts().get(idx)
.matches("^(v|final|release|snapshot|r|b|beta|a|alpha|u|rc|sp|dev|revision|service|build|pre|p|patch|update|m|20\\d\\d).*$")) {
cpeBuilder.version(StringUtils.join(depVersion.getVersionParts().subList(0, idx), "."));
//when written - no update versions in the NVD start with v### - they all strip the v off
if (depVersion.getVersionParts().get(idx).matches("^v\\d.*$")) {
cpeBuilder.update(depVersion.getVersionParts().get(idx).substring(1));
} else {
cpeBuilder.update(depVersion.getVersionParts().get(idx));
}
} else {
cpeBuilder.version(depVersion.toString());
}
}
/**
* The confidence whether the identifier is an exact match, or a best guess.
*/
private enum IdentifierConfidence {
/**
* An exact match for the CPE.
*/
EXACT_MATCH,
/**
* A best guess for the CPE.
*/
BEST_GUESS,
/**
* The entire vendor/product group must be added (without a guess at
* version) because there is a CVE with a VS that only specifies
* vendor/product.
*/
BROAD_MATCH
}
/**
* A simple object to hold an identifier and carry information about the
* confidence in the identifier.
*/
private static class IdentifierMatch implements Comparable<IdentifierMatch> {
/**
* The confidence whether this is an exact match, or a best guess.
*/
private IdentifierConfidence identifierConfidence;
/**
* The CPE identifier.
*/
private CpeIdentifier identifier;
/**
* Constructs an IdentifierMatch.
*
* @param cpe the CPE value for the match
* @param url the URL of the identifier
* @param identifierConfidence the confidence in the identifier: best
* guess or exact match
* @param evidenceConfidence the confidence of the evidence used to find
* the identifier
*/
IdentifierMatch(Cpe cpe, String url, IdentifierConfidence identifierConfidence, Confidence evidenceConfidence) {
this.identifier = new CpeIdentifier(cpe, url, evidenceConfidence);
this.identifierConfidence = identifierConfidence;
}
//<editor-fold defaultstate="collapsed" desc="Property implementations: evidenceConfidence, confidence, identifier">
/**
* Get the value of evidenceConfidence
*
* @return the value of evidenceConfidence
*/
public Confidence getEvidenceConfidence() {
return this.identifier.getConfidence();
}
/**
* Set the value of evidenceConfidence
*
* @param evidenceConfidence new value of evidenceConfidence
*/
public void setEvidenceConfidence(Confidence evidenceConfidence) {
this.identifier.setConfidence(evidenceConfidence);
}
/**
* Get the value of confidence.
*
* @return the value of confidence
*/
public IdentifierConfidence getIdentifierConfidence() {
return identifierConfidence;
}
/**
* Set the value of confidence.
*
* @param confidence new value of confidence
*/
public void setIdentifierConfidence(IdentifierConfidence confidence) {
this.identifierConfidence = confidence;
}
/**
* Get the value of identifier.
*
* @return the value of identifier
*/
public CpeIdentifier getIdentifier() {
return identifier;
}
/**
* Set the value of identifier.
*
* @param identifier new value of identifier
*/
public void setIdentifier(CpeIdentifier identifier) {
this.identifier = identifier;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Standard implementations of toString, hashCode, and equals">
/**
* Standard toString() implementation.
*
* @return the string representation of the object
*/
@Override
public String toString() {
return "IdentifierMatch{ IdentifierConfidence=" + identifierConfidence + ", identifier=" + identifier + '}';
}
/**
* Standard hashCode() implementation.
*
* @return the hashCode
*/
@Override
public int hashCode() {
return new HashCodeBuilder(115, 303)
.append(identifierConfidence)
.append(identifier)
.toHashCode();
}
/**
* Standard equals implementation.
*
* @param obj the object to compare
* @return true if the objects are equal, otherwise false
*/
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof IdentifierMatch)) {
return false;
}
if (this == obj) {
return true;
}
final IdentifierMatch other = (IdentifierMatch) obj;
return new EqualsBuilder()
.append(identifierConfidence, other.identifierConfidence)
.append(identifier, other.identifier)
.build();
}
//</editor-fold>
/**
* Standard implementation of compareTo that compares identifier
* confidence, evidence confidence, and then the identifier.
*
* @param o the IdentifierMatch to compare to
* @return the natural ordering of IdentifierMatch
*/
@Override
public int compareTo(@NotNull IdentifierMatch o) {
return new CompareToBuilder()
.append(identifierConfidence, o.identifierConfidence)
.append(identifier, o.identifier)
.toComparison();
}
}
/**
* Command line tool for querying the Lucene CPE Index.
*
* @param args not used
*/
public static void main(String[] args) {
final Settings props = new Settings();
try (Engine en = new Engine(Engine.Mode.EVIDENCE_PROCESSING, props)) {
en.openDatabase(false, false);
final CPEAnalyzer analyzer = new CPEAnalyzer();
analyzer.initialize(props);
analyzer.prepareAnalyzer(en);
LOGGER.error("test");
System.out.println("Memory index query for ODC");
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) {
while (true) {
final Map<String, MutableInt> vendor = new HashMap<>();
final Map<String, MutableInt> product = new HashMap<>();
System.out.print("Vendor: ");
String[] parts = br.readLine().split(" ");
for (String term : parts) {
final MutableInt count = vendor.get(term);
if (count == null) {
vendor.put(term, new MutableInt(0));
} else {
count.add(1);
}
}
System.out.print("Product: ");
parts = br.readLine().split(" ");
for (String term : parts) {
final MutableInt count = product.get(term);
if (count == null) {
product.put(term, new MutableInt(0));
} else {
count.add(1);
}
}
final List<IndexEntry> list = analyzer.searchCPE(vendor, product, new HashSet<>(), new HashSet<>(), "default");
if (list == null || list.isEmpty()) {
System.out.println("No results found");
} else {
list.forEach((e) -> System.out.println(String.format("%s:%s (%f)", e.getVendor(), e.getProduct(),
e.getSearchScore())));
}
System.out.println();
System.out.println();
}
}
} catch (InitializationException | IOException ex) {
System.err.println("Lucene ODC search tool failed:");
System.err.println(ex.getMessage());
}
}
/**
* Sets the reference to the CveDB.
*
* @param cveDb the CveDB
*/
protected void setCveDB(CveDB cveDb) {
this.cve = cveDb;
}
/**
* returns a reference to the CveDB.
*
* @return a reference to the CveDB
*/
protected CveDB getCveDB() {
return this.cve;
}
/**
* Sets the MemoryIndex.
*
* @param idx the memory index
*/
protected void setMemoryIndex(MemoryIndex idx) {
cpe = idx;
}
/**
* Returns the memory index.
*
* @return the memory index
*/
protected MemoryIndex getMemoryIndex() {
return cpe;
}
/**
* Sets the CPE Suppression Analyzer.
*
* @param suppression the CPE Suppression Analyzer
*/
protected void setCpeSuppressionAnalyzer(CpeSuppressionAnalyzer suppression) {
this.suppression = suppression;
}
}
| fix NPE per #3212 and #3214
| core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java | fix NPE per #3212 and #3214 | <ide><path>ore/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java
<ide> .filter(term -> term.getKey() != null)
<ide> .forEach(term -> {
<ide> majorVersions.stream()
<del> .filter(version -> (!term.getKey().endsWith(version)
<add> .filter(version -> version != null
<add> && (!term.getKey().endsWith(version)
<ide> && !Character.isDigit(term.getKey().charAt(term.getKey().length() - 1))
<ide> && !products.containsKey(term.getKey() + version)))
<ide> .forEach(version -> {
<ide> * @param dependency the dependency that the CPE entries could be for.
<ide> * @return whether or not the entry is valid.
<ide> */
<del> private boolean verifyEntry(final IndexEntry entry, final Dependency dependency,
<add> private boolean verifyEntry(final IndexEntry entry, final Dependency dependency,
<ide> final Set<String> majorVersions) {
<ide> boolean isValid = false;
<ide> //TODO - does this nullify some of the fuzzy matching that happens in the lucene search?
<ide> if (collectionContainsString(dependency.getEvidence(EvidenceType.PRODUCT), entry.getProduct())) {
<ide> isValid = true;
<ide> } else {
<del> isValid = majorVersions.stream().filter(version->entry.getProduct().endsWith(version) && entry.getProduct().length()>version.length())
<del> .anyMatch(version ->
<del> collectionContainsString(dependency.getEvidence(EvidenceType.PRODUCT), entry.getProduct().substring(0, entry.getProduct().length()-version.length()))
<del> );
<add> isValid = majorVersions.stream().filter(version -> entry.getProduct().endsWith(version) && entry.getProduct().length() > version.length())
<add> .anyMatch(version
<add> -> collectionContainsString(dependency.getEvidence(EvidenceType.PRODUCT), entry.getProduct().substring(0, entry.getProduct().length() - version.length()))
<add> );
<ide> }
<ide> }
<ide> return isValid; |
|
Java | apache-2.0 | a4d76182518b9ff83958c37151fe95fb963e9c41 | 0 | cefolger/needsmoredojo,cefolger/needsmoredojo | package com.chrisfolger.needsmoredojo.core.amd;
import com.chrisfolger.needsmoredojo.core.settings.DojoSettings;
import com.chrisfolger.needsmoredojo.core.util.AMDUtil;
import com.chrisfolger.needsmoredojo.core.util.DefineUtil;
import com.chrisfolger.needsmoredojo.core.util.FileUtil;
import com.chrisfolger.needsmoredojo.core.util.JSUtil;
import com.intellij.lang.javascript.psi.*;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class ImportCreator
{
private static final Map<String, Integer> libraryScores = new HashMap<String, Integer>();
static
{
libraryScores.put("dojo/tests", 0);
libraryScores.put("dojo/", 5);
libraryScores.put("dijit/", 4);
libraryScores.put("dgrid/", 2);
libraryScores.put("dojox/", 1);
}
private int getScore(String item)
{
int baseScore = 0;
for(String key : libraryScores.keySet().toArray(new String[0]))
{
if(item.indexOf(key) != -1)
{
return libraryScores.get(key);
}
}
return 0;
}
public @NotNull String[] getChoicesFromFiles(@NotNull PsiFile[] filesArray, @NotNull SourceLibrary[] libraries, @NotNull String module, @Nullable PsiFile originalModule)
{
return getChoicesFromFiles(filesArray, libraries, module, originalModule, false);
}
public @NotNull String[] getChoicesFromFiles(@NotNull PsiFile[] filesArray, @NotNull SourceLibrary[] libraries, @NotNull String module, @Nullable PsiFile originalModule, boolean prioritizeRelativePaths)
{
List<String> choices = new ArrayList<String>();
for(int i=0;i<filesArray.length;i++)
{
PsiFile file = filesArray[i];
PsiDirectory directory = file.getContainingDirectory();
String result = directory.getVirtualFile().getCanonicalPath();
// parse dojo libraries only
int firstIndex = Integer.MAX_VALUE;
SourceLibrary firstLibrary = null;
for(SourceLibrary library : libraries)
{
String fileWithoutLibraryPath = result;
if(fileWithoutLibraryPath.indexOf(library.getPath()) != -1)
{
fileWithoutLibraryPath = library.getName() + fileWithoutLibraryPath.substring(fileWithoutLibraryPath.indexOf(library.getPath()) + library.getPath().length());
}
int index = fileWithoutLibraryPath.indexOf(library.getName());
if(index > -1 && index < firstIndex)
{
firstIndex = index;
firstLibrary = library;
}
}
if(firstLibrary != null)
{
if(!firstLibrary.getPath().equals(""))
{
result = firstLibrary.getName() + result.substring(result.indexOf(firstLibrary.getPath()) + firstLibrary.getPath().length());
}
result = result.substring(result.indexOf(firstLibrary.getName()));
result = result.replace('\\', '/') + '/' + file.getName().substring(0, file.getName().indexOf('.'));
String originalModulePath = null;
String relativePathOption = null;
String absolutePathOption = null;
if(originalModule != null)
{
originalModulePath = originalModule.getContainingDirectory().getVirtualFile().getCanonicalPath();
originalModulePath = firstLibrary.getName() + originalModulePath.substring(originalModulePath.indexOf(firstLibrary.getPath()) + firstLibrary.getPath().length());
String relativePath = FileUtil.convertToRelativePath(originalModulePath, result);
if(relativePath != null)
{
// need to use dojo syntax when two files are in the same directory
if(relativePath.equals("."))
{
relativePath = "./";
}
else if (relativePath.charAt(0) != '.' && relativePath.charAt(0) != '/')
{
// top level module
relativePath = "./" + relativePath;
}
relativePathOption = relativePath;
}
}
absolutePathOption = result;
if(prioritizeRelativePaths && relativePathOption != null)
{
choices.add(relativePathOption);
choices.add(absolutePathOption);
}
else
{
choices.add(absolutePathOption);
if(relativePathOption != null)
{
choices.add(relativePathOption);
}
}
}
}
Collections.sort(choices, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return getScore(o2) - getScore(o1);
}
});
choices.add(module);
return choices.toArray(new String[0]);
}
public String[] getPossibleDojoImports(PsiFile psiFile, String module, boolean prioritizeRelativeImports)
{
PsiFile[] files = null;
PsiFile[] filesWithUnderscore = null;
List<SourceLibrary> libraries = new ArrayList<SourceLibrary>();
try
{
VirtualFile dojoSourcesParentDirectory = AMDUtil.getDojoSourcesDirectory(psiFile.getProject(), true);
if(dojoSourcesParentDirectory != null)
{
for(VirtualFile directory : dojoSourcesParentDirectory.getChildren())
{
SourceLibrary library = new SourceLibrary(directory.getName(), directory.getCanonicalPath(), true);
libraries.add(library);
}
}
VirtualFile[] otherSourceDirectories = AMDUtil.getProjectSourceDirectories(psiFile.getProject(), true);
for(VirtualFile directory : otherSourceDirectories)
{
for(VirtualFile sourceDirectory : directory.getChildren())
{
if(sourceDirectory.getName().contains("."))
{
continue; // file or hidden directory
}
SourceLibrary library = new SourceLibrary(sourceDirectory.getName(), sourceDirectory.getCanonicalPath(), true);
libraries.add(library);
}
}
files = FilenameIndex.getFilesByName(psiFile.getProject(), module + ".js", GlobalSearchScope.projectScope(psiFile.getProject()));
// this will let us search for _TemplatedMixin and friends
filesWithUnderscore = FilenameIndex.getFilesByName(psiFile.getProject(), "_" + module + ".js", GlobalSearchScope.projectScope(psiFile.getProject()));
}
catch(NullPointerException exc)
{
return new String[] { module };
}
Set<PsiFile> allFiles = new HashSet<PsiFile>();
for(PsiFile file : files) allFiles.add(file);
for(PsiFile file : filesWithUnderscore) allFiles.add(file);
PsiFile[] filesArray = allFiles.toArray(new PsiFile[0]);
return getChoicesFromFiles(filesArray, libraries.toArray(new SourceLibrary[0]), module, psiFile, prioritizeRelativeImports);
}
protected void createImport(String module, JSArrayLiteralExpression imports, JSParameterList parameters)
{
String parameter = AMDUtil.defineToParameter(module, ServiceManager.getService(parameters.getProject(), DojoSettings.class).getExceptionsMap());
if(imports.getChildren().length == 0)
{
Messages.showInfoMessage("Need at least one import already present", "Add new AMD import");
return;
}
for(JSParameter element : parameters.getParameters())
{
if(element.getName().equals(parameter))
{
// already defined, so just exit
new Notification("needsmoredojo", "Add new AMD import", parameter + " is already defined ", NotificationType.INFORMATION).notify(parameters.getProject());
return;
}
}
JSUtil.addStatementBeforeElement(imports, imports.getChildren()[0], String.format("'%s',", module), "\n");
JSUtil.addStatementBeforeElement(parameters, parameters.getChildren()[0], parameter + ",", " ");
}
public void addImport(PsiFile file, final String module)
{
JSRecursiveElementVisitor visitor = new DeclareFinder().getDefineVisitor(new DeclareFinder.CompletionCallback() {
@Override
public void run(Object[] result) {
JSCallExpression callExpression = (JSCallExpression) result[0];
JSFunction function = (JSFunction) result[1];
DefineUtil.DefineStatementItems items = new DefineUtil().getDefineStatementItemsFromArguments(callExpression.getArguments());
createImport(module, items.getArguments(), function.getParameterList());
}
});
file.acceptChildren(visitor);
}
/**
* when the user adds a new import, this code searches for the nearest possible element
* to the cursor that they may have wanted to import and returns a suggested choice.
*
* I know this method is crude/hard to read and could be way more elegant, however it's good enough for now
* and produces quite a lot of benefit for low effort
*
* TODO this is a good candidate for unit testing...
*/
public String getSuggestedImport(@Nullable PsiElement element)
{
if(element == null)
{
return "";
}
String initialChoice = "";
PsiElement parent = element.getParent();
PsiElement previousSibling = element.getPrevSibling();
// (underscore represents cursor)
// we're just over a reference. Example: Site_Util
if (element.getParent() != null && element.getParent() instanceof JSReferenceExpression)
{
initialChoice = element.getText();
}
// we're inside a constructor. Example: new Button({_});
if(element.getParent() instanceof JSObjectLiteralExpression)
{
JSObjectLiteralExpression literal = (JSObjectLiteralExpression) element.getParent();
if(literal.getParent() != null && literal.getParent().getParent() != null && literal.getParent().getParent() instanceof JSNewExpression)
{
initialChoice = ((JSNewExpression)literal.getParent().getParent()).getMethodExpression().getText();
}
}
// we're inside a new expression Example: new Button_
if(parent != null && element.getParent().getParent() != null && parent.getParent() instanceof JSNewExpression)
{
initialChoice = ((JSNewExpression)parent.getParent()).getMethodExpression().getText();
}
// we're right after a new expression. Example: new Button({}) _
else if (previousSibling != null && previousSibling.getChildren().length > 0 && previousSibling.getChildren()[0] instanceof JSNewExpression)
{
initialChoice = ((JSNewExpression)previousSibling.getChildren()[0]).getMethodExpression().getText();
}
// right after a reference. Example: SiteUtil_
else if (previousSibling != null && previousSibling.getChildren().length > 0 && previousSibling.getChildren()[0] instanceof JSReferenceExpression)
{
initialChoice = previousSibling.getChildren()[0].getText();
}
// after a variable declaration. Example: var x = new Button({})_
else if (previousSibling != null && element.getPrevSibling() instanceof JSVarStatement)
{
JSVarStatement statement = (JSVarStatement) element.getPrevSibling();
for(JSVariable variable : statement.getVariables())
{
if(variable.getInitializer() instanceof JSNewExpression)
{
JSNewExpression expression = (JSNewExpression) variable.getInitializer();
// if these conditions are false, it just means the new expression is not complete
if(expression != null && expression.getMethodExpression() != null)
{
initialChoice = expression.getMethodExpression().getText();
}
}
}
}
return initialChoice;
}
}
| src/com/chrisfolger/needsmoredojo/core/amd/ImportCreator.java | package com.chrisfolger.needsmoredojo.core.amd;
import com.chrisfolger.needsmoredojo.core.settings.DojoSettings;
import com.chrisfolger.needsmoredojo.core.util.AMDUtil;
import com.chrisfolger.needsmoredojo.core.util.DefineUtil;
import com.chrisfolger.needsmoredojo.core.util.FileUtil;
import com.chrisfolger.needsmoredojo.core.util.JSUtil;
import com.intellij.lang.javascript.psi.*;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class ImportCreator
{
private static final Map<String, Integer> libraryScores = new HashMap<String, Integer>();
static
{
libraryScores.put("dojo/tests", 0);
libraryScores.put("dojo/", 5);
libraryScores.put("dijit/", 4);
libraryScores.put("dgrid/", 2);
libraryScores.put("dojox/", 1);
}
private int getScore(String item)
{
int baseScore = 0;
for(String key : libraryScores.keySet().toArray(new String[0]))
{
if(item.indexOf(key) != -1)
{
return libraryScores.get(key);
}
}
return 0;
}
public @NotNull String[] getChoicesFromFiles(@NotNull PsiFile[] filesArray, @NotNull SourceLibrary[] libraries, @NotNull String module, @Nullable PsiFile originalModule)
{
return getChoicesFromFiles(filesArray, libraries, module, originalModule, false);
}
public @NotNull String[] getChoicesFromFiles(@NotNull PsiFile[] filesArray, @NotNull SourceLibrary[] libraries, @NotNull String module, @Nullable PsiFile originalModule, boolean prioritizeRelativePaths)
{
List<String> choices = new ArrayList<String>();
for(int i=0;i<filesArray.length;i++)
{
PsiFile file = filesArray[i];
PsiDirectory directory = file.getContainingDirectory();
String result = directory.getVirtualFile().getCanonicalPath();
// parse dojo libraries only
int firstIndex = Integer.MAX_VALUE;
SourceLibrary firstLibrary = null;
for(SourceLibrary library : libraries)
{
String fileWithoutLibraryPath = result;
if(fileWithoutLibraryPath.indexOf(library.getPath()) != -1)
{
fileWithoutLibraryPath = library.getName() + fileWithoutLibraryPath.substring(fileWithoutLibraryPath.indexOf(library.getPath()) + library.getPath().length());
}
int index = fileWithoutLibraryPath.indexOf(library.getName());
if(index > -1 && index < firstIndex)
{
firstIndex = index;
firstLibrary = library;
}
}
if(firstLibrary != null)
{
if(!firstLibrary.getPath().equals(""))
{
result = firstLibrary.getName() + result.substring(result.indexOf(firstLibrary.getPath()) + firstLibrary.getPath().length());
}
result = result.substring(result.indexOf(firstLibrary.getName()));
result = result.replace('\\', '/') + '/' + file.getName().substring(0, file.getName().indexOf('.'));
String originalModulePath = null;
String relativePathOption = null;
String absolutePathOption = null;
if(originalModule != null)
{
originalModulePath = originalModule.getContainingDirectory().getVirtualFile().getCanonicalPath();
originalModulePath = firstLibrary.getName() + originalModulePath.substring(originalModulePath.indexOf(firstLibrary.getPath()) + firstLibrary.getPath().length());
String relativePath = FileUtil.convertToRelativePath(originalModulePath, result);
if(relativePath != null)
{
// need to use dojo syntax when two files are in the same directory
if(relativePath.equals("."))
{
relativePath = "./";
}
else if (relativePath.charAt(0) != '.' && relativePath.charAt(0) != '/')
{
// top level module
relativePath = "./" + relativePath;
}
relativePathOption = relativePath;
}
}
absolutePathOption = result;
if(prioritizeRelativePaths && relativePathOption != null)
{
choices.add(relativePathOption);
choices.add(absolutePathOption);
}
else
{
choices.add(absolutePathOption);
if(relativePathOption != null)
{
choices.add(relativePathOption);
}
}
}
}
Collections.sort(choices, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return getScore(o2) - getScore(o1);
}
});
choices.add(module);
return choices.toArray(new String[0]);
}
public String[] getPossibleDojoImports(PsiFile psiFile, String module, boolean prioritizeRelativeImports)
{
PsiFile[] files = null;
PsiFile[] filesWithUnderscore = null;
List<SourceLibrary> libraries = new ArrayList<SourceLibrary>();
try
{
VirtualFile dojoSourcesParentDirectory = AMDUtil.getDojoSourcesDirectory(psiFile.getProject(), true);
if(dojoSourcesParentDirectory != null)
{
for(VirtualFile directory : dojoSourcesParentDirectory.getChildren())
{
SourceLibrary library = new SourceLibrary(directory.getName(), directory.getCanonicalPath(), true);
libraries.add(library);
}
}
VirtualFile[] otherSourceDirectories = AMDUtil.getProjectSourceDirectories(psiFile.getProject(), true);
for(VirtualFile directory : otherSourceDirectories)
{
for(VirtualFile sourceDirectory : directory.getChildren())
{
if(sourceDirectory.getName().contains("."))
{
continue; // file or hidden directory
}
SourceLibrary library = new SourceLibrary(sourceDirectory.getName(), sourceDirectory.getCanonicalPath(), true);
libraries.add(library);
}
}
files = FilenameIndex.getFilesByName(psiFile.getProject(), module + ".js", GlobalSearchScope.projectScope(psiFile.getProject()));
// this will let us search for _TemplatedMixin and friends
filesWithUnderscore = FilenameIndex.getFilesByName(psiFile.getProject(), "_" + module + ".js", GlobalSearchScope.projectScope(psiFile.getProject()));
}
catch(NullPointerException exc)
{
return new String[] { module };
}
Set<PsiFile> allFiles = new HashSet<PsiFile>();
for(PsiFile file : files) allFiles.add(file);
for(PsiFile file : filesWithUnderscore) allFiles.add(file);
PsiFile[] filesArray = allFiles.toArray(new PsiFile[0]);
return getChoicesFromFiles(filesArray, libraries.toArray(new SourceLibrary[0]), module, psiFile, prioritizeRelativeImports);
}
protected void createImport(String module, JSArrayLiteralExpression imports, JSParameterList parameters)
{
String parameter = AMDUtil.defineToParameter(module, ServiceManager.getService(parameters.getProject(), DojoSettings.class).getExceptionsMap());
if(imports.getChildren().length == 0)
{
Messages.showInfoMessage("Need at least one import already present", "Add new AMD import");
return;
}
for(JSParameter element : parameters.getParameters())
{
if(element.getName().equals(parameter))
{
// already defined, so just exit
new Notification("needsmoredojo", "Add new AMD import", parameter + " is already defined ", NotificationType.INFORMATION).notify(parameters.getProject());
return;
}
}
JSUtil.addStatementBeforeElement(imports, imports.getChildren()[0], String.format("'%s',", module), "\n");
JSUtil.addStatementBeforeElement(parameters, parameters.getChildren()[0], parameter + ",", " ");
}
public void addImport(PsiFile file, final String module)
{
JSRecursiveElementVisitor visitor = new DeclareFinder().getDefineVisitor(new DeclareFinder.CompletionCallback() {
@Override
public void run(Object[] result) {
JSCallExpression callExpression = (JSCallExpression) result[0];
JSFunction function = (JSFunction) result[1];
DefineUtil.DefineStatementItems items = new DefineUtil().getDefineStatementItemsFromArguments(callExpression.getArguments());
createImport(module, items.getArguments(), function.getParameterList());
}
});
file.acceptChildren(visitor);
}
/**
* when the user adds a new import, this code searches for the nearest possible element
* to the cursor that they may have wanted to import and returns a suggested choice.
*
* I know this method is crude/hard to read and could be way more elegant, however it's good enough for now
* and produces quite a lot of benefit for low effort
*
* TODO this is a good candidate for unit testing...
*/
public String getSuggestedImport(@Nullable PsiElement element)
{
if(element == null)
{
return "";
}
String initialChoice = "";
PsiElement parent = element.getParent();
PsiElement previousSibling = element.getPrevSibling();
// (underscore represents cursor)
// we're just over a reference. Example: Site_Util
if (element.getParent() != null && element.getParent() instanceof JSReferenceExpression)
{
initialChoice = element.getText();
}
// we're inside a constructor. Example: new Button({_});
if(element.getParent() instanceof JSObjectLiteralExpression)
{
JSObjectLiteralExpression literal = (JSObjectLiteralExpression) element.getParent();
if(literal.getParent() != null && literal.getParent().getParent() != null && literal.getParent().getParent() instanceof JSNewExpression)
{
initialChoice = ((JSNewExpression)literal.getParent().getParent()).getMethodExpression().getText();
}
}
// we're inside a new expression Example: new Button_
if(parent != null && element.getParent().getParent() != null && parent.getParent() instanceof JSNewExpression)
{
initialChoice = ((JSNewExpression)parent.getParent()).getMethodExpression().getText();
}
// we're right after a new expression. Example: new Button({}) _
else if (previousSibling != null && previousSibling.getChildren().length > 0 && previousSibling.getChildren()[0] instanceof JSNewExpression)
{
initialChoice = ((JSNewExpression)previousSibling.getChildren()[0]).getMethodExpression().getText();
}
// right after a reference. Example: SiteUtil_
else if (previousSibling != null && previousSibling.getChildren().length > 0 && previousSibling.getChildren()[0] instanceof JSReferenceExpression)
{
initialChoice = previousSibling.getChildren()[0].getText();
}
// after a variable declaration. Example: var x = new Button({})_
else if (previousSibling != null && element.getPrevSibling() instanceof JSVarStatement)
{
JSVarStatement statement = (JSVarStatement) element.getPrevSibling();
for(JSVariable variable : statement.getVariables())
{
if(variable.getInitializer() instanceof JSNewExpression)
{
JSNewExpression expression = (JSNewExpression) variable.getInitializer();
initialChoice = expression.getMethodExpression().getText();
}
}
}
return initialChoice;
}
}
| check for incomplete new expression. fixes #79
| src/com/chrisfolger/needsmoredojo/core/amd/ImportCreator.java | check for incomplete new expression. fixes #79 | <ide><path>rc/com/chrisfolger/needsmoredojo/core/amd/ImportCreator.java
<ide> if(variable.getInitializer() instanceof JSNewExpression)
<ide> {
<ide> JSNewExpression expression = (JSNewExpression) variable.getInitializer();
<del> initialChoice = expression.getMethodExpression().getText();
<add> // if these conditions are false, it just means the new expression is not complete
<add> if(expression != null && expression.getMethodExpression() != null)
<add> {
<add> initialChoice = expression.getMethodExpression().getText();
<add> }
<ide> }
<ide> }
<ide> } |
|
Java | epl-1.0 | 0efe837d57b6d1101ae8602012398bbde0fd5cd1 | 0 | mschreiber/packagedrone,eclipse/packagedrone,mschreiber/packagedrone,ibh-systems/packagedrone,ibh-systems/packagedrone,eclipse/packagedrone,mschreiber/packagedrone,eclipse/packagedrone,mschreiber/packagedrone,ibh-systems/packagedrone,ibh-systems/packagedrone,eclipse/packagedrone | /*******************************************************************************
* Copyright (c) 2014, 2015 IBH SYSTEMS GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBH SYSTEMS GmbH - initial API and implementation
*******************************************************************************/
package org.eclipse.packagedrone.repo.utils.osgi.bundle;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.packagedrone.repo.utils.osgi.ParserHelper;
import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.BundleRequirement;
import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.PackageExport;
import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.PackageImport;
import org.eclipse.packagedrone.utils.AttributedValue;
import org.eclipse.packagedrone.utils.Headers;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.VersionRange;
public class BundleInformationParser
{
private final ZipFile file;
private final Manifest manifest;
public BundleInformationParser ( final ZipFile file )
{
this.file = file;
this.manifest = null;
}
public BundleInformationParser ( final ZipFile file, final Manifest manifest )
{
this.file = file;
this.manifest = manifest;
}
@SuppressWarnings ( "deprecation" )
public BundleInformation parse () throws IOException
{
final BundleInformation result = new BundleInformation ();
Manifest m = null;
if ( this.manifest != null )
{
m = this.manifest;
}
else if ( this.file != null )
{
m = getManifest ( this.file );
}
if ( m == null )
{
return null;
}
final Attributes ma = m.getMainAttributes ();
final AttributedValue id = Headers.parse ( ma.getValue ( Constants.BUNDLE_SYMBOLICNAME ) );
final AttributedValue version = Headers.parse ( ma.getValue ( Constants.BUNDLE_VERSION ) );
if ( id == null || version == null )
{
return null;
}
result.setId ( id.getValue () );
result.setSingleton ( Boolean.parseBoolean ( id.getAttributes ().get ( "singleton" ) ) );
result.setVersion ( new Version ( version.getValue () ) );
result.setName ( ma.getValue ( Constants.BUNDLE_NAME ) );
result.setVendor ( ma.getValue ( Constants.BUNDLE_VENDOR ) );
result.setDocUrl ( ma.getValue ( Constants.BUNDLE_DOCURL ) );
result.setLicense ( makeLicense ( ma.getValue ( Constants.BUNDLE_LICENSE ) ) );
result.setDescription ( ma.getValue ( Constants.BUNDLE_DESCRIPTION ) );
result.setEclipseBundleShape ( ma.getValue ( "Eclipse-BundleShape" ) );
result.setRequiredExecutionEnvironments ( Headers.parseStringList ( ma.getValue ( Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT ) ) );
processImportPackage ( result, ma );
processExportPackage ( result, ma );
processImportBundle ( result, ma );
attachLocalization ( result, ma );
return result;
}
private String makeLicense ( final String value )
{
final AttributedValue license = Headers.parse ( value );
if ( license == null )
{
return null;
}
return license.getValue ();
}
private void processImportBundle ( final BundleInformation result, final Attributes ma )
{
for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.REQUIRE_BUNDLE ) ) ) )
{
final String name = av.getValue ();
final String vs = av.getAttributes ().get ( "bundle-version" );
VersionRange vr = null;
if ( vs != null )
{
vr = new VersionRange ( vs );
}
final boolean optional = "optional".equals ( av.getAttributes ().get ( "resolution" ) );
final boolean reexport = "reexport".equals ( av.getAttributes ().get ( "visibility" ) );
result.getBundleRequirements ().add ( new BundleRequirement ( name, vr, optional, reexport ) );
}
}
private void processImportPackage ( final BundleInformation result, final Attributes ma )
{
for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.IMPORT_PACKAGE ) ) ) )
{
final String name = av.getValue ();
final String vs = av.getAttributes ().get ( "version" );
VersionRange vr = null;
if ( vs != null )
{
vr = new VersionRange ( vs );
}
final boolean optional = "optional".equals ( av.getAttributes ().get ( "resolution" ) );
result.getPackageImports ().add ( new PackageImport ( name, vr, optional ) );
}
}
private void processExportPackage ( final BundleInformation result, final Attributes ma )
{
for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.EXPORT_PACKAGE ) ) ) )
{
final String name = av.getValue ();
final String vs = av.getAttributes ().get ( "version" );
Version v = null;
if ( vs != null )
{
v = new Version ( vs );
}
final String uses = av.getAttributes ().get ( "uses" );
result.getPackageExports ().add ( new PackageExport ( name, v, uses ) );
}
}
private <T> Collection<T> emptyNull ( final Collection<T> list )
{
if ( list == null )
{
return Collections.emptyList ();
}
return list;
}
private void attachLocalization ( final BundleInformation result, final Attributes ma ) throws IOException
{
String loc = ma.getValue ( Constants.BUNDLE_LOCALIZATION );
if ( loc == null )
{
loc = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME;
}
else
{
result.setBundleLocalization ( loc );
}
result.setLocalization ( ParserHelper.loadLocalization ( this.file, loc ) );
}
public static Manifest getManifest ( final ZipFile file ) throws IOException
{
final ZipEntry m = file.getEntry ( JarFile.MANIFEST_NAME );
if ( m == null )
{
return null;
}
try ( InputStream is = file.getInputStream ( m ) )
{
return new Manifest ( is );
}
}
}
| bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformationParser.java | /*******************************************************************************
* Copyright (c) 2014, 2015 IBH SYSTEMS GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBH SYSTEMS GmbH - initial API and implementation
*******************************************************************************/
package org.eclipse.packagedrone.repo.utils.osgi.bundle;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.packagedrone.repo.utils.osgi.ParserHelper;
import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.BundleRequirement;
import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.PackageExport;
import org.eclipse.packagedrone.repo.utils.osgi.bundle.BundleInformation.PackageImport;
import org.eclipse.packagedrone.utils.AttributedValue;
import org.eclipse.packagedrone.utils.Headers;
import org.osgi.framework.Constants;
import org.osgi.framework.Version;
import org.osgi.framework.VersionRange;
public class BundleInformationParser
{
private final ZipFile file;
private final Manifest manifest;
public BundleInformationParser ( final ZipFile file )
{
this.file = file;
this.manifest = null;
}
public BundleInformationParser ( final ZipFile file, final Manifest manifest )
{
this.file = file;
this.manifest = manifest;
}
@SuppressWarnings ( "deprecation" )
public BundleInformation parse () throws IOException
{
final BundleInformation result = new BundleInformation ();
Manifest m = null;
if ( this.manifest != null )
{
m = this.manifest;
}
else if ( this.file != null )
{
m = getManifest ( this.file );
}
if ( m == null )
{
return null;
}
final Attributes ma = m.getMainAttributes ();
final AttributedValue id = Headers.parse ( ma.getValue ( Constants.BUNDLE_SYMBOLICNAME ) );
final AttributedValue version = Headers.parse ( ma.getValue ( Constants.BUNDLE_VERSION ) );
if ( id == null || version == null )
{
return null;
}
result.setId ( id.getValue () );
result.setSingleton ( Boolean.parseBoolean ( id.getAttributes ().get ( "singleton" ) ) );
result.setVersion ( new Version ( version.getValue () ) );
result.setName ( ma.getValue ( Constants.BUNDLE_NAME ) );
result.setVendor ( ma.getValue ( Constants.BUNDLE_VENDOR ) );
result.setDocUrl ( ma.getValue ( Constants.BUNDLE_DOCURL ) );
result.setLicense ( makeLicense ( ma.getValue ( Constants.BUNDLE_LICENSE ) ) );
result.setDescription ( ma.getValue ( Constants.BUNDLE_DESCRIPTION ) );
result.setEclipseBundleShape ( ma.getValue ( "Eclipse-BundleShape" ) );
result.setRequiredExecutionEnvironments ( Headers.parseStringList ( ma.getValue ( Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT ) ) );
processImportPackage ( result, ma );
processExportPackage ( result, ma );
processImportBundle ( result, ma );
attachLocalization ( result, ma );
return result;
}
private String makeLicense ( final String value )
{
final AttributedValue license = Headers.parse ( value );
if ( license == null )
{
return null;
}
return license.getValue ();
}
private void processImportBundle ( final BundleInformation result, final Attributes ma )
{
for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.REQUIRE_BUNDLE ) ) ) )
{
final String name = av.getValue ();
final String vs = av.getAttributes ().get ( "bundle-version" );
VersionRange vr = null;
if ( vs != null )
{
vr = new VersionRange ( vs );
}
final boolean optional = "optional".equals ( av.getAttributes ().get ( "resolution" ) );
final boolean reexport = "reexport".equals ( av.getAttributes ().get ( "visibility" ) );
result.getBundleRequirements ().add ( new BundleRequirement ( name, vr, optional, reexport ) );
}
}
private void processImportPackage ( final BundleInformation result, final Attributes ma )
{
for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.IMPORT_PACKAGE ) ) ) )
{
final String name = av.getValue ();
final String vs = av.getAttributes ().get ( "version" );
VersionRange vr = null;
if ( vs != null )
{
vr = new VersionRange ( vs );
}
final boolean optional = "optional".equals ( av.getAttributes ().get ( "resolution" ) );
result.getPackageImports ().add ( new PackageImport ( name, vr, optional ) );
}
}
private void processExportPackage ( final BundleInformation result, final Attributes ma )
{
for ( final AttributedValue av : emptyNull ( Headers.parseList ( ma.getValue ( Constants.EXPORT_PACKAGE ) ) ) )
{
final String name = av.getValue ();
final String vs = av.getAttributes ().get ( "version" );
Version v = null;
if ( vs != null )
{
v = new Version ( vs );
}
final String uses = av.getAttributes ().get ( "uses" );
result.getPackageExports ().add ( new PackageExport ( name, v, uses ) );
}
}
private <T> Collection<T> emptyNull ( final Collection<T> list )
{
if ( list == null )
{
return Collections.emptyList ();
}
return list;
}
private void attachLocalization ( final BundleInformation result, final Attributes ma ) throws IOException
{
final String loc = ma.getValue ( Constants.BUNDLE_LOCALIZATION );
if ( loc == null )
{
return;
}
result.setBundleLocalization ( loc );
result.setLocalization ( ParserHelper.loadLocalization ( this.file, loc ) );
}
public static Manifest getManifest ( final ZipFile file ) throws IOException
{
final ZipEntry m = file.getEntry ( JarFile.MANIFEST_NAME );
if ( m == null )
{
return null;
}
try ( InputStream is = file.getInputStream ( m ) )
{
return new Manifest ( is );
}
}
}
| #2: default value for Bundle-Localization is not considered
If the `Bundle-Localized` header is not set there is a default of
`OSGI-INF/i10n/bundle` defined. This is now being applied as well.
The result was that some header entried did not get replaced if the
bundle header was missing but a properties was used. | bundles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformationParser.java | #2: default value for Bundle-Localization is not considered | <ide><path>undles/org.eclipse.packagedrone.repo.utils.osgi/src/org/eclipse/packagedrone/repo/utils/osgi/bundle/BundleInformationParser.java
<ide>
<ide> private void attachLocalization ( final BundleInformation result, final Attributes ma ) throws IOException
<ide> {
<del> final String loc = ma.getValue ( Constants.BUNDLE_LOCALIZATION );
<add> String loc = ma.getValue ( Constants.BUNDLE_LOCALIZATION );
<ide> if ( loc == null )
<ide> {
<del> return;
<del> }
<del>
<del> result.setBundleLocalization ( loc );
<add> loc = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME;
<add> }
<add> else
<add> {
<add> result.setBundleLocalization ( loc );
<add> }
<add>
<ide> result.setLocalization ( ParserHelper.loadLocalization ( this.file, loc ) );
<ide> }
<ide> |
|
JavaScript | mit | 2662d23fa4cc813a46ad687011cf67bfada5ca32 | 0 | spacenate/olark-observer,spacenate/olark-observer,spacenate/olark-observer,spacenate/olark-observer | var OlarkObserver = (function(OO, document, window) {
'use strict';
var debug = false,
feedbackEl = createFeedbackElement(),
statusObserver,
chatTabObserver,
chatListObserver,
linkObserver,
redColor = "#d65129",
yellowColor = "#f9cb32",
greenColor = "#88de68";
if (OO instanceof Object) {
// OlarkObserver is already injected
// Debug behavior - unregister old listeners,
// and proceed to load new OlarkObserver object
debug = OO.unregister();
}
/* Operator status changes */
var statusObserver = new MutationObserver(function(mutations) {
// Multiple mutations take place for each status change.
// Only the final mutation is important in determining the new status.
var lastMutation = mutations[mutations.length - 1],
newNodes = lastMutation.addedNodes,
newStatus = false;
// Grab the #status-indicator element, see what class has been assigned to it.
for (var i = 0; i < newNodes.length; i++) {
if (newNodes[i].id === 'status-indicator') {
newStatus = newNodes[i].className;
}
}
if (newStatus) {
sendXHR('PUT', 'status/' + newStatus);
}
})
/* New unread chats */
var chatTabObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// mutation.target is a LIVE element, and mutation callbacks are ASYNC
// so, ensure the tab has not been closed (mutation.target is not null)
if (mutation.type === 'attributes' && mutation.target !== null) {
var displayNameElement = mutation.target.querySelector('.display-name');
if (displayNameElement === null) {
return; // 'continue' with the next forEach, this is a closed chat tab
}
var tabName = hashString(displayNameElement.textContent.trim());
if (mutation.target.classList.contains('unread') && mutation.oldValue.indexOf('unread') === -1) {
// mutation.target just added the unread class
sendXHR('PUT', 'chats/' + tabName + '/1');
} else if (mutation.target.classList.contains('unread') === false && mutation.oldValue.indexOf('unread') !== -1) {
// mutation.target just removed the unread class
sendXHR('PUT', 'chats/' + tabName + '/0');
}
}
});
});
var chatListObserver = new MutationObserver(function(mutations) {
// iterate over mutations to look for new chats (new child added to #active-chats)
mutations.forEach(function(mutation) {
if (mutation.type === 'childList' && mutation.target.id === 'active-chats' && mutation.addedNodes.length > 0) {
sendXHR('PUT', 'chats/new/1')
var newTab = mutation.addedNodes[0];
chatTabObserver.observe(newTab, {attributes: true, attributeOldValue: true});
}
});
});
/* New unread chats, while window is inactive */
var linkObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
// It seems only one element is added for each mutation
var newElement = mutation.addedNodes[0];
// 'continue' with next forEach if the new element is not a link[rel=icon]
if (newElement.rel !== 'icon') {
return;
}
var newStatus = identifyBase64Image(newElement.href);
if (newStatus !== false) {
sendXHR('PUT', 'status/'+newStatus);
} else {
debugLog("Unidentified status icon", newElement.href);
}
}
});
});
// @todo: slim down this list to one base64 image per status
function identifyBase64Image(base64String) {
switch (base64String) {
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADVUlEQVRYhe2TTUwbRxiG5wbyKVWtRCqNWkgIErWlwglziExVxQilUhL10KiqmkpJS5O0BKfGP2t2Zz2xvYvXWmdtfpy4tOql6o/UEz1wS9MmIjQYG8zaBiMc95Arh5gciN8eFnPo1U6lVn6kT9837470vjOjJaRFixb/VSilZp7nHTzPOyilpzVNa/tXjD3Kx+NcaOypIPpeuNWP9ifUD/e9kc+rlPmeCwHXAmOs+6UY+3yXj3GRq0/8kWu4+csJjP9G4PydwPkHwY37BGOLBM5vB2uCyO1ROnmpqeY36LkjfOSLXe/8CFwPCNxLBBOPjO5eIpg46K6HBDd/fQ3+sLPa1BB+9UrR//X78C4TcI8JuD+N7n1MwC0T+OraMoFvmcCz2AlB5Paa8hze+ZGzQsgN/tEr4NPtENImCKsmTKZN4Ffbwafbwa8cVNoEPt2OyRUTvN+/WxNCnoXGTx+/nBV+fA9i5ijErBksa0Yga8yBzFEEsmYEMoYuZow5kHkVwtIbEBn3vOG/Q4hdf8buDSC43nFYofUOBNeMurXWgeD6cUNfO27o6x1g2dchRseqlNLTDQUQw55aOP0WQrlOSBtvQsp1QdroQvigpFwXwrmuf3w7ASnXCXHm032e5x0NBvDW5FUr5I1TkPUeTOndmNK7IeeNWdZPQta7IW+cwpTeA0nvMfbmTyIwM9p4AKaOV+UHdih5C6KFXkTzFigFK6IFC5RCL5SCFZG8BUq+19DyVih5CxTdCiHgf0EpNTd2A/Hrurx4HrHNPqibfYht9hu19TZiW/2Ha7XYZ+wp9kEt9kO5PwIW9TxtyJwQQqjqlMLfjNYS2zbES4NIlGxIlAaQKNkQ37ZhetuGeGkAiW0bput6aRC3brvApq+ONxxA07Q2GvTvag8vYK48hNkdO+Z2hpAsD2Fux45k2Y7Zcn39DpJlOyI/XwFTv3rSsHkdyibO0bB/b3rpA6QqZ3C3cgapyjBSlWHcrQwj9ZcDqYoDd3ZGEPnhGthtz64vOHasaQEOQ4QmdyPffVmL3/sEyfRFpLbOY750AcmVi4gtfAYm+yHNuopUvXSkqeZ1NE1rYzGfFEq69bDmrjKJqzGJqwVnvM+kO85s9KfRsy/FuEWLFv9r/gY+jTpf/0j1VwAAAABJRU5ErkJggg==':
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADU0lEQVRYhe2TPWgbZxzG381GU0pFAnVDayeOwZWg9mSlEORAI2MSSEKHBkqbQkIwrrEdVdHX6T4t3Z11qpST/KFadUqX0lLayR28pWkSHDeWJVs+SbaMFWXI6iFyBkdPh7M8ZD0lkKAfPPz/73MvPM9xHCFNmjR5W2FZ1kzTtIOmaQfLsmdUVW15I8Ee5ZtxShx7xvC+l57o1/vu6Ff7vvBQlRX8LxjBtSAIQudrCfYFrx2jwsNPqPAwnH+dwPg/BDf/Jbh5n2DsHsHoIoHz589qDO/fY9nA1YaGj0UvHqHDI7ve+UG4HhC4lwhuPdKne4ng1sF0PSRw/v0BAqKz2tASVPR6kfrpC3iXCfyPCfz/6dP7mMC/TOCre8sEvmUCz2I7GN6/15DP4Z2/cJ4JuUE/eg90uhVM2gRm1YRA2gR6tRV0uhX0yoHSJtDpVgRWTPD9+nmNCXkWjL99/FqW+f0CuMxRcFkzhKwZfFbf+cxR8Fkz+Izucxl95zPvg1n6CJxAvTD8dzCxkefC3T4E19sOFVpvQ3BN18RaG4Lrx3V/7bjur7dByH4I7ofRKsuyZwwV4ERvTUx/glCuHdLGx5ByHZA2OiAeSMp1QMx1vPLsBKRcO7jpG/s0TTsMFvDV5FUr5I1TkLUuTGqdmNQ6Ief1XdZOQtY6IW+cwqTWBUnr0u/mT4KfHjJeQIiNV+UHdih5CyKFbkTyFigFKyIFC5RCN5SCFeG8BUq+W/fyVih5CxTNClagXrIsazZUgE+MaPLiJcQ2exDd7EFss1fX1qeIbfUenqPFHv1OsQfRYi+Ue4MQIp5nhsIJIYSLfi+Jd4ZqiW0b4qXTSJRsSJT6kCjZEN+2YWrbhnipD4ltG6bqfuk0Jm67IEx9N264gKqqLVyI2lUfXsZsuR8zO3bM7vQjWe7H7I4dybIdM+X6+SySZTvCf1zHRMz1xHB4HVbwXuQkam9q6UukKucwVzmHVGUAqcoA5ioDSD11IFVx4MedQYR/G8bEbc9uMDZ6rGEFDkuIgd3wL6O1+N1vkUxfQWrrEuZLl5FcuYLYwg0IMgVpxlVk71w90tDwOqqqtgRVnyQm3ZoY91QFiaoJElULTXufS3PObOTP4fOvJbhJkybvNP8DXOE67fHe6r8AAAAASUVORK5CYII=':
return 'available';
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADLElEQVRYhe2VW0gUYRiGP4JykwiDqSgvMsOKUsi6qITCggikoKSLIKIuCjoY6oaHPTjz7w7uIZVd1qK6UJcIiiK6KsibskzZtEa3UkunqQyKblwpD9E2bxfuWq0rO+oUBL7w8c8B5n3+9/t+hmhWs5rV/yrGGMfz/G6e53czxrb7fL6kf2JcXn2k2OIo/CTYzD/KPIfDpZ5DYVPVyWEmmkcFe8kdURQz/oqx2XxsqaXq1Htr1Wmcvb0KxQ8JxmaC8TGh6BGhsJFg9Oeogs0ywljFUV3Ni9i+FL7qzKCpPg8lLYSyAKH0ydhaFiCURtaSVsLZu8thdRqHdYWweo6/ttYdgKmNYHlKsLSPraanBEsbwRx91kYwtxHKG1dCsFlGdGmHqT5vj+AoA/9kEXjJAEFKhtCRjAopGXyHAbxkAP8sUlIyeMkAsWk+ais2qU7LmXsz333tsaBwYy9snUtgC3IQgxzswbFre+cS2IMc7J0crooLcH/nPMhEsTUgEzUoRLnTAhC8BUNi0xZUvkgdL8eLVFQ+H6sLNxejfe3ceMYTqo/ovkKUMiUAm7NcdUrr4Xi5Eq6uNLhepsPVlQ5nVzrq/MvQs3DOBKOQ14uovly7FvteUYg2TAHApLo7suDuWg139xqc687Aue4MXL69Iq75h82bEf78+RfA9evx0pA0JyF6iofdLbmo7slEzat1qOnJRPWrLDxbaxj/oMJxGG1tRfjjR0BV8bsmAUAfkV9bArUF3e7G/fD2ZsPTmw1v70bccq3442MKx0H9+hXxNBmATASFKC0hAPMYXc6GE+r5N1tRK+fgvLwVLbsWTQD4JkkI9/fju6JAHRrSBCATsYQAPp8viVVaB32t+bj0bgcuvs1NOO0jzc2aAPqIHmhqAxNL9zGndeRC4CCutmxLCDAaCGhNYEATwDiEo2LQX56v6ggAzQDRdtSw0x4dAUJTAohKJgrpAaB5BmLVR+TXKYGiaQEoRLk6AISm/F+ISeHBDAHYtM0jKaTIRG8TAly5ol/v40BskIk6Ep2KWPMZRR8HIiXRUEZ7PuPYE4CkyUQsMhvRYxqK3BdNtuuf8bvc+Hczj/wAAAAASUVORK5CYII=':
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADLElEQVRYhe2VW0gUYRiGP4JykwiFySgvMsOKMtAIyqKwIIQo6HTRRVQXdREirW2me5qZnUF3N5VdVqO6qJYIiiK6KsibTqZspqNbuppO0wkMb1opD9E2bxfuWq0rO+oUBL7w8c8B5n3+9/t+hmhWs5rV/yqe5xmWZYtYli3ieX6bz+dL+SfGFTVHS21O4ydOsPyo8ByJlHsORyzVJ4d50TrKiWX3RFHM+SvGlsrji23Vxe9t1cUw3V2B0ieE042E088IxqeEUw0Ek3+LygnWEZ63H9PV3OjZm8ZWlwyar+xCWROhPEA4+3xsLQ8QzkbXsmaC6f5S2J2mYV0hbJ4Tr22XD8LcQrC2EqwvxlZzK8HaQrDEnrUQLC2Eiobl4ATriC7tMF/Zs5urKgf7PB2sZAAnpYJrT4VdSgXbbgArGcC2RUtKBSsZID6ejzr7BtVpLXkw893XHQ9yt/bA0ZEBR5CBGGQgBMeuhY4MCEEGQgeD6+ICPNwxDzJRfH2Wia4qRIXTAuC8JUPi402ofJU5XlWvMlH5cqzO316EF6vnJjKeUH1EDxWitCkBOJxm1SmtRVXncri6suDqzIarKxvOrmxc9i9B98I5E4zCXi9i+nLjRvx7RSHKmwKARXW3r4O7ayXcoVU4F8rBuVAOLt1dltD848aNiAwM/AK4eTNRGpLmJERv6bC7qRA13bmo7VmD2u5c1PSsQ9tqw/gHFYbBaHMzIv39gKrid00CgD4ivyYAob4k5G7YB29vPjy9+fD2rscd17I/PqYwDNSvX5FIkwHIRFCIspK3wHPG5bx6Uq1/U4A6eTPq5QI07UyfAPBNkhD58AHfFQXq0JAmAJmITwrg8/lSHFW2QV/zflx8tx0X3hYmnfaRxkZNAH1EjzS1gRfNex0u28j5wCFcb9qaFGA0ENCawGdNAOMQTvugv+KAqiMANAPE2uERij06AoSnBBCTTBTWA0DzDMSrj8ivUwLGaQEoRIU6AISn/F+IS+HRDAH4aZtHU0iTid4mBbh2Tb/eJ4DIk4nak52KePMZRZ8AIi3ZUMZ6PuPYk4BkyUR8dDZixzQcvTdOtuufuk3dRfHDbRAAAAAASUVORK5CYII=':
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADIklEQVRYhe2VW0gUcRTGTw+xi09Zk1E9mIYGlQ8GUUmFPQVSkFFYRNiDQRejdcPLXpyZ3cW9eGmX1S4vXShIKcIeKkiIrCzZzEY3XdOdzcrA8CUldY22+XpQ07bVHXUqAj84nGEY5vv9v3OYIZrXvOb1v4rneYZl2Z0sy+7keX672+1W/RXjovLsPIP19CfOpP9e6DwcKnAeCunKjg/zFv0IZ86/Z7FYkv6IsV6fs8xQduKDsewkztSuRt4TgraBoH1G0DwlnK4jaK+mSZzJEOT54iOKmmv4PYvYslMDussZyH9OKPQQCl6M9kIPoWCs5zcSztxfAaNNO6wohNF5tMt4aR90TQRDM8HwcrTrmgmGJoJ+/F4TQd9EKKpLAGcyBBUZh+5yxi7OWgj2RSxYQQ1OiAHXEoNiIQZsixqsoAb7aqyEGLCCGva7atw4nCyVa3Iezv30lTle7uZumFrjYPIysHgZmL2j1+bWOJi9DMytDB5kqvCaWYAAUXhJIpE/QKSZFQDnyh2yPN6MkraVP8vathIlr0fremksulS/mUYskeizjyh+RgAmW5FkE9bB2p4Au28V7O2JsPsSYfMl4nbR4ohG/S4XxvWlujoc4ptIlDUDAJ3kaEmBw5cMR8calHYkobQjCTfOLo9o/nHTJoT6+iYAamoiPTcsOwmLM2/Y8Twd5W/Wo6JzLSrerEd5Zwq6VBPz7mYYjDQ2ItTbC0gSJmsKAPiJRHkJVOZ2OOoy4fKnwulPhcu/AY/2L/nlZd0MA2lwEJE0FUCACJ1EW6MC8E6t3XblmFT1dgsqA2moCmxB+9KFvwF8FQSEenrwrbsb0tCQLACRqD4qgNvtVvElxgF3415cfL8DF96lR932YEODXIB+WWPgLQV7eJsxeM5zALdub4wKMOLxyAIIEEmyAH5CWIsH7hzcJikIANkA4+O4oM0+/88AxqUUgOwdCJefSFQIoHa2CWiUAJjxf2GyRKL+uQDI+gZMJx9RfIAoFBXg2jXlZh8hhSyRKBhtKcPN5xR9uHxE8dGWUrHYp1Mn0VaRqD58N0SifpGodqpT/wCWW+EolsF5jAAAAABJRU5ErkJggg==':
return 'available?withChats=1';
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADyklEQVRYhe1VXWxTZRh+Y6LUxZiRHDHKBWNmSiYQ0BshUaZBSBZNkEgwWUQvMJmWha5kP/3Z+enJ+kO3dOkgzgugF3DjYriaxN0w/BkZA9pV2IbtsQwjK6lhW5S2G915vFh31nPa2nabJiZ7kzff6Zv0e57zvO/zHqK1WIu1+L8Gz/MMy7L7WZbdz/P8W16vd91/Atza8UmjxX48ygnm+RbPx6lmT13K5P48zovmJGdr6hNFsepfATabjz5vcX9xz+rW48TFl9D4PcH4I8H4E8HwA+F4P8Ho2y1zgiXB822friq4gT9QzrobZkxna9E0SGgZIjRfWzhbhgjN6bPpKuHEty/C6jDGV5WE1fPZL9YzH8I0TLDcIFiuL5ymGwTLMMG8WBsmmIcJrf2bwQmWxKq0w3S29j3O3gL22nqwfh04fxm4QBna/GVgAzqwfh3Ym+n0l4H16yBeeRrdba/LDkvDdyt/++6jQe7r9yGMbIAQZCAGGdiCC8+2kQ2wBRnYRhicF5/B5XeegkSkzSmJ6FyEqGZZBLiuY4/EK2+g/dZGJe23NqL954U83fscrm95UgV6f98+TNbWIsIwqnqY6HKEqLwkAoKjVXb4X4X99mY4RyvgvF0J52glHKOVOON7AePPPqEAxC9dghyPIzMeh8OIHj6cSSQSIdpRAgGT7Apsg2v0ZbjGXsHJsSqcHKvCVxc3qcATAwPIG/PziNXXZ5LwF62E6GmMuwZr0DG+FZ13qtE5vhUdd7bh5hadcmH00CEglVoCnJ1FanJSxSEVjapaEibyFadA97ExV/8H6ArthCe0E12h1/CNc5Oqt9NerwIkJxL4fc8eSET4q7d3qR6P4151tep/EaKKggR4j9HpOFcvn/p1F7ql3Tgl7cLgu+tVF8309ChAc6GQUo/p9YAsK214cOSI1iF8QQJer3cd326d8V49iJ6Jt/Hl3Zosq93fuxcPBQEPBQGxhgal/qivT6XMb9u3a10xUFQbeLH5AO+wJk4PfYTzg2/m8npWZsoPAI8nJnLuiKIIKCTsbTO+1oPyPwFHGAazgUCWC3LID4kIRRNYbEcnr/fkA4/p9ZCTSTX43Bz+MBjyEZ4uicBiSETT2suyrJheQtq+L2sGtBEm8mllT0WjS8iyjD8vXChmVgzLIhAhqlHtAbc7e/lNTUFOJpcykcCDujqV/CV/FzQqDOSyW96QZcT0+tJ2QAEVyiWiuwW/AzmcsOze5yCxQyIKFLMXMgdvRdLnIFGuHcp8llux7AWIVEhEfHo2Fm06nf5tyPfWfwPcuzdCV3S+YgAAAABJRU5ErkJggg==':
return 'available?withChats=2';
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAD+UlEQVRYhe2VXUibZxTHD4OtmYxhIevoelF1uBXXQrverIWtbnQtBAddWelgjO2ig820VFP8yIdv3uTFfFQlGi3LLmxDKb3YGPZmgwlS67YUtRqN1lg1SxtIW2rXJHOJmo/3v4uYN59q/Nhg4B8OT3J4OOf3nHOe5yXa0pa29H8Vy7JihmGOMwxznGXZ98xm87b/JHF98xfVSt35x2qNIlZn+jxaa/osKm/6JsRyigW1tuYnjuNK/5XECsWZV5VNlR5VkxQXul5HdR9B9htB9juh6lfC+W6CzHqYV2uU8yzb8OWmJq9iTxQyTecC8ssS1NgIdf2E2oH4WtdPqF1aa24TLvz8GlR6WWhTIVSmr6ZUnZ9APkhQDhGUd+KrfIigHCQoEr5BgmKQUN9dDLVGOb8p7ZBfllSodXVgBraDsYugthdAPVKABnsBmBERGLsIzPCS2QvA2EXgbr2I9oaDvF557peNn779jEP9/UfQjO6AxiEG5xBD64j/1o7ugNYhhnZUjGvcS7j5wQtwEWWaz0V0xU1Uvi4AdevZIHfrHTSO7xJMN74LjWNxu/TDK7iz5/m0pA+PHcMjiQRusTjNP0N0001UuCYAjb6e19vfgu5uMQwTRTDcLYFhogT6iRJ0Wndi8uXnhAShnh4gHEaqwk4nHh49mgridhPtXwOAnDeO7INx4g0YnW/iorMUF52l+K5rd1ryhYEBLKtwGN4jR1Ih7HlXgjNVh4y2cjRP7kXLvTK0TO5F8719GN4jEgLOVlYCPC/kiz55gqjXm8YQ6unJbIc1vwq0n3Uauz9G6/QBmKYPoHX6bfxo2J0WLGCxJJN7vYJ/cWwsWYSpqawBdRMVrQrAmmQG/ZWv+Y4/DqHddRgdrkOwfbg9LZDPaAQfDIKfm8Pc9etJgKEhAWBxfDzXDWFXBTCbzdvYRlXAfPskLA/ex7f3y3MFSp5KLMZfnZ3xmUhpy9zVq1l7Z4h682oDy9WeYPWq+Uv9n+Ka7d0VAR6fPg3EYulDGI1mXcnEG5EXgAChawhY60/yKwKcOgVEo1kXYb6vL+f+vAES7WhhpaaVAFxEeCSR4BnLIvb0qQDAh0LwlJVl7vWvCSAhF5E/NdDfXV2IeDyIeDx4ptUK/j/l8uQc8DxmpdL1zUCmZoisqYEWh4eFky7YbILf39a20mMEF1HVugDcROWZFUjVgs2G4I0babMQ8/nwoLg4rfxr/i5kVKFX6HlFBRCJZA1eqgIdHWt/A1apQqGL6L7wHEul4IPB7MyRCAIWy+b0PgfEfhfRSGrwWakU/rY2BCwW+IzGXJ/k3g2VPgdEYeZQLmP+DZd9FZAiFxG7NBuJa+pf+l+13Kn/Ac86ODo4iC2XAAAAAElFTkSuQmCC':
return 'available?withChats=3';
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADPElEQVRYhe2T32tTZxzGz12Fk5PE0zbRBFJoT5tmZth6ck7SE82vTnM2XFq2dDOllaYX6Ryt4FpEK+qt173zD8hopa1Wkord1TaGbGOMeSPkzk6lV8PM9rzfQM3jxUn1DzhxMMkHXp73eXjheeBwOK5Fixb/V27LQkdR5dNFlU8XlUOxJYlr+0+Ky2eOXlqPizvLYeF1OX1kf1M/sr+RdBkrqkCrmqNcDLf1vpfi74dd7o1Ex/b9ZCcq38j493oKezeGsXfzE7y6kcLO5VP47Zy/vhwR2B1FmGpq+d2E07kRE6uPvujG7pU4aDEBuhZHbTGO2tUEaosJ0GIcxtUYnl4IYVVzGk0dURrurPzyuQ/Gd0OoLWioLZhKC1HU5rV32bwGNh/F34VBLEcE1pTP8fNn3rNrmgO738qguRBoTgFdVEFzKuhiw88qoNmQmc0pMGZV/DHSVV+N2MuWBzxIdD7+M+MDKwyCzQyAZgZAM4NgM8dBhUHTF8ycFRr3wnH8Mx3EHcVGlv+O0klx79nXEth0ECwfBOWDoPwx0JR5WD4INh0ETQdB+Y9BU+YbY+oYSidFo6gcilkasBYW6i9zfWAT/aDJftBEADQZADsfAJsMvPU02d/QAOj8R6CJfmwlxP2iyqetDVCF+suvekC5XrCcHzTeB8r1gcb9De01NdcHyvnBxv1gjfxh7LD1AWXNabzI+EBZCTTW3VAJNNYDNtYNGpPAsj1g2W4zy0qgrATjSwkriu31bVnosDTgoXb4SeW0GzTiAxvxgUa6zDPqA4027pkusEyX+SZj+qe6B/fC9h1L5RzHcSXVcetHzVEn3QuW9oJ0D0j3gOleMN0D+vRAPaC0B6R7YegelIcceBCxX7I8YEni2lZVW3U71g6WcoElXKCkG5RygyU7QUkXWMr0Zu7C71Enyqp923L5ASuyMLqu8mx7SARFRTBNBGntoGg7SOsARUWQJmI3KuJRxIGSKlQ3wry7aQPejlBs1Z9CtnpFteO5Ykc15EBVdeCZYsdfih3rig1bslC5O8A5m1p+wJLEtZVk/taWbHuyGeKNtRBfXwvx9U2Z3/tB5h//ekI4+16KW7Ro8UHzBoGVChwxHE8wAAAAAElFTkSuQmCC':
return 'away';
case 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADHUlEQVRYhe2V7UtTYRjGb4iIIkhqmlszZ2yRmnS2OTdrbtN0i7bKXlhU9EJK0fqiEWlk4Me+Jf0DRVAatKJVhlbYB0mMaBFUEBtHWrCUyGnqppvP1Ye2XuZkR3cKAi+4eXjOgef6neu+Hw7Rgha0oP9VN9fLJLc0ObZbmhybWy01XSFa8k+Mu6qVjR7j2s9unXS6u0YZe2xVxjrNBRN3tLKIR7/m4Q0uW/VXjG/qC1Y/Mik+PjIrMHDChMiFHYi27ET04i5MtuzA17Pb4HWqmbtMFnZrco+Jan6XU2R1bskfeVlbgqlz28Ga7WDn7UCzHWj6sbJmO2JN2xE8acY9g3xCVIhuS8GHF/YixBpqgDPWn8XO2IDG35411mC60YbB+gq4dbKwKO14bt3g8OjlmDppBlwWwFUJnK4Cc1UBpy1grkrgVCVwygK4qgBXJaaOG/GuXME6udVdGQM8MRW8eWsvAqurAKuvAOLF6o1AXXxfZ8SoaT2C+SvhJ0quYT/RVZ7IMi+ArvK88aF9HNjRcrAjBiBRh39UxFGCwMplqYxnlI+ohyfKmhOAp1TKwk4t2AEdcFAHHCgDDpaBHSrDxNYN4BcvmmEUamtDQt/a25Pf8zwRJxxAK2XhvWrAqQVzlgL7SwGnFpPWopTmn/R6xIaGfgF0dKRKwys4iccG+cQXezGwWw3s4eKrGoEVS38eyEskiPT1IRYMAozhd80CAB/RNUEAPQb5+4EqFeDYCObYCDhKMLpJ/sdhvEQCNjaGVJoNwE8EnkiRFqBbK7vUp89jqC4E21oIVBcimL18BsCk14tYIIAoz4ONjwsC8BO1pgW4QrTEo80dGdy8DsykAjOq0k57uLdXEICP6JmgNtzmcmofaKXhQZ0CUS4vLUCkv19oAsOCABIQ9zW5I6+Uq5iIABAMkGjH0+LsyyIChOYEkJCfKCQGgOAZSJaP6JpICTTMC4AnsogAEJrzfyEphWcZArTO2zyeQpafaCAtwPXr4vU+BQTnJ3qd7lYkm2cUfQqIrHRDmeh5xrGnAVH4iVrjs5G4pqH4vmG2r/4Oe0DU2cmYxtwAAAAASUVORK5CYII=':
return 'away?withChats=1';
/* need base64 image for away?withChats=2 */
case 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAD6ElEQVRYhe2VbUibVxTHL4xRNgaVLlqTxTUZWmpaWWKML1tMoo1xJOnWrWukLXthykqTL1rGqqwD6af5aVj6IV/KSmFCYZldtlm0DZV+yEBWO9ZughhiU9LUl5lEl/cn978PJk+evKjxZYOBfzg8PIfLOb97zrn3ErKrXe3q/6qhgwLejdqy9hu1Ze02GV91mZA9/0niUW1lj1356jObgp8ca6tkbusqmRG1OPy9XBC1N7zy87fS0qp/JfFQg3j/LZXIc0stwuynKkS/OIbExbeR+PIdxC4ew9Jnb+GBSUZt9YKIrbb84x1NPiwVlYy8eSD46/EaxD/Xg/YaQPsMQK8BuLD6pb0GMBf08J1V44dGYXhHIcY04ukJgwRMdxtwXscaPd8O9HB8PW1I9rRjrqsZNoUgsiPtcOoOGe0NQsTPqgGzBjC3AJZWUHMrYNGAmluAcy3AOQ1gbgXMLYh/osSfTSI6It0/um2AOyrx738YJKCdzaBdzUDKaJcS6Ez9dyqxrDoI34F9cBGSa34XId+4CdFsCWC0qSI0/74U9KMm0A8bgbR9sGpRYw2e7HsxK+lTnQ4+vR5uHi/LP0PIXTchJZsCsNfxacQkBz2lAE4rgFP1wOl60DP1CB89BPfzz7EJwg4HEI+Dq/jUFJ5qtVwQt5sQafEAcj6NnJABJjmoqQ7oqANMcsR0kqzk0YkJrKl4HF61mgvxoOhK3G4UhhcNh4F3ZcB70tRXhid7X2ADLpjNAKVsPmZ+HozXm8UQdjhy23GtKIC7jcKp2dYqwHgE1HgEMNZg+XVhVrCg1ZpJ7vWy/tjDh5kiTE/nDaibENGGAGNywVe/NFRQaKtBj1YD2mr4Sl/KCuQfGAANhUBXVrAyNJQBuH+fBYg9elTohPRvCHCZkD12eXlw7o3XQFVVoMqqQoEyu+LxsHz16upMcNqycv163toZQsaLasN30rLjP8n5kTmFCAlpxboAzzo6gGQyewgZJu9Ipu+IogDSED/WlgcnK1+m6wKcPAkwTN5BiNy7V3B90QDpdjgOl369HoCLEPj0eiz19yO5uMgC0HAYHokkd21gUwBpuQgJcAP9PTyMhMeDhMeDpUuXWP9ffX2ZOaAUCxbL1mYgVzOEXOMGik1OsjuNOp2sPzA4uN5lBBch3VsCcBOiya0AV1GnE6GbN7NmIen347FYnFX+Tb8LOVUYZ3tuNAKJRN7gcRW8cmXzd8AGVShxETLLXscWC2golJ85kUDQat2Z3heAkLoI+Y0bfMFiQWBwEEGrFf6BgUJP8vi2Sl8AoiR3KNewwLbLvgGIyEVIf2o20sc0kPrvXmvX/wBYvzAbZYnsEQAAAABJRU5ErkJggg==':
return 'away?withChats=3';
default:
return false;
}
}
function sendXHR(method, newStatus, successCb, errorCb) {
debugLog(method, newStatus);
var oReq = new XMLHttpRequest();
if (successCb instanceof Function) oReq.addEventListener('load', successCb);
if (errorCb instanceof Function) oReq.addEventListener('error', errorCb);
oReq.open(method, 'https://localhost.spacenate.com:4443/' + newStatus, true);
oReq.send();
}
function hashString(string) {
var hash = 0, i, chr, len;
if (string.length === 0) return hash;
for (i = 0, len = string.length; i < len; i++) {
chr = string.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return hash;
}
function unregister() {
debugLog('Disconnecting observers');
var observers = [statusObserver,chatTabObserver,chatListObserver,linkObserver];
for (var i=0; i<observers.length; i++) {
debugLog('Disconnecting', observers[i]);
observers[i].disconnect();
}
return debug;
}
function setDebugMode(bool) {
debug = (bool) ? true : false;
var prefix = (debug) ? "en" : "dis";
return "Debug mode " + prefix + "abled";
}
function debugLog() {
if (debug) {
console.log.apply(console, arguments);
}
}
function createFeedbackElement() {
if ((inner = document.getElementById('olark-observer')) instanceof Object) {
return inner;
}
/* olark-observer-container */
var container = document.createElement('div');
container.id = "olark-observer-container";
container.style.position = "absolute";
container.style.bottom = "18px";
container.style.right = "20px";
/* olark-observer */
var inner = document.createElement('div');
inner.id = "olark-observer";
inner.style.padding = "7px 14px 7px 0";
inner.style.backgroundColor = "rgba(255,255,255,0.1)";
inner.style.borderRadius = "19px";
inner.style.color = "#fff";
inner.style.fontSize = "14px";
inner.style.transition = "transform 1s";
inner.style.transform = "translateY(3em)";
/* status-indicator */
var indicator = document.createElement('span');
indicator.id = "olark-observer-status-indicator";
indicator.style.height = "9px";
indicator.style.width = "9px";
indicator.style.borderRadius = "10px";
indicator.style.float = "right";
indicator.style.position = "relative";
indicator.style.top = "3px";
indicator.style.left = "4px";
indicator.style.backgroundColor = redColor;
/* status-text */
var text = document.createElement('span');
text.id = "olark-observer-status-text";
text.style.float = "right";
text.style.marginRight = "5px";
text.textContent = "Connecting to server...";
inner.appendChild(indicator);
inner.appendChild(text);
container.appendChild(inner);
document.body.appendChild(container);
return inner;
}
function showFeedback(message) {
debugLog(message);
/*
if (!feedbackEl.firstChild) {
var messageEl = document.createElement('span');
messageEl.style.margin = "0.2em";
feedbackEl.appendChild(messageEl);
}
feedbackEl.firstChild.textContent = message;
window.setTimeout(function(){
feedbackEl.style.transform = "translateY(0em)";
}, 0);
window.setTimeout(function(){
feedbackEl.style.transform = "translateY(3em)";
}, 4000);
*/
}
/* Find width of element, then animate on to page
var offScreen = document.createElement('div');
offScreen.style.position = "absolute";
offScreen.style.top = "-100em";
document.body.appendChild(offScreen);
var p = document.createElement('p');
p.textContent = "Some string";
offScreen.appendChild(p);
p.scrollWidth;
*/
/* Start observers observing */
var statusPanelEl = document.querySelector('#op-status-panel'),
activeChatsEl = document.querySelector('#active-chats');
if (statusPanelEl instanceof Object && activeChatsEl instanceof Object) {
statusObserver.observe(statusPanelEl, {childList: true});
chatListObserver.observe(activeChatsEl, { childList: true});
linkObserver.observe(document.querySelector('head'), {childList: true});
showFeedback('Olark Observer loaded!');
} else {
showFeedback('Olark Observer loaded~')
}
return {
send: sendXHR,
unregister: unregister,
setDebugMode: setDebugMode,
showFeedback: showFeedback
};
}(OlarkObserver, document, window));
| bookmarklet/olark-observer.js | var OlarkObserver = (function(OO, document, window) {
'use strict';
var debug = false,
feedbackEl = createFeedbackElement(),
statusObserver,
chatTabObserver,
chatListObserver,
linkObserver;
if (OO instanceof Object) {
// OlarkObserver is already injected
// Debug behavior - unregister old listeners,
// and proceed to load new OlarkObserver object
debug = OO.unregister();
}
/* Operator status changes */
var statusObserver = new MutationObserver(function(mutations) {
// Multiple mutations take place for each status change.
// Only the final mutation is important in determining the new status.
var lastMutation = mutations[mutations.length - 1],
newNodes = lastMutation.addedNodes,
newStatus = false;
// Grab the #status-indicator element, see what class has been assigned to it.
for (var i = 0; i < newNodes.length; i++) {
if (newNodes[i].id === 'status-indicator') {
newStatus = newNodes[i].className;
}
}
if (newStatus) {
sendXHR('PUT', 'status/' + newStatus);
}
})
/* New unread chats */
var chatTabObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// mutation.target is a LIVE element, and mutation callbacks are ASYNC
// so, ensure the tab has not been closed (mutation.target is not null)
if (mutation.type === 'attributes' && mutation.target !== null) {
var displayNameElement = mutation.target.querySelector('.display-name');
if (displayNameElement === null) {
return; // 'continue' with the next forEach, this is a closed chat tab
}
var tabName = hashString(displayNameElement.textContent.trim());
if (mutation.target.classList.contains('unread') && mutation.oldValue.indexOf('unread') === -1) {
// mutation.target just added the unread class
sendXHR('PUT', 'chats/' + tabName + '/1');
} else if (mutation.target.classList.contains('unread') === false && mutation.oldValue.indexOf('unread') !== -1) {
// mutation.target just removed the unread class
sendXHR('PUT', 'chats/' + tabName + '/0');
}
}
});
});
var chatListObserver = new MutationObserver(function(mutations) {
// iterate over mutations to look for new chats (new child added to #active-chats)
mutations.forEach(function(mutation) {
if (mutation.type === 'childList' && mutation.target.id === 'active-chats' && mutation.addedNodes.length > 0) {
sendXHR('PUT', 'chats/new/1')
var newTab = mutation.addedNodes[0];
chatTabObserver.observe(newTab, {attributes: true, attributeOldValue: true});
}
});
});
/* New unread chats, while window is inactive */
var linkObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
// It seems only one element is added for each mutation
var newElement = mutation.addedNodes[0];
// 'continue' with next forEach if the new element is not a link[rel=icon]
if (newElement.rel !== 'icon') {
return;
}
var newStatus = identifyBase64Image(newElement.href);
if (newStatus !== false) {
sendXHR('PUT', 'status/'+newStatus);
} else {
debugLog("Unidentified status icon", newElement.href);
}
}
});
});
// @todo: slim down this list to one base64 image per status
function identifyBase64Image(base64String) {
switch (base64String) {
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADVUlEQVRYhe2TTUwbRxiG5wbyKVWtRCqNWkgIErWlwglziExVxQilUhL10KiqmkpJS5O0BKfGP2t2Zz2xvYvXWmdtfpy4tOql6o/UEz1wS9MmIjQYG8zaBiMc95Arh5gciN8eFnPo1U6lVn6kT9837470vjOjJaRFixb/VSilZp7nHTzPOyilpzVNa/tXjD3Kx+NcaOypIPpeuNWP9ifUD/e9kc+rlPmeCwHXAmOs+6UY+3yXj3GRq0/8kWu4+csJjP9G4PydwPkHwY37BGOLBM5vB2uCyO1ROnmpqeY36LkjfOSLXe/8CFwPCNxLBBOPjO5eIpg46K6HBDd/fQ3+sLPa1BB+9UrR//X78C4TcI8JuD+N7n1MwC0T+OraMoFvmcCz2AlB5Paa8hze+ZGzQsgN/tEr4NPtENImCKsmTKZN4Ffbwafbwa8cVNoEPt2OyRUTvN+/WxNCnoXGTx+/nBV+fA9i5ijErBksa0Yga8yBzFEEsmYEMoYuZow5kHkVwtIbEBn3vOG/Q4hdf8buDSC43nFYofUOBNeMurXWgeD6cUNfO27o6x1g2dchRseqlNLTDQUQw55aOP0WQrlOSBtvQsp1QdroQvigpFwXwrmuf3w7ASnXCXHm032e5x0NBvDW5FUr5I1TkPUeTOndmNK7IeeNWdZPQta7IW+cwpTeA0nvMfbmTyIwM9p4AKaOV+UHdih5C6KFXkTzFigFK6IFC5RCL5SCFZG8BUq+19DyVih5CxTdCiHgf0EpNTd2A/Hrurx4HrHNPqibfYht9hu19TZiW/2Ha7XYZ+wp9kEt9kO5PwIW9TxtyJwQQqjqlMLfjNYS2zbES4NIlGxIlAaQKNkQ37ZhetuGeGkAiW0bput6aRC3brvApq+ONxxA07Q2GvTvag8vYK48hNkdO+Z2hpAsD2Fux45k2Y7Zcn39DpJlOyI/XwFTv3rSsHkdyibO0bB/b3rpA6QqZ3C3cgapyjBSlWHcrQwj9ZcDqYoDd3ZGEPnhGthtz64vOHasaQEOQ4QmdyPffVmL3/sEyfRFpLbOY750AcmVi4gtfAYm+yHNuopUvXSkqeZ1NE1rYzGfFEq69bDmrjKJqzGJqwVnvM+kO85s9KfRsy/FuEWLFv9r/gY+jTpf/0j1VwAAAABJRU5ErkJggg==':
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADU0lEQVRYhe2TPWgbZxzG381GU0pFAnVDayeOwZWg9mSlEORAI2MSSEKHBkqbQkIwrrEdVdHX6T4t3Z11qpST/KFadUqX0lLayR28pWkSHDeWJVs+SbaMFWXI6iFyBkdPh7M8ZD0lkKAfPPz/73MvPM9xHCFNmjR5W2FZ1kzTtIOmaQfLsmdUVW15I8Ee5ZtxShx7xvC+l57o1/vu6Ff7vvBQlRX8LxjBtSAIQudrCfYFrx2jwsNPqPAwnH+dwPg/BDf/Jbh5n2DsHsHoIoHz589qDO/fY9nA1YaGj0UvHqHDI7ve+UG4HhC4lwhuPdKne4ng1sF0PSRw/v0BAqKz2tASVPR6kfrpC3iXCfyPCfz/6dP7mMC/TOCre8sEvmUCz2I7GN6/15DP4Z2/cJ4JuUE/eg90uhVM2gRm1YRA2gR6tRV0uhX0yoHSJtDpVgRWTPD9+nmNCXkWjL99/FqW+f0CuMxRcFkzhKwZfFbf+cxR8Fkz+Izucxl95zPvg1n6CJxAvTD8dzCxkefC3T4E19sOFVpvQ3BN18RaG4Lrx3V/7bjur7dByH4I7ofRKsuyZwwV4ERvTUx/glCuHdLGx5ByHZA2OiAeSMp1QMx1vPLsBKRcO7jpG/s0TTsMFvDV5FUr5I1TkLUuTGqdmNQ6Ief1XdZOQtY6IW+cwqTWBUnr0u/mT4KfHjJeQIiNV+UHdih5CyKFbkTyFigFKyIFC5RCN5SCFeG8BUq+W/fyVih5CxTNClagXrIsazZUgE+MaPLiJcQ2exDd7EFss1fX1qeIbfUenqPFHv1OsQfRYi+Ue4MQIp5nhsIJIYSLfi+Jd4ZqiW0b4qXTSJRsSJT6kCjZEN+2YWrbhnipD4ltG6bqfuk0Jm67IEx9N264gKqqLVyI2lUfXsZsuR8zO3bM7vQjWe7H7I4dybIdM+X6+SySZTvCf1zHRMz1xHB4HVbwXuQkam9q6UukKucwVzmHVGUAqcoA5ioDSD11IFVx4MedQYR/G8bEbc9uMDZ6rGEFDkuIgd3wL6O1+N1vkUxfQWrrEuZLl5FcuYLYwg0IMgVpxlVk71w90tDwOqqqtgRVnyQm3ZoY91QFiaoJElULTXufS3PObOTP4fOvJbhJkybvNP8DXOE67fHe6r8AAAAASUVORK5CYII=':
return 'available';
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADLElEQVRYhe2VW0gUYRiGP4JykwiDqSgvMsOKUsi6qITCggikoKSLIKIuCjoY6oaHPTjz7w7uIZVd1qK6UJcIiiK6KsibskzZtEa3UkunqQyKblwpD9E2bxfuWq0rO+oUBL7w8c8B5n3+9/t+hmhWs5rV/yrGGMfz/G6e53czxrb7fL6kf2JcXn2k2OIo/CTYzD/KPIfDpZ5DYVPVyWEmmkcFe8kdURQz/oqx2XxsqaXq1Htr1Wmcvb0KxQ8JxmaC8TGh6BGhsJFg9Oeogs0ywljFUV3Ni9i+FL7qzKCpPg8lLYSyAKH0ydhaFiCURtaSVsLZu8thdRqHdYWweo6/ttYdgKmNYHlKsLSPraanBEsbwRx91kYwtxHKG1dCsFlGdGmHqT5vj+AoA/9kEXjJAEFKhtCRjAopGXyHAbxkAP8sUlIyeMkAsWk+ais2qU7LmXsz333tsaBwYy9snUtgC3IQgxzswbFre+cS2IMc7J0crooLcH/nPMhEsTUgEzUoRLnTAhC8BUNi0xZUvkgdL8eLVFQ+H6sLNxejfe3ceMYTqo/ovkKUMiUAm7NcdUrr4Xi5Eq6uNLhepsPVlQ5nVzrq/MvQs3DOBKOQ14uovly7FvteUYg2TAHApLo7suDuWg139xqc687Aue4MXL69Iq75h82bEf78+RfA9evx0pA0JyF6iofdLbmo7slEzat1qOnJRPWrLDxbaxj/oMJxGG1tRfjjR0BV8bsmAUAfkV9bArUF3e7G/fD2ZsPTmw1v70bccq3442MKx0H9+hXxNBmATASFKC0hAPMYXc6GE+r5N1tRK+fgvLwVLbsWTQD4JkkI9/fju6JAHRrSBCATsYQAPp8viVVaB32t+bj0bgcuvs1NOO0jzc2aAPqIHmhqAxNL9zGndeRC4CCutmxLCDAaCGhNYEATwDiEo2LQX56v6ggAzQDRdtSw0x4dAUJTAohKJgrpAaB5BmLVR+TXKYGiaQEoRLk6AISm/F+ISeHBDAHYtM0jKaTIRG8TAly5ol/v40BskIk6Ep2KWPMZRR8HIiXRUEZ7PuPYE4CkyUQsMhvRYxqK3BdNtuuf8bvc+Hczj/wAAAAASUVORK5CYII=':
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADLElEQVRYhe2VW0gUYRiGP4JykwiFySgvMsOKMtAIyqKwIIQo6HTRRVQXdREirW2me5qZnUF3N5VdVqO6qJYIiiK6KsibTqZspqNbuppO0wkMb1opD9E2bxfuWq0rO+oUBL7w8c8B5n3+9/t+hmhWs5rV/yqe5xmWZYtYli3ieX6bz+dL+SfGFTVHS21O4ydOsPyo8ByJlHsORyzVJ4d50TrKiWX3RFHM+SvGlsrji23Vxe9t1cUw3V2B0ieE042E088IxqeEUw0Ek3+LygnWEZ63H9PV3OjZm8ZWlwyar+xCWROhPEA4+3xsLQ8QzkbXsmaC6f5S2J2mYV0hbJ4Tr22XD8LcQrC2EqwvxlZzK8HaQrDEnrUQLC2Eiobl4ATriC7tMF/Zs5urKgf7PB2sZAAnpYJrT4VdSgXbbgArGcC2RUtKBSsZID6ejzr7BtVpLXkw893XHQ9yt/bA0ZEBR5CBGGQgBMeuhY4MCEEGQgeD6+ICPNwxDzJRfH2Wia4qRIXTAuC8JUPi402ofJU5XlWvMlH5cqzO316EF6vnJjKeUH1EDxWitCkBOJxm1SmtRVXncri6suDqzIarKxvOrmxc9i9B98I5E4zCXi9i+nLjRvx7RSHKmwKARXW3r4O7ayXcoVU4F8rBuVAOLt1dltD848aNiAwM/AK4eTNRGpLmJERv6bC7qRA13bmo7VmD2u5c1PSsQ9tqw/gHFYbBaHMzIv39gKrid00CgD4ivyYAob4k5G7YB29vPjy9+fD2rscd17I/PqYwDNSvX5FIkwHIRFCIspK3wHPG5bx6Uq1/U4A6eTPq5QI07UyfAPBNkhD58AHfFQXq0JAmAJmITwrg8/lSHFW2QV/zflx8tx0X3hYmnfaRxkZNAH1EjzS1gRfNex0u28j5wCFcb9qaFGA0ENCawGdNAOMQTvugv+KAqiMANAPE2uERij06AoSnBBCTTBTWA0DzDMSrj8ivUwLGaQEoRIU6AISn/F+IS+HRDAH4aZtHU0iTid4mBbh2Tb/eJ4DIk4nak52KePMZRZ8AIi3ZUMZ6PuPYk4BkyUR8dDZixzQcvTdOtuufuk3dRfHDbRAAAAAASUVORK5CYII=':
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADIklEQVRYhe2VW0gUcRTGTw+xi09Zk1E9mIYGlQ8GUUmFPQVSkFFYRNiDQRejdcPLXpyZ3cW9eGmX1S4vXShIKcIeKkiIrCzZzEY3XdOdzcrA8CUldY22+XpQ07bVHXUqAj84nGEY5vv9v3OYIZrXvOb1v4rneYZl2Z0sy+7keX672+1W/RXjovLsPIP19CfOpP9e6DwcKnAeCunKjg/zFv0IZ86/Z7FYkv6IsV6fs8xQduKDsewkztSuRt4TgraBoH1G0DwlnK4jaK+mSZzJEOT54iOKmmv4PYvYslMDussZyH9OKPQQCl6M9kIPoWCs5zcSztxfAaNNO6wohNF5tMt4aR90TQRDM8HwcrTrmgmGJoJ+/F4TQd9EKKpLAGcyBBUZh+5yxi7OWgj2RSxYQQ1OiAHXEoNiIQZsixqsoAb7aqyEGLCCGva7atw4nCyVa3Iezv30lTle7uZumFrjYPIysHgZmL2j1+bWOJi9DMytDB5kqvCaWYAAUXhJIpE/QKSZFQDnyh2yPN6MkraVP8vathIlr0fremksulS/mUYskeizjyh+RgAmW5FkE9bB2p4Au28V7O2JsPsSYfMl4nbR4ohG/S4XxvWlujoc4ptIlDUDAJ3kaEmBw5cMR8calHYkobQjCTfOLo9o/nHTJoT6+iYAamoiPTcsOwmLM2/Y8Twd5W/Wo6JzLSrerEd5Zwq6VBPz7mYYjDQ2ItTbC0gSJmsKAPiJRHkJVOZ2OOoy4fKnwulPhcu/AY/2L/nlZd0MA2lwEJE0FUCACJ1EW6MC8E6t3XblmFT1dgsqA2moCmxB+9KFvwF8FQSEenrwrbsb0tCQLACRqD4qgNvtVvElxgF3415cfL8DF96lR932YEODXIB+WWPgLQV7eJsxeM5zALdub4wKMOLxyAIIEEmyAH5CWIsH7hzcJikIANkA4+O4oM0+/88AxqUUgOwdCJefSFQIoHa2CWiUAJjxf2GyRKL+uQDI+gZMJx9RfIAoFBXg2jXlZh8hhSyRKBhtKcPN5xR9uHxE8dGWUrHYp1Mn0VaRqD58N0SifpGodqpT/wCWW+EolsF5jAAAAABJRU5ErkJggg==':
return 'available?withChats=1';
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADyklEQVRYhe1VXWxTZRh+Y6LUxZiRHDHKBWNmSiYQ0BshUaZBSBZNkEgwWUQvMJmWha5kP/3Z+enJ+kO3dOkgzgugF3DjYriaxN0w/BkZA9pV2IbtsQwjK6lhW5S2G915vFh31nPa2nabJiZ7kzff6Zv0e57zvO/zHqK1WIu1+L8Gz/MMy7L7WZbdz/P8W16vd91/Atza8UmjxX48ygnm+RbPx6lmT13K5P48zovmJGdr6hNFsepfATabjz5vcX9xz+rW48TFl9D4PcH4I8H4E8HwA+F4P8Ho2y1zgiXB822friq4gT9QzrobZkxna9E0SGgZIjRfWzhbhgjN6bPpKuHEty/C6jDGV5WE1fPZL9YzH8I0TLDcIFiuL5ymGwTLMMG8WBsmmIcJrf2bwQmWxKq0w3S29j3O3gL22nqwfh04fxm4QBna/GVgAzqwfh3Ym+n0l4H16yBeeRrdba/LDkvDdyt/++6jQe7r9yGMbIAQZCAGGdiCC8+2kQ2wBRnYRhicF5/B5XeegkSkzSmJ6FyEqGZZBLiuY4/EK2+g/dZGJe23NqL954U83fscrm95UgV6f98+TNbWIsIwqnqY6HKEqLwkAoKjVXb4X4X99mY4RyvgvF0J52glHKOVOON7AePPPqEAxC9dghyPIzMeh8OIHj6cSSQSIdpRAgGT7Apsg2v0ZbjGXsHJsSqcHKvCVxc3qcATAwPIG/PziNXXZ5LwF62E6GmMuwZr0DG+FZ13qtE5vhUdd7bh5hadcmH00CEglVoCnJ1FanJSxSEVjapaEibyFadA97ExV/8H6ArthCe0E12h1/CNc5Oqt9NerwIkJxL4fc8eSET4q7d3qR6P4151tep/EaKKggR4j9HpOFcvn/p1F7ql3Tgl7cLgu+tVF8309ChAc6GQUo/p9YAsK214cOSI1iF8QQJer3cd326d8V49iJ6Jt/Hl3Zosq93fuxcPBQEPBQGxhgal/qivT6XMb9u3a10xUFQbeLH5AO+wJk4PfYTzg2/m8npWZsoPAI8nJnLuiKIIKCTsbTO+1oPyPwFHGAazgUCWC3LID4kIRRNYbEcnr/fkA4/p9ZCTSTX43Bz+MBjyEZ4uicBiSETT2suyrJheQtq+L2sGtBEm8mllT0WjS8iyjD8vXChmVgzLIhAhqlHtAbc7e/lNTUFOJpcykcCDujqV/CV/FzQqDOSyW96QZcT0+tJ2QAEVyiWiuwW/AzmcsOze5yCxQyIKFLMXMgdvRdLnIFGuHcp8llux7AWIVEhEfHo2Fm06nf5tyPfWfwPcuzdCV3S+YgAAAABJRU5ErkJggg==':
return 'available?withChats=2';
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAD+UlEQVRYhe2VXUibZxTHD4OtmYxhIevoelF1uBXXQrverIWtbnQtBAddWelgjO2ig820VFP8yIdv3uTFfFQlGi3LLmxDKb3YGPZmgwlS67YUtRqN1lg1SxtIW2rXJHOJmo/3v4uYN59q/Nhg4B8OT3J4OOf3nHOe5yXa0pa29H8Vy7JihmGOMwxznGXZ98xm87b/JHF98xfVSt35x2qNIlZn+jxaa/osKm/6JsRyigW1tuYnjuNK/5XECsWZV5VNlR5VkxQXul5HdR9B9htB9juh6lfC+W6CzHqYV2uU8yzb8OWmJq9iTxQyTecC8ssS1NgIdf2E2oH4WtdPqF1aa24TLvz8GlR6WWhTIVSmr6ZUnZ9APkhQDhGUd+KrfIigHCQoEr5BgmKQUN9dDLVGOb8p7ZBfllSodXVgBraDsYugthdAPVKABnsBmBERGLsIzPCS2QvA2EXgbr2I9oaDvF557peNn779jEP9/UfQjO6AxiEG5xBD64j/1o7ugNYhhnZUjGvcS7j5wQtwEWWaz0V0xU1Uvi4AdevZIHfrHTSO7xJMN74LjWNxu/TDK7iz5/m0pA+PHcMjiQRusTjNP0N0001UuCYAjb6e19vfgu5uMQwTRTDcLYFhogT6iRJ0Wndi8uXnhAShnh4gHEaqwk4nHh49mgridhPtXwOAnDeO7INx4g0YnW/iorMUF52l+K5rd1ryhYEBLKtwGN4jR1Ih7HlXgjNVh4y2cjRP7kXLvTK0TO5F8719GN4jEgLOVlYCPC/kiz55gqjXm8YQ6unJbIc1vwq0n3Uauz9G6/QBmKYPoHX6bfxo2J0WLGCxJJN7vYJ/cWwsWYSpqawBdRMVrQrAmmQG/ZWv+Y4/DqHddRgdrkOwfbg9LZDPaAQfDIKfm8Pc9etJgKEhAWBxfDzXDWFXBTCbzdvYRlXAfPskLA/ex7f3y3MFSp5KLMZfnZ3xmUhpy9zVq1l7Z4h682oDy9WeYPWq+Uv9n+Ka7d0VAR6fPg3EYulDGI1mXcnEG5EXgAChawhY60/yKwKcOgVEo1kXYb6vL+f+vAES7WhhpaaVAFxEeCSR4BnLIvb0qQDAh0LwlJVl7vWvCSAhF5E/NdDfXV2IeDyIeDx4ptUK/j/l8uQc8DxmpdL1zUCmZoisqYEWh4eFky7YbILf39a20mMEF1HVugDcROWZFUjVgs2G4I0babMQ8/nwoLg4rfxr/i5kVKFX6HlFBRCJZA1eqgIdHWt/A1apQqGL6L7wHEul4IPB7MyRCAIWy+b0PgfEfhfRSGrwWakU/rY2BCwW+IzGXJ/k3g2VPgdEYeZQLmP+DZd9FZAiFxG7NBuJa+pf+l+13Kn/Ac86ODo4iC2XAAAAAElFTkSuQmCC':
return 'available?withChats=3';
case 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADPElEQVRYhe2T32tTZxzGz12Fk5PE0zbRBFJoT5tmZth6ck7SE82vTnM2XFq2dDOllaYX6Ryt4FpEK+qt173zD8hopa1Wkord1TaGbGOMeSPkzk6lV8PM9rzfQM3jxUn1DzhxMMkHXp73eXjheeBwOK5Fixb/V27LQkdR5dNFlU8XlUOxJYlr+0+Ky2eOXlqPizvLYeF1OX1kf1M/sr+RdBkrqkCrmqNcDLf1vpfi74dd7o1Ex/b9ZCcq38j493oKezeGsXfzE7y6kcLO5VP47Zy/vhwR2B1FmGpq+d2E07kRE6uPvujG7pU4aDEBuhZHbTGO2tUEaosJ0GIcxtUYnl4IYVVzGk0dURrurPzyuQ/Gd0OoLWioLZhKC1HU5rV32bwGNh/F34VBLEcE1pTP8fNn3rNrmgO738qguRBoTgFdVEFzKuhiw88qoNmQmc0pMGZV/DHSVV+N2MuWBzxIdD7+M+MDKwyCzQyAZgZAM4NgM8dBhUHTF8ycFRr3wnH8Mx3EHcVGlv+O0klx79nXEth0ECwfBOWDoPwx0JR5WD4INh0ETQdB+Y9BU+YbY+oYSidFo6gcilkasBYW6i9zfWAT/aDJftBEADQZADsfAJsMvPU02d/QAOj8R6CJfmwlxP2iyqetDVCF+suvekC5XrCcHzTeB8r1gcb9De01NdcHyvnBxv1gjfxh7LD1AWXNabzI+EBZCTTW3VAJNNYDNtYNGpPAsj1g2W4zy0qgrATjSwkriu31bVnosDTgoXb4SeW0GzTiAxvxgUa6zDPqA4027pkusEyX+SZj+qe6B/fC9h1L5RzHcSXVcetHzVEn3QuW9oJ0D0j3gOleMN0D+vRAPaC0B6R7YegelIcceBCxX7I8YEni2lZVW3U71g6WcoElXKCkG5RygyU7QUkXWMr0Zu7C71Enyqp923L5ASuyMLqu8mx7SARFRTBNBGntoGg7SOsARUWQJmI3KuJRxIGSKlQ3wry7aQPejlBs1Z9CtnpFteO5Ykc15EBVdeCZYsdfih3rig1bslC5O8A5m1p+wJLEtZVk/taWbHuyGeKNtRBfXwvx9U2Z3/tB5h//ekI4+16KW7Ro8UHzBoGVChwxHE8wAAAAAElFTkSuQmCC':
return 'away';
case 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAADHUlEQVRYhe2V7UtTYRjGb4iIIkhqmlszZ2yRmnS2OTdrbtN0i7bKXlhU9EJK0fqiEWlk4Me+Jf0DRVAatKJVhlbYB0mMaBFUEBtHWrCUyGnqppvP1Ye2XuZkR3cKAi+4eXjOgef6neu+Hw7Rgha0oP9VN9fLJLc0ObZbmhybWy01XSFa8k+Mu6qVjR7j2s9unXS6u0YZe2xVxjrNBRN3tLKIR7/m4Q0uW/VXjG/qC1Y/Mik+PjIrMHDChMiFHYi27ET04i5MtuzA17Pb4HWqmbtMFnZrco+Jan6XU2R1bskfeVlbgqlz28Ga7WDn7UCzHWj6sbJmO2JN2xE8acY9g3xCVIhuS8GHF/YixBpqgDPWn8XO2IDG35411mC60YbB+gq4dbKwKO14bt3g8OjlmDppBlwWwFUJnK4Cc1UBpy1grkrgVCVwygK4qgBXJaaOG/GuXME6udVdGQM8MRW8eWsvAqurAKuvAOLF6o1AXXxfZ8SoaT2C+SvhJ0quYT/RVZ7IMi+ArvK88aF9HNjRcrAjBiBRh39UxFGCwMplqYxnlI+ohyfKmhOAp1TKwk4t2AEdcFAHHCgDDpaBHSrDxNYN4BcvmmEUamtDQt/a25Pf8zwRJxxAK2XhvWrAqQVzlgL7SwGnFpPWopTmn/R6xIaGfgF0dKRKwys4iccG+cQXezGwWw3s4eKrGoEVS38eyEskiPT1IRYMAozhd80CAB/RNUEAPQb5+4EqFeDYCObYCDhKMLpJ/sdhvEQCNjaGVJoNwE8EnkiRFqBbK7vUp89jqC4E21oIVBcimL18BsCk14tYIIAoz4ONjwsC8BO1pgW4QrTEo80dGdy8DsykAjOq0k57uLdXEICP6JmgNtzmcmofaKXhQZ0CUS4vLUCkv19oAsOCABIQ9zW5I6+Uq5iIABAMkGjH0+LsyyIChOYEkJCfKCQGgOAZSJaP6JpICTTMC4AnsogAEJrzfyEphWcZArTO2zyeQpafaCAtwPXr4vU+BQTnJ3qd7lYkm2cUfQqIrHRDmeh5xrGnAVH4iVrjs5G4pqH4vmG2r/4Oe0DU2cmYxtwAAAAASUVORK5CYII=':
return 'away?withChats=1';
/* need base64 image for away?withChats=2 */
case 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAD6ElEQVRYhe2VbUibVxTHL4xRNgaVLlqTxTUZWmpaWWKML1tMoo1xJOnWrWukLXthykqTL1rGqqwD6af5aVj6IV/KSmFCYZldtlm0DZV+yEBWO9ZughhiU9LUl5lEl/cn978PJk+evKjxZYOBfzg8PIfLOb97zrn3ErKrXe3q/6qhgwLejdqy9hu1Ze02GV91mZA9/0niUW1lj1356jObgp8ca6tkbusqmRG1OPy9XBC1N7zy87fS0qp/JfFQg3j/LZXIc0stwuynKkS/OIbExbeR+PIdxC4ew9Jnb+GBSUZt9YKIrbb84x1NPiwVlYy8eSD46/EaxD/Xg/YaQPsMQK8BuLD6pb0GMBf08J1V44dGYXhHIcY04ukJgwRMdxtwXscaPd8O9HB8PW1I9rRjrqsZNoUgsiPtcOoOGe0NQsTPqgGzBjC3AJZWUHMrYNGAmluAcy3AOQ1gbgXMLYh/osSfTSI6It0/um2AOyrx738YJKCdzaBdzUDKaJcS6Ez9dyqxrDoI34F9cBGSa34XId+4CdFsCWC0qSI0/74U9KMm0A8bgbR9sGpRYw2e7HsxK+lTnQ4+vR5uHi/LP0PIXTchJZsCsNfxacQkBz2lAE4rgFP1wOl60DP1CB89BPfzz7EJwg4HEI+Dq/jUFJ5qtVwQt5sQafEAcj6NnJABJjmoqQ7oqANMcsR0kqzk0YkJrKl4HF61mgvxoOhK3G4UhhcNh4F3ZcB70tRXhid7X2ADLpjNAKVsPmZ+HozXm8UQdjhy23GtKIC7jcKp2dYqwHgE1HgEMNZg+XVhVrCg1ZpJ7vWy/tjDh5kiTE/nDaibENGGAGNywVe/NFRQaKtBj1YD2mr4Sl/KCuQfGAANhUBXVrAyNJQBuH+fBYg9elTohPRvCHCZkD12eXlw7o3XQFVVoMqqQoEyu+LxsHz16upMcNqycv163toZQsaLasN30rLjP8n5kTmFCAlpxboAzzo6gGQyewgZJu9Ipu+IogDSED/WlgcnK1+m6wKcPAkwTN5BiNy7V3B90QDpdjgOl369HoCLEPj0eiz19yO5uMgC0HAYHokkd21gUwBpuQgJcAP9PTyMhMeDhMeDpUuXWP9ffX2ZOaAUCxbL1mYgVzOEXOMGik1OsjuNOp2sPzA4uN5lBBch3VsCcBOiya0AV1GnE6GbN7NmIen347FYnFX+Tb8LOVUYZ3tuNAKJRN7gcRW8cmXzd8AGVShxETLLXscWC2golJ85kUDQat2Z3heAkLoI+Y0bfMFiQWBwEEGrFf6BgUJP8vi2Sl8AoiR3KNewwLbLvgGIyEVIf2o20sc0kPrvXmvX/wBYvzAbZYnsEQAAAABJRU5ErkJggg==':
return 'away?withChats=3';
default:
return false;
}
}
function sendXHR(method, newStatus, successCb, errorCb) {
debugLog(method, newStatus);
var oReq = new XMLHttpRequest();
if (successCb instanceof Function) oReq.addEventListener('load', successCb);
if (errorCb instanceof Function) oReq.addEventListener('error', errorCb);
oReq.open(method, 'https://localhost.spacenate.com:4443/' + newStatus, true);
oReq.send();
}
function hashString(string) {
var hash = 0, i, chr, len;
if (string.length === 0) return hash;
for (i = 0, len = string.length; i < len; i++) {
chr = string.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return hash;
}
function unregister() {
debugLog('Disconnecting observers');
var observers = [statusObserver,chatTabObserver,chatListObserver,linkObserver];
for (var i=0; i<observers.length; i++) {
debugLog('Disconnecting', observers[i]);
observers[i].disconnect();
}
return debug;
}
function setDebugMode(bool) {
debug = (bool) ? true : false;
var prefix = (debug) ? "en" : "dis";
return "Debug mode " + prefix + "abled";
}
function debugLog() {
if (debug) {
console.log.apply(console, arguments);
}
}
function createFeedbackElement() {
if ((inner = document.getElementById('olark-observer')) instanceof Object) {
return inner;
}
/* olark-observer-container */
var container = document.createElement('div');
container.id = "olark-observer-container";
container.style.position = "absolute";
container.style.bottom = "18px";
container.style.right = "20px";
/* olark-observer */
var inner = document.createElement('div');
inner.id = "olark-observer";
inner.style.padding = "7px 0 7px 14px";
inner.style.backgroundColor = "rgba(255,255,255,0.1)";
inner.style.borderRadius = "19px";
inner.style.color = "#fff";
inner.style.fontSize = "14px";
inner.style.transition = "transform 1s";
inner.style.transform = "translateY(3em)";
/* status-indicator */
var indicator = document.createElement('span');
indicator.id = "olark-observer-status-indicator";
indicator.style.height = "9px";
indicator.style.width = "9px";
indicator.style.borderRadius = "10px";
indicator.style.float = "right";
indicator.style.position = "relative";
indicator.style.top = "3px";
indicator.style.left = "4px";
indicator.style.backgroundColor = "#aaa";
/* status-text */
var text = document.createElement('span');
text.id = "olark-observer-status-text";
text.style.float = "right";
text.style.marginRight = "5px";
text.textContent = "Connecting to server...";
inner.appendChild(indicator);
inner.appendChild(text);
container.appendChild(inner);
document.body.appendChild(container);
return inner;
}
function showFeedback(message) {
debugLog(message);
/*
if (!feedbackEl.firstChild) {
var messageEl = document.createElement('span');
messageEl.style.margin = "0.2em";
feedbackEl.appendChild(messageEl);
}
feedbackEl.firstChild.textContent = message;
window.setTimeout(function(){
feedbackEl.style.transform = "translateY(0em)";
}, 0);
window.setTimeout(function(){
feedbackEl.style.transform = "translateY(3em)";
}, 4000);
*/
}
/* Find width of element, then animate on to page
var offScreen = document.createElement('div');
offScreen.style.position = "absolute";
offScreen.style.top = "-100em";
document.body.appendChild(offScreen);
var p = document.createElement('p');
p.textContent = "Some string";
offScreen.appendChild(p);
p.scrollWidth;
*/
/* Start observers observing */
var statusPanelEl = document.querySelector('#op-status-panel'),
activeChatsEl = document.querySelector('#active-chats');
if (statusPanelEl instanceof Object && activeChatsEl instanceof Object) {
statusObserver.observe(statusPanelEl, {childList: true});
chatListObserver.observe(activeChatsEl, { childList: true});
linkObserver.observe(document.querySelector('head'), {childList: true});
showFeedback('Olark Observer loaded!');
} else {
showFeedback('Olark Observer loaded~')
}
return {
send: sendXHR,
unregister: unregister,
setDebugMode: setDebugMode,
showFeedback: showFeedback
};
}(OlarkObserver, document, window));
| Flip padding on #olark-observer
| bookmarklet/olark-observer.js | Flip padding on #olark-observer | <ide><path>ookmarklet/olark-observer.js
<ide> statusObserver,
<ide> chatTabObserver,
<ide> chatListObserver,
<del> linkObserver;
<add> linkObserver,
<add> redColor = "#d65129",
<add> yellowColor = "#f9cb32",
<add> greenColor = "#88de68";
<add>
<ide>
<ide> if (OO instanceof Object) {
<ide> // OlarkObserver is already injected
<ide> /* olark-observer */
<ide> var inner = document.createElement('div');
<ide> inner.id = "olark-observer";
<del> inner.style.padding = "7px 0 7px 14px";
<add> inner.style.padding = "7px 14px 7px 0";
<ide> inner.style.backgroundColor = "rgba(255,255,255,0.1)";
<ide> inner.style.borderRadius = "19px";
<ide> inner.style.color = "#fff";
<ide> indicator.style.position = "relative";
<ide> indicator.style.top = "3px";
<ide> indicator.style.left = "4px";
<del> indicator.style.backgroundColor = "#aaa";
<add> indicator.style.backgroundColor = redColor;
<ide> /* status-text */
<ide> var text = document.createElement('span');
<ide> text.id = "olark-observer-status-text"; |
|
Java | mit | 3198cc4f8e175aeedd323d133e73297c778a4977 | 0 | MrCreosote/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe,MrCreosote/workspace_deluxe,kbase/workspace_deluxe,kbase/workspace_deluxe,kbase/workspace_deluxe,MrCreosote/workspace_deluxe | package us.kbase.workspace.database.mongo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.jongo.FindAndModify;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.jongo.marshall.MarshallingException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import us.kbase.common.mongo.GetMongoDB;
import us.kbase.common.mongo.exceptions.InvalidHostException;
import us.kbase.common.mongo.exceptions.MongoAuthException;
import us.kbase.typedobj.core.AbsoluteTypeDefId;
import us.kbase.typedobj.core.MD5;
import us.kbase.typedobj.core.ObjectPaths;
import us.kbase.typedobj.core.TypeDefId;
import us.kbase.typedobj.core.TypeDefName;
import us.kbase.typedobj.core.TypedObjectExtractor;
import us.kbase.typedobj.core.TypedObjectValidator;
import us.kbase.typedobj.db.MongoTypeStorage;
import us.kbase.typedobj.db.TypeDefinitionDB;
import us.kbase.typedobj.exceptions.TypeStorageException;
import us.kbase.typedobj.exceptions.TypedObjectExtractionException;
import us.kbase.typedobj.tests.DummyTypedObjectValidationReport;
import us.kbase.workspace.database.AllUsers;
import us.kbase.workspace.database.ObjectIDNoWSNoVer;
import us.kbase.workspace.database.ObjectIDResolvedWS;
import us.kbase.workspace.database.ObjectInformation;
import us.kbase.workspace.database.Permission;
import us.kbase.workspace.database.PermissionSet;
import us.kbase.workspace.database.Provenance;
import us.kbase.workspace.database.Reference;
import us.kbase.workspace.database.ResolvedWorkspaceID;
import us.kbase.workspace.database.TypeAndReference;
import us.kbase.workspace.database.User;
import us.kbase.workspace.database.WorkspaceDatabase;
import us.kbase.workspace.database.WorkspaceIdentifier;
import us.kbase.workspace.database.WorkspaceInformation;
import us.kbase.workspace.database.WorkspaceObjectData;
import us.kbase.workspace.database.WorkspaceUser;
import us.kbase.workspace.database.exceptions.CorruptWorkspaceDBException;
import us.kbase.workspace.database.exceptions.DBAuthorizationException;
import us.kbase.workspace.database.exceptions.NoSuchObjectException;
import us.kbase.workspace.database.exceptions.NoSuchWorkspaceException;
import us.kbase.workspace.database.exceptions.PreExistingWorkspaceException;
import us.kbase.workspace.database.exceptions.UninitializedWorkspaceDBException;
import us.kbase.workspace.database.exceptions.WorkspaceCommunicationException;
import us.kbase.workspace.database.exceptions.WorkspaceDBException;
import us.kbase.workspace.database.exceptions.WorkspaceDBInitializationException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreAuthorizationException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreCommunicationException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreException;
import us.kbase.workspace.database.mongo.exceptions.NoSuchBlobException;
import us.kbase.workspace.kbase.Util;
import us.kbase.workspace.lib.ResolvedSaveObject;
import us.kbase.workspace.lib.WorkspaceSaveObject;
import us.kbase.workspace.test.WorkspaceTestCommon;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
@RunWith(Enclosed.class)
public class MongoWorkspaceDB implements WorkspaceDatabase {
//TODO query user metadata
//TODO save set of objects with same provenance if they were generated by same fn
private static final String COL_ADMINS = "admins";
private static final String COL_SETTINGS = "settings";
private static final String COL_WS_CNT = "workspaceCounter";
private static final String COL_WORKSPACES = "workspaces";
private static final String COL_WS_ACLS = "workspaceACLs";
private static final String COL_WORKSPACE_OBJS = "workspaceObjects";
private static final String COL_WORKSPACE_VERS = "workspaceObjVersions";
private static final String COL_PROVENANCE = "provenance";
private static final String COL_SHOCK_PREFIX = "shock_";
private static final User ALL_USERS = new AllUsers('*');
private static final long MAX_OBJECT_SIZE = 200005000;
private static final long MAX_SUBDATA_SIZE = 15000000;
private static final long MAX_PROV_SIZE = 1000000;
private final DB wsmongo;
private final Jongo wsjongo;
private final BlobStore blob;
private final QueryMethods query;
private final FindAndModify updateWScounter;
private final TypedObjectValidator typeValidator;
private final Set<String> typeIndexEnsured = new HashSet<String>();
//TODO constants class
private static final Map<String, Map<List<String>, List<String>>> INDEXES;
private static final String IDX_UNIQ = "unique";
private static final String IDX_SPARSE = "sparse";
static {
//hardcoded indexes
INDEXES = new HashMap<String, Map<List<String>, List<String>>>();
//workspaces indexes
Map<List<String>, List<String>> ws = new HashMap<List<String>, List<String>>();
//find workspaces you own
ws.put(Arrays.asList(Fields.WS_OWNER), Arrays.asList(""));
//find workspaces by permanent id
ws.put(Arrays.asList(Fields.WS_ID), Arrays.asList(IDX_UNIQ));
//find workspaces by mutable name
ws.put(Arrays.asList(Fields.WS_NAME), Arrays.asList(IDX_UNIQ));
INDEXES.put(COL_WORKSPACES, ws);
//workspace acl indexes
Map<List<String>, List<String>> wsACL = new HashMap<List<String>, List<String>>();
//get a user's permission for a workspace, index covers queries
wsACL.put(Arrays.asList(Fields.ACL_WSID, Fields.ACL_USER, Fields.ACL_PERM), Arrays.asList(IDX_UNIQ));
//find workspaces to which a user has some level of permission, index coves queries
wsACL.put(Arrays.asList(Fields.ACL_USER, Fields.ACL_PERM, Fields.ACL_WSID), Arrays.asList(""));
INDEXES.put(COL_WS_ACLS, wsACL);
//workspace object indexes
Map<List<String>, List<String>> wsObj = new HashMap<List<String>, List<String>>();
//find objects by workspace id & name
wsObj.put(Arrays.asList(Fields.OBJ_WS_ID, Fields.OBJ_NAME), Arrays.asList(IDX_UNIQ));
//find object by workspace id & object id
wsObj.put(Arrays.asList(Fields.OBJ_WS_ID, Fields.OBJ_ID), Arrays.asList(IDX_UNIQ));
//find recently modified objects
wsObj.put(Arrays.asList(Fields.OBJ_MODDATE), Arrays.asList(""));
//find object to garbage collect
wsObj.put(Arrays.asList(Fields.OBJ_DEL, Fields.OBJ_REFCOUNTS), Arrays.asList(""));
INDEXES.put(COL_WORKSPACE_OBJS, wsObj);
//workspace object version indexes
Map<List<String>, List<String>> wsVer = new HashMap<List<String>, List<String>>();
//find versions
wsVer.put(Arrays.asList(Fields.VER_WS_ID, Fields.VER_ID,
Fields.VER_VER), Arrays.asList(IDX_UNIQ));
//find versions by data object
wsVer.put(Arrays.asList(Fields.VER_TYPE, Fields.VER_CHKSUM), Arrays.asList(""));
//determine whether a particular object is referenced by this object
wsVer.put(Arrays.asList(Fields.VER_REF), Arrays.asList(IDX_SPARSE));
//determine whether a particular object is included in this object's provenance
wsVer.put(Arrays.asList(Fields.VER_PROVREF), Arrays.asList(IDX_SPARSE));
//find objects that have the same provenance
wsVer.put(Arrays.asList(Fields.VER_PROV), Arrays.asList(""));
//find objects by saved date
wsVer.put(Arrays.asList(Fields.VER_SAVEDATE), Arrays.asList(""));
//find objects by metadata
wsVer.put(Arrays.asList(Fields.VER_META), Arrays.asList(IDX_SPARSE));
INDEXES.put(COL_WORKSPACE_VERS, wsVer);
//no indexes needed for provenance since all lookups are by _id
//admin indexes
Map<List<String>, List<String>> admin = new HashMap<List<String>, List<String>>();
//find admins by name
admin.put(Arrays.asList(Fields.ADMIN_NAME), Arrays.asList(IDX_UNIQ));
INDEXES.put(COL_ADMINS, admin);
}
public MongoWorkspaceDB(final String host, final String database,
final String backendSecret)
throws UnknownHostException, IOException, InvalidHostException,
WorkspaceDBException, TypeStorageException {
wsmongo = GetMongoDB.getDB(host, database);
wsjongo = new Jongo(wsmongo);
query = new QueryMethods(wsmongo, (AllUsers) ALL_USERS, COL_WORKSPACES,
COL_WORKSPACE_OBJS, COL_WORKSPACE_VERS, COL_WS_ACLS);
final Settings settings = getSettings();
blob = setupBlobStore(settings, backendSecret);
updateWScounter = buildCounterQuery(wsjongo);
//TODO check a few random types and make sure they exist
this.typeValidator = new TypedObjectValidator(
new TypeDefinitionDB(
new MongoTypeStorage(
GetMongoDB.getDB(host, settings.getTypeDatabase()))));
ensureIndexes();
ensureTypeIndexes();
}
public MongoWorkspaceDB(final String host, final String database,
final String backendSecret, final String user,
final String password)
throws UnknownHostException, WorkspaceDBException,
TypeStorageException, IOException, InvalidHostException,
MongoAuthException {
wsmongo = GetMongoDB.getDB(host, database, user, password);
wsjongo = new Jongo(wsmongo);
query = new QueryMethods(wsmongo, (AllUsers) ALL_USERS, COL_WORKSPACES,
COL_WORKSPACE_OBJS, COL_WORKSPACE_VERS, COL_WS_ACLS);
final Settings settings = getSettings();
blob = setupBlobStore(settings, backendSecret);
updateWScounter = buildCounterQuery(wsjongo);
this.typeValidator = new TypedObjectValidator(
new TypeDefinitionDB(
new MongoTypeStorage(
GetMongoDB.getDB(host, settings.getTypeDatabase(),
user, password))));
ensureIndexes();
ensureTypeIndexes();
}
//test constructor - runs both the java and perl type compilers
public MongoWorkspaceDB(final String host, final String database,
final String backendSecret, final String user,
final String password, final String kidlpath,
final String typeDBdir)
throws UnknownHostException, IOException,
WorkspaceDBException, InvalidHostException, MongoAuthException,
TypeStorageException {
wsmongo = GetMongoDB.getDB(host, database, user, password);
wsjongo = new Jongo(wsmongo);
query = new QueryMethods(wsmongo, (AllUsers) ALL_USERS, COL_WORKSPACES,
COL_WORKSPACE_OBJS, COL_WORKSPACE_VERS, COL_WS_ACLS);
final Settings settings = getSettings();
blob = setupBlobStore(settings, backendSecret);
updateWScounter = buildCounterQuery(wsjongo);
this.typeValidator = new TypedObjectValidator(
new TypeDefinitionDB(
new MongoTypeStorage(
GetMongoDB.getDB(host, settings.getTypeDatabase(),
user, password)),
typeDBdir == null ? null : new File(typeDBdir), kidlpath, "both"));
ensureIndexes();
ensureTypeIndexes();
}
private void ensureIndexes() {
for (String col: INDEXES.keySet()) {
wsmongo.getCollection(col).resetIndexCache();
for (List<String> idx: INDEXES.get(col).keySet()) {
final DBObject index = new BasicDBObject();
final DBObject opts = new BasicDBObject();
for (String field: idx) {
index.put(field, 1);
}
for (String option: INDEXES.get(col).get(idx)) {
if (!option.equals("")) {
opts.put(option, 1);
}
}
wsmongo.getCollection(col).ensureIndex(index, opts);
}
}
}
private void ensureTypeIndexes() {
for (final String col: wsmongo.getCollectionNames()) {
if (col.startsWith(TypeData.TYPE_COL_PREFIX)) {
ensureTypeIndex(col);
}
}
}
private void ensureTypeIndex(final TypeDefId type) {
ensureTypeIndex(TypeData.getTypeCollection(type));
}
private void ensureTypeIndex(String col) {
if (typeIndexEnsured.contains(col)) {
return;
}
final DBObject chksum = new BasicDBObject();
chksum.put(Fields.TYPE_CHKSUM, 1);
final DBObject unique = new BasicDBObject();
unique.put(IDX_UNIQ, 1);
wsmongo.getCollection(col).resetIndexCache();
wsmongo.getCollection(col).ensureIndex(chksum, unique);
typeIndexEnsured.add(col);
}
private static FindAndModify buildCounterQuery(final Jongo j) {
return j.getCollection(COL_WS_CNT)
.findAndModify(String.format("{%s: #}",
Fields.CNT_ID), Fields.CNT_ID_VAL)
.upsert().returnNew()
.with("{$inc: {" + Fields.CNT_NUM + ": #}}", 1L)
.projection(String.format("{%s: 1, %s: 0}",
Fields.CNT_NUM, Fields.MONGO_ID));
}
private Settings getSettings() throws UninitializedWorkspaceDBException,
CorruptWorkspaceDBException {
if (!wsmongo.collectionExists(COL_SETTINGS)) {
throw new UninitializedWorkspaceDBException(
"No settings collection exists");
}
MongoCollection settings = wsjongo.getCollection(COL_SETTINGS);
if (settings.count() != 1) {
throw new CorruptWorkspaceDBException(
"More than one settings document exists");
}
Settings wsSettings = null;
try {
wsSettings = settings.findOne().as(Settings.class);
} catch (MarshallingException me) {
Throwable ex = me.getCause();
if (ex == null) {
throw new CorruptWorkspaceDBException(
"Unable to unmarshal settings document", me);
}
ex = ex.getCause();
if (ex == null || !(ex instanceof CorruptWorkspaceDBException)) {
throw new CorruptWorkspaceDBException(
"Unable to unmarshal settings document", me);
}
throw (CorruptWorkspaceDBException) ex;
}
return wsSettings;
}
private BlobStore setupBlobStore(final Settings settings,
final String backendSecret) throws CorruptWorkspaceDBException,
DBAuthorizationException, WorkspaceDBInitializationException {
if (settings.isGridFSBackend()) {
return new GridFSBackend(wsmongo);
}
if (settings.isShockBackend()) {
URL shockurl = null;
try {
shockurl = new URL(settings.getShockUrl());
} catch (MalformedURLException mue) {
throw new CorruptWorkspaceDBException(
"Settings has bad shock url: "
+ settings.getShockUrl(), mue);
}
BlobStore bs;
try {
bs = new ShockBackend(wsmongo, COL_SHOCK_PREFIX,
shockurl, settings.getShockUser(), backendSecret);
} catch (BlobStoreAuthorizationException e) {
throw new DBAuthorizationException(
"Not authorized to access the blob store database", e);
} catch (BlobStoreException e) {
throw new WorkspaceDBInitializationException(
"The database could not be initialized: " +
e.getLocalizedMessage(), e);
}
// TODO if shock, check a few random nodes to make sure they match
// the internal representation, die otherwise
return bs;
}
throw new RuntimeException("Something's real broke y'all");
}
@Override
public TypedObjectValidator getTypeValidator() {
return typeValidator;
}
@Override
public String getBackendType() {
return blob.getStoreType();
}
private static final String M_CREATE_WS_QRY = String.format("{%s: #}",
Fields.WS_NAME);
@Override
public WorkspaceInformation createWorkspace(final WorkspaceUser user,
final String wsname, final boolean globalRead,
final String description) throws PreExistingWorkspaceException,
WorkspaceCommunicationException, CorruptWorkspaceDBException {
//avoid incrementing the counter if we don't have to
try {
if (wsjongo.getCollection(COL_WORKSPACES).count(
M_CREATE_WS_QRY, wsname) > 0) {
throw new PreExistingWorkspaceException(String.format(
"Workspace %s already exists", wsname));
}
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final long count;
try {
count = ((Number) updateWScounter.as(DBObject.class)
.get(Fields.CNT_NUM)).longValue();
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final DBObject ws = new BasicDBObject();
ws.put(Fields.WS_OWNER, user.getUser());
ws.put(Fields.WS_ID, count);
Date moddate = new Date();
ws.put(Fields.WS_MODDATE, moddate);
ws.put(Fields.WS_NAME, wsname);
ws.put(Fields.WS_DEL, false);
ws.put(Fields.WS_NUMOBJ, 0L);
ws.put(Fields.WS_DESC, description);
ws.put(Fields.WS_LOCKED, false);
try {
wsmongo.getCollection(COL_WORKSPACES).insert(ws);
} catch (MongoException.DuplicateKey mdk) {
//this is almost impossible to test and will probably almost never happen
throw new PreExistingWorkspaceException(String.format(
"Workspace %s already exists", wsname));
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
setPermissionsForWorkspaceUsers(
new ResolvedMongoWSID(wsname, count, false),
Arrays.asList(user), Permission.OWNER, false);
if (globalRead) {
setPermissions(new ResolvedMongoWSID(wsname, count, false),
Arrays.asList(ALL_USERS), Permission.READ, false);
}
return new MongoWSInfo(count, wsname, user, moddate, 0L,
Permission.OWNER, globalRead, false);
}
private static final Set<String> FLDS_CLONE_WS =
newHashSet(Fields.OBJ_ID, Fields.OBJ_NAME, Fields.OBJ_DEL,
Fields.OBJ_HIDE);
@Override
public WorkspaceInformation cloneWorkspace(final WorkspaceUser user,
final ResolvedWorkspaceID wsid, final String newname,
final boolean globalRead, final String description)
throws PreExistingWorkspaceException,
WorkspaceCommunicationException, CorruptWorkspaceDBException {
// looked at using copyObject to do this but was too messy
final ResolvedMongoWSID fromWS = query.convertResolvedWSID(wsid);
final WorkspaceInformation wsinfo =
createWorkspace(user, newname, globalRead, description);
final ResolvedMongoWSID toWS = new ResolvedMongoWSID(wsinfo.getName(),
wsinfo.getId(), wsinfo.isLocked());
final DBObject q = new BasicDBObject(Fields.OBJ_WS_ID, fromWS.getID());
final List<Map<String, Object>> wsobjects =
query.queryCollection(COL_WORKSPACE_OBJS, q, FLDS_CLONE_WS);
for (Map<String, Object> o: wsobjects) {
if ((Boolean) o.get(Fields.OBJ_DEL)) {
continue;
}
final long oldid = (Long) o.get(Fields.OBJ_ID);
final String name = (String) o.get(Fields.OBJ_NAME);
final boolean hidden = (Boolean) o.get(Fields.OBJ_HIDE);
final ResolvedMongoObjectIDNoVer roi =
new ResolvedMongoObjectIDNoVer(fromWS, name, oldid);
final List<Map<String, Object>> versions = query.queryAllVersions(
new HashSet<ResolvedMongoObjectIDNoVer>(Arrays.asList(roi)),
FLDS_VER_COPYOBJ).get(roi);
for (final Map<String, Object> v: versions) {
final int ver = (Integer) v.get(Fields.VER_VER);
v.remove(Fields.MONGO_ID);
v.put(Fields.VER_SAVEDBY, user.getUser());
v.put(Fields.VER_RVRT, null);
v.put(Fields.VER_COPIED, new MongoReference(
fromWS.getID(), oldid, ver).toString());
}
updateReferenceCountsForVersions(versions);
final long newid = incrementWorkspaceCounter(toWS, 1);
final long objid = saveWorkspaceObject(toWS, newid, name).id;
saveObjectVersions(user, toWS, objid, versions, hidden);
}
return getWorkspaceInformation(user, toWS);
}
private final static String M_LOCK_WS_QRY = String.format("{%s: #}",
Fields.WS_ID);
private final static String M_LOCK_WS_WTH = String.format("{$set: {%s: #}}",
Fields.WS_LOCKED);
@Override
public WorkspaceInformation lockWorkspace(final WorkspaceUser user,
final ResolvedWorkspaceID rwsi)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
try {
wsjongo.getCollection(COL_WORKSPACES)
.update(M_LOCK_WS_QRY, rwsi.getID())
.with(M_LOCK_WS_WTH, true);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return getWorkspaceInformation(user, rwsi);
}
private static final Set<String> FLDS_VER_COPYOBJ = newHashSet(
Fields.VER_WS_ID, Fields.VER_ID, Fields.VER_VER,
Fields.VER_TYPE, Fields.VER_CHKSUM, Fields.VER_SIZE,
Fields.VER_PROV, Fields.VER_REF, Fields.VER_PROVREF,
Fields.VER_COPIED, Fields.VER_META);
@Override
public ObjectInformation copyObject(final WorkspaceUser user,
final ObjectIDResolvedWS from, final ObjectIDResolvedWS to)
throws NoSuchObjectException, WorkspaceCommunicationException {
return copyOrRevert(user, from, to, false);
}
@Override
public ObjectInformation revertObject(final WorkspaceUser user,
final ObjectIDResolvedWS oi)
throws NoSuchObjectException, WorkspaceCommunicationException {
return copyOrRevert(user, oi, null, true);
}
private ObjectInformation copyOrRevert(final WorkspaceUser user,
final ObjectIDResolvedWS from, ObjectIDResolvedWS to,
final boolean revert)
throws NoSuchObjectException, WorkspaceCommunicationException {
final ResolvedMongoObjectID rfrom = resolveObjectIDs(
new HashSet<ObjectIDResolvedWS>(Arrays.asList(from))).get(from);
final ResolvedMongoObjectID rto;
if (revert) {
to = from;
rto = rfrom;
} else {
rto = resolveObjectIDs(
new HashSet<ObjectIDResolvedWS>(Arrays.asList(to)),
true, false).get(to); //don't except if there's no object
}
if (rto == null && to.getId() != null) {
throw new NoSuchObjectException(String.format(
"Copy destination is specified as object id %s in workspace %s which does not exist.",
to.getId(), to.getWorkspaceIdentifier().getID()));
}
final List<Map<String, Object>> versions;
if (rto == null && from.getVersion() == null) {
final ResolvedMongoObjectIDNoVer o =
new ResolvedMongoObjectIDNoVer(rfrom);
versions = query.queryAllVersions(
new HashSet<ResolvedMongoObjectIDNoVer>(Arrays.asList(o)),
FLDS_VER_COPYOBJ).get(o);
} else {
versions = Arrays.asList(query.queryVersions(
new HashSet<ResolvedMongoObjectID>(Arrays.asList(rfrom)),
FLDS_VER_COPYOBJ).get(rfrom));
}
for (final Map<String, Object> v: versions) {
int ver = (Integer) v.get(Fields.VER_VER);
v.remove(Fields.MONGO_ID);
v.put(Fields.VER_SAVEDBY, user.getUser());
if (revert) {
v.put(Fields.VER_RVRT, ver);
} else {
v.put(Fields.VER_RVRT, null);
v.put(Fields.VER_COPIED, new MongoReference(
rfrom.getWorkspaceIdentifier().getID(), rfrom.getId(),
ver).toString());
}
}
updateReferenceCountsForVersions(versions);
final ResolvedMongoWSID toWS = query.convertResolvedWSID(
to.getWorkspaceIdentifier());
final long objid;
if (rto == null) { //need to make a new object
final long id = incrementWorkspaceCounter(toWS, 1);
objid = saveWorkspaceObject(toWS, id, to.getName()).id;
} else {
objid = rto.getId();
}
saveObjectVersions(user, toWS, objid, versions, null);
final Map<String, Object> info = versions.get(versions.size() - 1);
return generateObjectInfo(toWS, objid, rto == null ? to.getName() :
rto.getName(), info);
}
final private static String M_RENAME_WS_QRY = String.format(
"{%s: #}", Fields.WS_ID);
final private static String M_RENAME_WS_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.WS_NAME, Fields.WS_MODDATE);
@Override
public WorkspaceInformation renameWorkspace(final WorkspaceUser user,
final ResolvedWorkspaceID rwsi, final String newname)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
if (newname.equals(rwsi.getName())) {
throw new IllegalArgumentException("Workspace is already named " +
newname);
}
try {
wsjongo.getCollection(COL_WORKSPACES)
.update(M_RENAME_WS_QRY, rwsi.getID())
.with(M_RENAME_WS_WTH, newname, new Date());
} catch (MongoException.DuplicateKey medk) {
throw new IllegalArgumentException(
"There is already a workspace named " + newname);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return getWorkspaceInformation(user, rwsi);
}
final private static String M_RENAME_OBJ_QRY = String.format(
"{%s: #, %s: #}", Fields.OBJ_WS_ID, Fields.OBJ_ID);
final private static String M_RENAME_OBJ_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.OBJ_NAME, Fields.OBJ_MODDATE);
@Override
public ObjectInformation renameObject(final ObjectIDResolvedWS oi,
final String newname)
throws NoSuchObjectException, WorkspaceCommunicationException {
Set<ObjectIDResolvedWS> input = new HashSet<ObjectIDResolvedWS>(
Arrays.asList(oi));
final ResolvedMongoObjectID roi = resolveObjectIDs(input).get(oi);
if (newname.equals(roi.getName())) {
throw new IllegalArgumentException("Object is already named " +
newname);
}
try {
wsjongo.getCollection(COL_WORKSPACE_OBJS)
.update(M_RENAME_OBJ_QRY,
roi.getWorkspaceIdentifier().getID(), roi.getId())
.with(M_RENAME_OBJ_WTH, newname, new Date());
} catch (MongoException.DuplicateKey medk) {
throw new IllegalArgumentException(
"There is already an object in the workspace named " +
newname);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final ObjectIDResolvedWS oid = new ObjectIDResolvedWS(
roi.getWorkspaceIdentifier(), roi.getId(), roi.getVersion());
input = new HashSet<ObjectIDResolvedWS>(Arrays.asList(oid));
return getObjectInformation(input, false).get(oid);
}
//projection lists
private static final Set<String> FLDS_WS_DESC = newHashSet(Fields.WS_DESC);
private static final Set<String> FLDS_WS_OWNER = newHashSet(Fields.WS_OWNER);
//http://stackoverflow.com/questions/2041778/initialize-java-hashset-values-by-construction
@SafeVarargs
private static <T> Set<T> newHashSet(T... objs) {
Set<T> set = new HashSet<T>();
for (T o : objs) {
set.add(o);
}
return set;
}
@Override
public String getWorkspaceDescription(final ResolvedWorkspaceID rwsi) throws
CorruptWorkspaceDBException, WorkspaceCommunicationException {
return (String) query.queryWorkspace(query.convertResolvedWSID(rwsi),
FLDS_WS_DESC).get(Fields.WS_DESC);
}
private final static String M_WS_ID_QRY = String.format("{%s: #}",
Fields.WS_ID);
private final static String M_WS_ID_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.WS_DESC, Fields.WS_MODDATE);
@Override
public void setWorkspaceDescription(final ResolvedWorkspaceID rwsi,
final String description) throws WorkspaceCommunicationException {
//TODO generalized method for setting fields?
try {
wsjongo.getCollection(COL_WORKSPACES)
.update(M_WS_ID_QRY, rwsi.getID())
.with(M_WS_ID_WTH, description, new Date());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
@Override
public ResolvedWorkspaceID resolveWorkspace(final WorkspaceIdentifier wsi)
throws NoSuchWorkspaceException, WorkspaceCommunicationException {
return resolveWorkspace(wsi, false);
}
@Override
public ResolvedWorkspaceID resolveWorkspace(final WorkspaceIdentifier wsi,
final boolean allowDeleted)
throws NoSuchWorkspaceException, WorkspaceCommunicationException {
Set<WorkspaceIdentifier> wsiset = new HashSet<WorkspaceIdentifier>();
wsiset.add(wsi);
return resolveWorkspaces(wsiset, allowDeleted).get(wsi);
}
@Override
public Map<WorkspaceIdentifier, ResolvedWorkspaceID> resolveWorkspaces(
final Set<WorkspaceIdentifier> wsis) throws NoSuchWorkspaceException,
WorkspaceCommunicationException {
return resolveWorkspaces(wsis, false);
}
private static final Set<String> FLDS_WS_ID_NAME_DEL =
newHashSet(Fields.WS_ID, Fields.WS_NAME, Fields.WS_DEL,
Fields.WS_LOCKED);
@Override
public Map<WorkspaceIdentifier, ResolvedWorkspaceID> resolveWorkspaces(
final Set<WorkspaceIdentifier> wsis, final boolean allowDeleted)
throws NoSuchWorkspaceException, WorkspaceCommunicationException {
final Map<WorkspaceIdentifier, ResolvedWorkspaceID> ret =
new HashMap<WorkspaceIdentifier, ResolvedWorkspaceID>();
if (wsis.isEmpty()) {
return ret;
}
final Map<WorkspaceIdentifier, Map<String, Object>> res =
query.queryWorkspacesByIdentifier(wsis, FLDS_WS_ID_NAME_DEL);
for (final WorkspaceIdentifier wsi: wsis) {
if (!res.containsKey(wsi)) {
throw new NoSuchWorkspaceException(String.format(
"No workspace with %s exists", getWSErrorId(wsi)),
wsi);
}
if (!allowDeleted && (Boolean) res.get(wsi).get(Fields.WS_DEL)) {
throw new NoSuchWorkspaceException("Workspace " +
wsi.getIdentifierString() + " is deleted", wsi);
}
ResolvedMongoWSID r = new ResolvedMongoWSID(
(String) res.get(wsi).get(Fields.WS_NAME),
(Long) res.get(wsi).get(Fields.WS_ID),
(Boolean) res.get(wsi).get(Fields.WS_LOCKED));
ret.put(wsi, r);
}
return ret;
}
@Override
public PermissionSet getPermissions(
final WorkspaceUser user, final Permission perm,
final boolean excludeGlobalRead)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
return getPermissions(user,
new HashSet<ResolvedWorkspaceID>(), perm, excludeGlobalRead);
}
@Override
public PermissionSet getPermissions(
final WorkspaceUser user, final Set<ResolvedWorkspaceID> rwsis,
final Permission perm, final boolean excludeGlobalRead)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
if (perm == null || Permission.NONE.equals(perm)) {
throw new IllegalArgumentException(
"Permission cannot be null or NONE");
}
Set<ResolvedMongoWSID> rmwsis = query.convertResolvedWSID(rwsis);
final Map<ResolvedMongoWSID, Map<User, Permission>> userperms;
if (user != null) {
userperms = query.queryPermissions(rmwsis,
new HashSet<User>(Arrays.asList(user)), perm);
} else {
userperms = new HashMap<ResolvedMongoWSID, Map<User,Permission>>();
}
final Set<User> allusers = new HashSet<User>(Arrays.asList(ALL_USERS));
final Map<ResolvedMongoWSID, Map<User, Permission>> globalperms;
if (excludeGlobalRead || perm.compareTo(Permission.WRITE) >= 0) {
if (userperms.isEmpty()) {
globalperms =
new HashMap<ResolvedMongoWSID, Map<User,Permission>>();
} else {
globalperms = query.queryPermissions(userperms.keySet(),
allusers);
}
} else {
globalperms = query.queryPermissions(rmwsis, allusers,
Permission.READ);
}
final MongoPermissionSet pset = new MongoPermissionSet(user, ALL_USERS);
for (final ResolvedMongoWSID rwsi: userperms.keySet()) {
Permission gl = globalperms.get(rwsi) == null ? Permission.NONE :
globalperms.get(rwsi).get(ALL_USERS);
gl = gl == null ? Permission.NONE : gl;
Permission p = userperms.get(rwsi).get(user);
p = p == null ? Permission.NONE : p;
if (!p.equals(Permission.NONE) || !gl.equals(Permission.NONE)) {
pset.setPermission(rwsi, p, gl);
}
globalperms.remove(rwsi);
}
for (final ResolvedMongoWSID rwsi: globalperms.keySet()) {
final Permission gl = globalperms.get(rwsi).get(ALL_USERS);
if (gl != null && !gl.equals(Permission.NONE)) {
pset.setPermission(rwsi, Permission.NONE, gl);
}
}
return pset;
}
private static String getWSErrorId(final WorkspaceIdentifier wsi) {
if (wsi.getId() == null) {
return "name " + wsi.getName();
}
return "id " + wsi.getId();
}
@Override
public void setPermissions(final ResolvedWorkspaceID rwsi,
final List<WorkspaceUser> users, final Permission perm) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
setPermissionsForWorkspaceUsers(query.convertResolvedWSID(rwsi),
users, perm, true);
}
@Override
public void setGlobalPermission(final ResolvedWorkspaceID rwsi,
final Permission perm)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
setPermissions(query.convertResolvedWSID(rwsi),
Arrays.asList(ALL_USERS), perm, false);
}
//wsid must exist as a workspace
private void setPermissionsForWorkspaceUsers(final ResolvedMongoWSID wsid,
final List<WorkspaceUser> users, final Permission perm,
final boolean checkowner) throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
List<User> u = new ArrayList<User>();
for (User user: users) {
u.add(user);
}
setPermissions(wsid, u, perm, checkowner);
}
private static final String M_PERMS_QRY = String.format("{%s: #, %s: #}",
Fields.ACL_WSID, Fields.ACL_USER);
private static final String M_PERMS_UPD = String.format("{$set: {%s: #}}",
Fields.ACL_PERM);
private void setPermissions(final ResolvedMongoWSID wsid, final List<User> users,
final Permission perm, final boolean checkowner) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
final WorkspaceUser owner;
if (checkowner) {
final Map<String, Object> ws =
query.queryWorkspace(wsid, FLDS_WS_OWNER);
if (ws == null) {
throw new CorruptWorkspaceDBException(String.format(
"Workspace %s was unexpectedly deleted from the database",
wsid.getID()));
}
owner = new WorkspaceUser((String) ws.get(Fields.WS_OWNER));
} else {
owner = null;
}
for (User user: users) {
if (owner != null && owner.getUser().equals(user.getUser())) {
continue; // can't change owner permissions
}
try {
if (perm.equals(Permission.NONE)) {
wsjongo.getCollection(COL_WS_ACLS).remove(
M_PERMS_QRY, wsid.getID(), user.getUser());
} else {
wsjongo.getCollection(COL_WS_ACLS).update(
M_PERMS_QRY, wsid.getID(), user.getUser())
.upsert().with(M_PERMS_UPD, perm.getPermission());
}
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
}
@Override
public Permission getPermission(final WorkspaceUser user,
final ResolvedWorkspaceID wsi) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
return getPermissions(user, wsi).getPermission(wsi, true);
}
public PermissionSet getPermissions(final WorkspaceUser user,
final ResolvedWorkspaceID rwsi) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
final Set<ResolvedWorkspaceID> wsis =
new HashSet<ResolvedWorkspaceID>();
wsis.add(rwsi);
return getPermissions(user, wsis);
}
@Override
public PermissionSet getPermissions(
final WorkspaceUser user, final Set<ResolvedWorkspaceID> rwsis)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
return getPermissions(user, rwsis, Permission.READ, false);
}
@Override
public Map<User, Permission> getAllPermissions(
final ResolvedWorkspaceID rwsi) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
return query.queryPermissions(query.convertResolvedWSID(rwsi));
}
private static final Set<String> FLDS_WS_NO_DESC =
newHashSet(Fields.WS_ID, Fields.WS_NAME, Fields.WS_OWNER,
Fields.WS_MODDATE, Fields.WS_NUMOBJ, Fields.WS_DEL,
Fields.WS_LOCKED);
@Override
public List<WorkspaceInformation> getWorkspaceInformation(
final PermissionSet pset, final List<WorkspaceUser> owners,
final boolean showDeleted, final boolean showOnlyDeleted)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
if (!(pset instanceof MongoPermissionSet)) {
throw new IllegalArgumentException(
"Illegal implementation of PermissionSet: " +
pset.getClass().getName());
}
final Map<Long, ResolvedMongoWSID> rwsis =
new HashMap<Long, ResolvedMongoWSID>();
for (final ResolvedWorkspaceID rwsi: pset.getWorkspaces()) {
rwsis.put(rwsi.getID(), query.convertResolvedWSID(rwsi));
}
final DBObject q = new BasicDBObject(Fields.WS_ID,
new BasicDBObject("$in", rwsis.keySet()));
if (owners != null && !owners.isEmpty()) {
q.put(Fields.WS_OWNER, new BasicDBObject("$in",
convertWorkspaceUsers(owners)));
}
final List<Map<String, Object>> ws = query.queryCollection(
COL_WORKSPACES, q, FLDS_WS_NO_DESC);
final List<WorkspaceInformation> ret =
new LinkedList<WorkspaceInformation>();
for (final Map<String, Object> w: ws) {
final ResolvedWorkspaceID rwsi =
rwsis.get((Long) w.get(Fields.WS_ID));
final boolean isDeleted = (Boolean) w.get(Fields.WS_DEL);
if (showOnlyDeleted) {
if (isDeleted &&
pset.hasUserPermission(rwsi, Permission.OWNER)) {
ret.add(generateWSInfo(rwsi, pset, w));
}
} else if (!isDeleted || (showDeleted &&
pset.hasUserPermission(rwsi, Permission.OWNER))) {
ret.add(generateWSInfo(rwsi, pset, w));
}
}
return ret;
}
private List<String> convertWorkspaceUsers(final List<WorkspaceUser> owners) {
final List<String> own = new ArrayList<String>();
for (final WorkspaceUser wu: owners) {
own.add(wu.getUser());
}
return own;
}
@Override
public WorkspaceInformation getWorkspaceInformation(
final WorkspaceUser user, final ResolvedWorkspaceID rwsi)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
final ResolvedMongoWSID m = query.convertResolvedWSID(rwsi);
final Map<String, Object> ws = query.queryWorkspace(m,
FLDS_WS_NO_DESC);
final PermissionSet perms = getPermissions(user, m);
return generateWSInfo(rwsi, perms, ws);
}
private WorkspaceInformation generateWSInfo(final ResolvedWorkspaceID rwsi,
final PermissionSet perms, final Map<String, Object> wsdata) {
return new MongoWSInfo((Long) wsdata.get(Fields.WS_ID),
(String) wsdata.get(Fields.WS_NAME),
new WorkspaceUser((String) wsdata.get(Fields.WS_OWNER)),
(Date) wsdata.get(Fields.WS_MODDATE),
(Long) wsdata.get(Fields.WS_NUMOBJ),
perms.getUserPermission(rwsi),
perms.isWorldReadable(rwsi),
(Boolean) wsdata.get(Fields.WS_LOCKED));
}
private Map<ObjectIDNoWSNoVer, ResolvedMongoObjectID> resolveObjectIDs(
final ResolvedMongoWSID workspaceID,
final Set<ObjectIDNoWSNoVer> objects) throws
WorkspaceCommunicationException {
final Map<ObjectIDNoWSNoVer, ObjectIDResolvedWS> queryobjs =
new HashMap<ObjectIDNoWSNoVer, ObjectIDResolvedWS>();
for (final ObjectIDNoWSNoVer o: objects) {
queryobjs.put(o, new ObjectIDResolvedWS(workspaceID, o));
}
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> res;
try {
res = resolveObjectIDs(
new HashSet<ObjectIDResolvedWS>(queryobjs.values()),
false, false);
} catch (NoSuchObjectException nsoe) {
throw new RuntimeException(
"Threw a NoSuchObjectException when explicitly told not to");
}
final Map<ObjectIDNoWSNoVer, ResolvedMongoObjectID> ret =
new HashMap<ObjectIDNoWSNoVer, ResolvedMongoObjectID>();
for (final ObjectIDNoWSNoVer o: objects) {
if (res.containsKey(queryobjs.get(o))) {
ret.put(o, res.get(queryobjs.get(o)));
}
}
return ret;
}
// save object in preexisting object container
private ObjectInformation saveObjectVersion(final WorkspaceUser user,
final ResolvedMongoWSID wsid, final long objectid,
final ObjectSavePackage pkg)
throws WorkspaceCommunicationException {
final Map<String, Object> version = new HashMap<String, Object>();
version.put(Fields.VER_SAVEDBY, user.getUser());
version.put(Fields.VER_CHKSUM, pkg.td.getChksum());
final List<Map<String, String>> meta =
new ArrayList<Map<String, String>>();
if (pkg.wo.getUserMeta() != null) {
for (String key: pkg.wo.getUserMeta().keySet()) {
Map<String, String> m = new LinkedHashMap<String, String>(2);
m.put(Fields.VER_META_KEY, key);
m.put(Fields.VER_META_VALUE, pkg.wo.getUserMeta().get(key));
meta.add(m);
}
}
version.put(Fields.VER_META, meta);
version.put(Fields.VER_REF, pkg.refs);
version.put(Fields.VER_PROVREF, pkg.provrefs);
version.put(Fields.VER_PROV, pkg.mprov.getMongoId());
version.put(Fields.VER_TYPE, pkg.wo.getRep().getValidationTypeDefId()
.getTypeString());
version.put(Fields.VER_SIZE, pkg.td.getSize());
version.put(Fields.VER_RVRT, null);
version.put(Fields.VER_COPIED, null);
saveObjectVersions(user, wsid, objectid, Arrays.asList(version),
pkg.wo.isHidden());
return new MongoObjectInfo(objectid, pkg.name,
pkg.wo.getRep().getValidationTypeDefId().getTypeString(),
(Date) version.get(Fields.VER_SAVEDATE),
(Integer) version.get(Fields.VER_VER),
user, wsid, pkg.td.getChksum(), pkg.td.getSize(),
pkg.wo.getUserMeta() == null ? new HashMap<String, String>() :
pkg.wo.getUserMeta());
}
private static final String M_SAVEINS_QRY = String.format("{%s: #, %s: #}",
Fields.OBJ_WS_ID, Fields.OBJ_ID);
private static final String M_SAVEINS_PROJ = String.format("{%s: 1, %s: 0}",
Fields.OBJ_VCNT, Fields.MONGO_ID);
private static final String M_SAVEINS_WTH = String.format(
"{$inc: {%s: #}, $set: {%s: false, %s: #, %s: null, %s: #}, $push: {%s: {$each: #}}}",
Fields.OBJ_VCNT, Fields.OBJ_DEL, Fields.OBJ_MODDATE,
Fields.OBJ_LATEST, Fields.OBJ_HIDE, Fields.OBJ_REFCOUNTS);
private static final String M_SAVEINS_NO_HIDE_WTH = String.format(
"{$inc: {%s: #}, $set: {%s: false, %s: #, %s: null}, $push: {%s: {$each: #}}}",
Fields.OBJ_VCNT, Fields.OBJ_DEL, Fields.OBJ_MODDATE,
Fields.OBJ_LATEST, Fields.OBJ_REFCOUNTS);
private void saveObjectVersions(final WorkspaceUser user,
final ResolvedMongoWSID wsid, final long objectid,
final List<Map<String, Object>> versions, final Boolean hidden)
throws WorkspaceCommunicationException {
// collection objects might be batchable if saves are slow
/* TODO deal with rare failure modes below as much as possible at some point. Not high prio since rare
* 1) save an object, crash w/ 0 versions. 2) increment versions, crash w/o saving
* check all places counter incremented (ws, obj, ver) to see if any other problems
* known issues in resolveObjects and listObjects
* can't necc count on the fact that vercount or latestVersion is accurate
* ignore listObjs for now, in resolveObjs mark vers with class and
* have queryVersions pull the right version if it's missing. Make a test for this.
* Have queryVersions revert to the newest version if the latest is missing, autorevert
*
* None of the above addresses the object w/ 0 versions failure. Not sure what to do about that.
*
*/
int ver;
final List<Integer> zeros = new LinkedList<Integer>();
for (int i = 0; i < versions.size(); i++) {
zeros.add(0);
}
final Date saved = new Date();
try {
FindAndModify q = wsjongo.getCollection(COL_WORKSPACE_OBJS)
.findAndModify(M_SAVEINS_QRY, wsid.getID(), objectid)
.returnNew();
if (hidden == null) {
q = q.with(M_SAVEINS_NO_HIDE_WTH, versions.size(),
saved, zeros);
} else {
q = q.with(M_SAVEINS_WTH, versions.size(), saved,
hidden, zeros);
}
ver = (Integer) q
.projection(M_SAVEINS_PROJ).as(DBObject.class)
.get(Fields.OBJ_VCNT)
- versions.size() + 1;
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
//TODO look into why saving array of maps via List.ToArray() /w Jongo makes Lazy?Objects return, which screw up everything
final List<DBObject> dbo = new LinkedList<DBObject>();
for (final Map<String, Object> v: versions) {
v.put(Fields.VER_SAVEDATE, saved);
v.put(Fields.VER_WS_ID, wsid.getID());
v.put(Fields.VER_ID, objectid);
v.put(Fields.VER_VER, ver++);
final DBObject d = new BasicDBObject();
for (final Entry<String, Object> e: v.entrySet()) {
d.put(e.getKey(), e.getValue());
}
dbo.add(d);
}
try {
wsmongo.getCollection(COL_WORKSPACE_VERS).insert(dbo);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
//TODO make all projections not include _id unless specified
private static final String M_UNIQ_NAME_QRY = String.format(
"{%s: #, %s: {$regex: '^#(-\\\\d+)?$'}}", Fields.OBJ_WS_ID,
Fields.OBJ_NAME);
private static final String M_UNIQ_NAME_PROJ = String.format(
"{%s: 1, %s: 0}", Fields.OBJ_NAME, Fields.MONGO_ID);
private String generateUniqueNameForObject(final ResolvedWorkspaceID wsid,
final long objectid) throws WorkspaceCommunicationException {
final String prefix = "auto" + objectid;
@SuppressWarnings("rawtypes")
Iterable<Map> ids;
try {
ids = wsjongo.getCollection(COL_WORKSPACE_OBJS)
.find(M_UNIQ_NAME_QRY, wsid.getID(), prefix)
.projection(M_UNIQ_NAME_PROJ).as(Map.class);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
boolean exact = false;
final Set<Long> suffixes = new HashSet<Long>();
for (@SuppressWarnings("rawtypes") Map m: ids) {
final String[] id = ((String) m.get(Fields.OBJ_NAME)).split("-");
if (id.length == 2) {
try {
suffixes.add(Long.parseLong(id[1]));
} catch (NumberFormatException e) {
// do nothing
}
} else if (id.length == 1) {
try {
exact = exact || prefix.equals(id[0]);
} catch (NumberFormatException e) {
// do nothing
}
}
}
if (!exact) {
return prefix;
}
long counter = 1;
while (suffixes.contains(counter)) {
counter++;
}
return prefix + "-" + counter;
}
//save brand new object - create container
//objectid *must not exist* in the workspace otherwise this method will recurse indefinitely
//the workspace must exist
private IDName saveWorkspaceObject(
final ResolvedMongoWSID wsid, final long objectid,
final String name)
throws WorkspaceCommunicationException {
String newName = name;
if (name == null) {
newName = generateUniqueNameForObject(wsid, objectid);
}
final DBObject dbo = new BasicDBObject();
dbo.put(Fields.OBJ_WS_ID, wsid.getID());
dbo.put(Fields.OBJ_ID, objectid);
dbo.put(Fields.OBJ_VCNT, 0); //Integer
dbo.put(Fields.OBJ_REFCOUNTS, new LinkedList<Integer>());
dbo.put(Fields.OBJ_NAME, newName);
dbo.put(Fields.OBJ_LATEST, null);
dbo.put(Fields.OBJ_DEL, false);
dbo.put(Fields.OBJ_HIDE, false);
try {
//maybe could speed things up with batch inserts but dealing with
//errors would really suck
//do this later if it becomes a bottleneck
wsmongo.getCollection(COL_WORKSPACE_OBJS).insert(dbo);
} catch (MongoException.DuplicateKey dk) {
//ok, someone must've just this second added this name to an object
//asshole
//this should be a rare event
//TODO is this a name or id clash? if the latter, something is broken
if (name == null) {
//not much chance of this happening again, let's just recurse
//and make a new name again
return saveWorkspaceObject(wsid, objectid, name);
}
final ObjectIDNoWSNoVer o = new ObjectIDNoWSNoVer(name);
final Map<ObjectIDNoWSNoVer, ResolvedMongoObjectID> objID =
resolveObjectIDs(wsid,
new HashSet<ObjectIDNoWSNoVer>(Arrays.asList(o)));
if (objID.isEmpty()) {
//oh ffs, name deleted again, try again
return saveWorkspaceObject(wsid, objectid, name);
}
//save version via the id associated with our name which already exists
return new IDName(objID.get(o).getId(), objID.get(o).getName());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return new IDName(objectid, newName);
}
private class IDName {
public long id;
public String name;
public IDName(long id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "IDName [id=" + id + ", name=" + name + "]";
}
}
private static class ObjectSavePackage {
public ResolvedSaveObject wo;
public String name;
public TypeData td;
public Set<String> refs;
public List<String> provrefs;
public MongoProvenance mprov;
@Override
public String toString() {
return "ObjectSavePackage [wo=" + wo + ", name=" + name + ", td="
+ td + ", mprov =" + mprov + "]";
}
}
private static final ObjectMapper MAPPER = new ObjectMapper();
private static String getObjectErrorId(final ObjectIDNoWSNoVer oi,
final int objcount) {
String objErrId = "#" + objcount;
objErrId += oi == null ? "" : ", " + oi.getIdentifierString();
return objErrId;
}
//at this point the objects are expected to be validated and references rewritten
private List<ObjectSavePackage> saveObjectsBuildPackages(
final List<ResolvedSaveObject> objects) {
//this method must maintain the order of the objects
int objnum = 1;
final List<ObjectSavePackage> ret = new LinkedList<ObjectSavePackage>();
for (ResolvedSaveObject o: objects) {
if (o.getRep().getValidationTypeDefId().getMd5() != null) {
throw new RuntimeException("MD5 types are not accepted");
}
final ObjectSavePackage pkg = new ObjectSavePackage();
pkg.refs = checkRefsAreMongo(o.getRefs());
//cannot do by combining in one set since a non-MongoReference
//could be overwritten by a MongoReference if they have the same
//hash
pkg.provrefs = checkRefsAreMongo(o.getProvRefs());
pkg.wo = o;
checkObjectLength(o.getProvenance(), MAX_PROV_SIZE,
o.getObjectIdentifier(), objnum, "provenance");
final Map<String, Object> subdata;
try {
@SuppressWarnings("unchecked")
final Map<String, Object> subdata2 = (Map<String, Object>)
MAPPER.treeToValue(
o.getRep().extractSearchableWsSubset(),
Map.class);
subdata = subdata2;
} catch (JsonProcessingException jpe) {
throw new RuntimeException(
"Should never get a JSON exception here", jpe);
}
escapeSubdata(subdata);
checkObjectLength(subdata, MAX_SUBDATA_SIZE,
o.getObjectIdentifier(), objnum, "subdata");
//could save time by making type->data->TypeData map and reusing
//already calced TDs, but hardly seems worth it - unlikely event
pkg.td = new TypeData(o.getRep().getJsonInstance(),
o.getRep().getValidationTypeDefId(), subdata);
if (pkg.td.getSize() > MAX_OBJECT_SIZE) {
throw new IllegalArgumentException(String.format(
"Object %s data size %s exceeds limit of %s",
getObjectErrorId(o.getObjectIdentifier(), objnum),
pkg.td.getSize(), MAX_OBJECT_SIZE));
}
ret.add(pkg);
objnum++;
}
return ret;
}
//is there some way to combine these with generics?
private Set<String> checkRefsAreMongo(final Set<Reference> refs) {
final Set<String> newrefs = new HashSet<String>();
checkRefsAreMongoInternal(refs, newrefs);
return newrefs;
}
//order must be maintained
private List<String> checkRefsAreMongo(final List<Reference> refs) {
final List<String> newrefs = new LinkedList<String>();
checkRefsAreMongoInternal(refs, newrefs);
return newrefs;
}
private void checkRefsAreMongoInternal(final Collection<Reference> refs,
final Collection<String> newrefs) {
for (final Reference r: refs) {
if (!(r instanceof MongoReference)) {
throw new RuntimeException(
"Improper reference implementation: " +
(r == null ? null : r.getClass()));
}
newrefs.add(r.toString());
}
}
private void checkObjectLength(final Object o, final long max,
final ObjectIDNoWSNoVer oi, final int objnum,
final String objtype) {
final CountingOutputStream cos = new CountingOutputStream();
try {
//writes in UTF8
MAPPER.writeValue(cos, o);
} catch (IOException ioe) {
throw new RuntimeException("something's broken", ioe);
} finally {
try {
cos.close();
} catch (IOException ioe) {
throw new RuntimeException("something's broken", ioe);
}
}
if (cos.getSize() > max) {
throw new IllegalArgumentException(String.format(
"Object %s %s size %s exceeds limit of %s",
getObjectErrorId(oi, objnum), objtype, cos.getSize(), max));
}
}
private void escapeSubdata(final Map<String, Object> subdata) {
escapeSubdataInternal(subdata);
}
//rewrite w/o recursion?
private Object escapeSubdataInternal(final Object o) {
if (o instanceof String || o instanceof Number ||
o instanceof Boolean || o == null) {
return o;
} else if (o instanceof List) {
@SuppressWarnings("unchecked")
final List<Object> l = (List<Object>)o;
for (Object lo: l) {
escapeSubdataInternal(lo);
}
return o;
} else if (o instanceof Map) {
@SuppressWarnings("unchecked")
final Map<String, Object> m = (Map<String, Object>)o;
//save updated keys in separate map so we don't overwrite
//keys before they're escaped
final Map<String, Object> newm = new HashMap<String, Object>();
final Iterator<Entry<String, Object>> iter = m.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, Object> e = iter.next();
final String key = e.getKey();
//need side effect
final Object value = escapeSubdataInternal(e.getValue());
final String newkey = mongoHTMLEscape(key);
//works since mongoHTMLEscape returns same string object if no change
if (key != newkey) {
iter.remove();
newm.put(newkey, value);
}
}
m.putAll(newm);
return o;
} else {
throw new RuntimeException("Unsupported class: " + o.getClass());
}
}
private static final int CODEPOINT_PERC = new String("%").codePointAt(0);
private static final int CODEPOINT_DLR = new String("$").codePointAt(0);
private static final int CODEPOINT_PNT = new String(".").codePointAt(0);
//might be faster just using std string replace() method
private String mongoHTMLEscape(final String s) {
final StringBuilder ret = new StringBuilder();
boolean mod = false;
for (int offset = 0; offset < s.length(); ) {
final int codepoint = s.codePointAt(offset);
if (codepoint == CODEPOINT_PERC) {
ret.append("%25");
mod = true;
} else if (codepoint == CODEPOINT_DLR) {
ret.append("%24");
mod = true;
} else if (codepoint == CODEPOINT_PNT) {
ret.append("%2e");
mod = true;
} else {
ret.appendCodePoint(codepoint);
}
offset += Character.charCount(codepoint);
}
if (mod) {
return ret.toString();
} else {
return s;
}
}
private static final String M_SAVE_QRY = String.format("{%s: #}",
Fields.WS_ID);
private static final String M_SAVE_WTH = String.format("{$inc: {%s: #}}",
Fields.WS_NUMOBJ);
private static final String M_SAVE_PROJ = String.format("{%s: 1, %s: 0}",
Fields.WS_NUMOBJ, Fields.MONGO_ID);
//at this point the objects are expected to be validated and references rewritten
@Override
public List<ObjectInformation> saveObjects(final WorkspaceUser user,
final ResolvedWorkspaceID rwsi,
final List<ResolvedSaveObject> objects)
throws WorkspaceCommunicationException,
NoSuchObjectException {
//TODO break this up
//this method must maintain the order of the objects
final ResolvedMongoWSID wsidmongo = query.convertResolvedWSID(rwsi);
final List<ObjectSavePackage> packages = saveObjectsBuildPackages(
objects);
final Map<ObjectIDNoWSNoVer, List<ObjectSavePackage>> idToPkg =
new HashMap<ObjectIDNoWSNoVer, List<ObjectSavePackage>>();
int newobjects = 0;
for (final ObjectSavePackage p: packages) {
final ObjectIDNoWSNoVer o = p.wo.getObjectIdentifier();
if (o != null) {
if (idToPkg.get(o) == null) {
idToPkg.put(o, new ArrayList<ObjectSavePackage>());
}
idToPkg.get(o).add(p);
} else {
newobjects++;
}
}
final Map<ObjectIDNoWSNoVer, ResolvedMongoObjectID> objIDs =
resolveObjectIDs(wsidmongo, idToPkg.keySet());
for (ObjectIDNoWSNoVer o: idToPkg.keySet()) {
if (!objIDs.containsKey(o)) {
if (o.getId() != null) {
throw new NoSuchObjectException(
"There is no object with id " + o.getId());
} else {
for (ObjectSavePackage pkg: idToPkg.get(o)) {
pkg.name = o.getName();
}
newobjects++;
}
} else {
for (ObjectSavePackage pkg: idToPkg.get(o)) {
pkg.name = objIDs.get(o).getName();
}
}
}
//at this point everything should be ready to save, only comm errors
//can stop us now, the world is doomed
saveData(wsidmongo, packages);
saveProvenance(packages);
updateReferenceCounts(packages);
long newid = incrementWorkspaceCounter(wsidmongo, newobjects);
/* alternate impl: 1) make all save objects 2) increment all version
* counters 3) batch save versions
* This probably won't help much. Firstly, saving the same object
* multiple times (e.g. save over the same object in the same
* saveObjects call) is going to be a rare op - who wants to do that?
* Hence batching up the version increments is probably not going to
* help much.
* Secondly, the write lock is on a per document basis, so batching
* writes has no effect on write locking.
* That means that the gain from batching writes is removal of the
* flight time to/from the server between each object. This may
* be significant for many small objects, but is probably
* insignificant for a few objects, or many large objects.
* Summary: probably not worth the trouble and increase in code
* complexity.
*/
final List<ObjectInformation> ret = new ArrayList<ObjectInformation>();
final Map<String, Long> seenNames = new HashMap<String, Long>();
for (final ObjectSavePackage p: packages) {
final ObjectIDNoWSNoVer oi = p.wo.getObjectIdentifier();
if (oi == null) { //no name given, need to generate one
final IDName obj = saveWorkspaceObject(wsidmongo, newid++,
null);
p.name = obj.name;
ret.add(saveObjectVersion(user, wsidmongo, obj.id, p));
} else if (oi.getId() != null) { //confirmed ok id
ret.add(saveObjectVersion(user, wsidmongo, oi.getId(), p));
} else if (objIDs.get(oi) != null) {//given name translated to id
ret.add(saveObjectVersion(user, wsidmongo, objIDs.get(oi).getId(), p));
} else if (seenNames.containsKey(oi.getName())) {
//we've already generated an id for this name
ret.add(saveObjectVersion(user, wsidmongo, seenNames.get(oi.getName()), p));
} else {//new name, need to generate new id
final IDName obj = saveWorkspaceObject(wsidmongo, newid++,
oi.getName());
p.name = obj.name;
seenNames.put(obj.name, obj.id);
ret.add(saveObjectVersion(user, wsidmongo, obj.id, p));
}
}
return ret;
}
//returns starting object number
private long incrementWorkspaceCounter(final ResolvedMongoWSID wsidmongo,
final int newobjects) throws WorkspaceCommunicationException {
final long lastid;
try {
lastid = ((Number) wsjongo.getCollection(COL_WORKSPACES)
.findAndModify(M_SAVE_QRY, wsidmongo.getID())
.returnNew().with(M_SAVE_WTH, (long) newobjects)
.projection(M_SAVE_PROJ)
.as(DBObject.class).get(Fields.WS_NUMOBJ)).longValue();
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
long newid = lastid - newobjects + 1;
return newid;
}
private void saveProvenance(final List<ObjectSavePackage> packages)
throws WorkspaceCommunicationException {
final List<MongoProvenance> prov = new LinkedList<MongoProvenance>();
for (final ObjectSavePackage p: packages) {
final MongoProvenance mp = new MongoProvenance(
p.wo.getProvenance());
prov.add(mp);
p.mprov = mp;
}
try {
wsjongo.getCollection(COL_PROVENANCE).insert((Object[])
prov.toArray(new MongoProvenance[prov.size()]));
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
private class VerCount {
final public int ver;
final public int count;
public VerCount (final int ver, final int count) {
this.ver = ver;
this.count = count;
}
@Override
public String toString() {
return "VerCount [ver=" + ver + ", count=" + count + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + count;
result = prime * result + ver;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof VerCount)) {
return false;
}
VerCount other = (VerCount) obj;
if (!getOuterType().equals(other.getOuterType())) {
return false;
}
if (count != other.count) {
return false;
}
if (ver != other.ver) {
return false;
}
return true;
}
private MongoWorkspaceDB getOuterType() {
return MongoWorkspaceDB.this;
}
}
private void updateReferenceCounts(final List<ObjectSavePackage> packages)
throws WorkspaceCommunicationException {
//TODO when garbage collection working much more testing of these methods
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts =
countReferences(packages);
/* since the version numbers are probably highly skewed towards 1 and
* the reference counts are also highly skewed towards 1 we can
* probably minimize the number of updates by running one update
* per version/count combination
*/
updateReferenceCounts(refcounts);
}
private void updateReferenceCountsForVersions(
final List<Map<String, Object>> versions)
throws WorkspaceCommunicationException {
//TODO when garbage collection working much more testing of these methods
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts =
countReferencesForVersions(versions);
/* since the version numbers are probably highly skewed towards 1 and
* the reference counts are also highly skewed towards 1 we can
* probably minimize the number of updates by running one update
* per version/count combination
*/
updateReferenceCounts(refcounts);
}
private void updateReferenceCounts(
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts)
throws WorkspaceCommunicationException {
final Map<VerCount, Map<Long, List<Long>>> queries =
new HashMap<VerCount, Map<Long,List<Long>>>();
for (final Long ws: refcounts.keySet()) {
for (final Long obj: refcounts.get(ws).keySet()) {
for (final Integer ver: refcounts.get(ws).get(obj).keySet()) {
final VerCount vc = new VerCount(ver,
refcounts.get(ws).get(obj).get(ver).getValue());
if (!queries.containsKey(vc)) {
queries.put(vc, new HashMap<Long, List<Long>>());
}
if (!queries.get(vc).containsKey(ws)) {
queries.get(vc).put(ws, new LinkedList<Long>());
}
queries.get(vc).get(ws).add(obj);
}
}
}
for (final VerCount vc: queries.keySet()) {
updateReferenceCounts(vc, queries.get(vc));
}
}
private void updateReferenceCounts(final VerCount vc,
final Map<Long, List<Long>> wsToObjs)
throws WorkspaceCommunicationException {
final DBObject update = new BasicDBObject("$inc",
new BasicDBObject(Fields.OBJ_REFCOUNTS + "." + (vc.ver - 1),
vc.count));
final List<DBObject> orquery = new LinkedList<DBObject>();
for (final Long ws: wsToObjs.keySet()) {
final DBObject query = new BasicDBObject(Fields.OBJ_WS_ID, ws);
query.put(Fields.OBJ_ID, new BasicDBObject("$in",
wsToObjs.get(ws)));
orquery.add(query);
}
try {
wsmongo.getCollection(COL_WORKSPACE_OBJS).update(
new BasicDBObject("$or", orquery), update, false, true);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
private Map<Long, Map<Long, Map<Integer, Counter>>> countReferences(
final List<ObjectSavePackage> packages) {
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts =
new HashMap<Long, Map<Long,Map<Integer,Counter>>>();
for (final ObjectSavePackage p: packages) {
//these were checked to be MongoReferences in saveObjectBuildPackages
final Set<Reference> refs = new HashSet<Reference>();
refs.addAll(p.wo.getRefs());
refs.addAll(p.wo.getProvRefs());
countReferences(refcounts, refs);
}
return refcounts;
}
private Map<Long, Map<Long, Map<Integer, Counter>>> countReferencesForVersions(
final List<Map<String, Object>> versions) {
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts =
new HashMap<Long, Map<Long,Map<Integer,Counter>>>();
for (final Map<String, Object> p: versions) {
//these were checked to be MongoReferences in saveObjectBuildPackages
final Set<Reference> refs = new HashSet<Reference>();
@SuppressWarnings("unchecked")
final List<String> objrefs = (List<String>) p.get(Fields.VER_REF);
@SuppressWarnings("unchecked")
final List<String> provrefs = (List<String>) p.get(Fields.VER_PROVREF);
// objrefs.addAll(provrefs); //DON'T DO THIS YOU MORON
for (final String s: objrefs) {
refs.add(new MongoReference(s));
}
for (final String s: provrefs) {
refs.add(new MongoReference(s));
}
countReferences(refcounts, refs);
}
return refcounts;
}
private void countReferences(
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts,
final Set<Reference> refs) {
for (final Reference r: refs) {
if (!refcounts.containsKey(r.getWorkspaceID())) {
refcounts.put(r.getWorkspaceID(),
new HashMap<Long, Map<Integer, Counter>>());
}
if (!refcounts.get(r.getWorkspaceID())
.containsKey(r.getObjectID())) {
refcounts.get(r.getWorkspaceID()).put(r.getObjectID(),
new HashMap<Integer, Counter>());
}
if (!refcounts.get(r.getWorkspaceID()).get(r.getObjectID())
.containsKey(r.getVersion())) {
refcounts.get(r.getWorkspaceID()).get(r.getObjectID())
.put(r.getVersion(), new Counter());
}
refcounts.get(r.getWorkspaceID()).get(r.getObjectID())
.get(r.getVersion()).increment();
}
}
private void saveData(final ResolvedMongoWSID workspaceid,
final List<ObjectSavePackage> data) throws
WorkspaceCommunicationException {
final Map<TypeDefId, List<ObjectSavePackage>> pkgByType =
new HashMap<TypeDefId, List<ObjectSavePackage>>();
for (final ObjectSavePackage p: data) {
if (pkgByType.get(p.td.getType()) == null) {
pkgByType.put(p.td.getType(), new ArrayList<ObjectSavePackage>());
}
pkgByType.get(p.td.getType()).add(p);
}
for (final TypeDefId type: pkgByType.keySet()) {
ensureTypeIndex(type);
final String col = TypeData.getTypeCollection(type);
final Map<String, TypeData> chksum = new HashMap<String, TypeData>();
for (ObjectSavePackage p: pkgByType.get(type)) {
chksum.put(p.td.getChksum(), p.td);
}
final DBObject query = new BasicDBObject(Fields.TYPE_CHKSUM,
new BasicDBObject("$in", new ArrayList<String>(
chksum.keySet())));
final DBObject proj = new BasicDBObject(Fields.TYPE_CHKSUM, 1);
proj.put(Fields.MONGO_ID, 0);
DBCursor res;
try {
res = wsmongo.getCollection(col).find(query, proj);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final Set<String> existChksum = new HashSet<String>();
for (DBObject dbo: res) {
existChksum.add((String)dbo.get(Fields.TYPE_CHKSUM));
}
final List<TypeData> newdata = new ArrayList<TypeData>();
for (String md5: chksum.keySet()) {
if (existChksum.contains(md5)) {
continue;
}
newdata.add(chksum.get(md5));
try {
//this is kind of stupid, but no matter how you slice it you have
//to calc md5s before you save the data
blob.saveBlob(new MD5(md5), chksum.get(md5).getData());
} catch (BlobStoreCommunicationException e) {
throw new WorkspaceCommunicationException(
e.getLocalizedMessage(), e);
} catch (BlobStoreAuthorizationException e) {
throw new WorkspaceCommunicationException(
"Authorization error communicating with the backend storage system",
e);
}
}
try {
wsjongo.getCollection(col).insert((Object[]) newdata.toArray(
new TypeData[newdata.size()]));
} catch (MongoException.DuplicateKey dk) {
//At least one of the data objects was just inserted by another
//thread, which is fine - do nothing
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
}
private static final Set<String> FLDS_VER_GET_OBJECT_SUBDATA = newHashSet(
Fields.VER_VER, Fields.VER_TYPE, Fields.VER_CHKSUM);
private static final String M_GETOBJSUB_QRY = String.format(
"{%s: {$in: #}}", Fields.TYPE_CHKSUM);
private static final String M_GETOBJSUB_PROJ = String.format(
"{%s: 1, %s: 1, %s: 0}",
Fields.TYPE_CHKSUM, Fields.TYPE_SUBDATA, Fields.MONGO_ID);
public Map<ObjectIDResolvedWS, Map<String, Object>> getObjectSubData(
final Set<ObjectIDResolvedWS> objectIDs)
throws NoSuchObjectException, WorkspaceCommunicationException {
//keep doing the next two lines over and over, should probably extract
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> oids =
resolveObjectIDs(objectIDs);
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(
new HashSet<ResolvedMongoObjectID>(oids.values()),
FLDS_VER_GET_OBJECT_SUBDATA);
final Map<TypeDefId, Map<String, Set<ObjectIDResolvedWS>>> toGet =
new HashMap<TypeDefId, Map<String,Set<ObjectIDResolvedWS>>>();
for (final ObjectIDResolvedWS oid: objectIDs) {
final ResolvedMongoObjectID roi = oids.get(oid);
if (!vers.containsKey(roi)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", roi.getId(), roi.getName(),
roi.getVersion(),
roi.getWorkspaceIdentifier().getID()), oid);
}
final Map<String, Object> v = vers.get(roi);
final TypeDefId type = TypeDefId.fromTypeString(
(String) v.get(Fields.VER_TYPE));
final String md5 = (String) v.get(Fields.VER_CHKSUM);
if (!toGet.containsKey(type)) {
toGet.put(type, new HashMap<String, Set<ObjectIDResolvedWS>>());
}
if (!toGet.get(type).containsKey(md5)) {
toGet.get(type).put(md5, new HashSet<ObjectIDResolvedWS>());
}
toGet.get(type).get(md5).add(oid);
}
final Map<ObjectIDResolvedWS, Map<String, Object>> ret =
new HashMap<ObjectIDResolvedWS, Map<String,Object>>();
for (final TypeDefId type: toGet.keySet()) {
@SuppressWarnings("rawtypes")
final Iterable<Map> subdata;
try {
subdata = wsjongo.getCollection(TypeData.getTypeCollection(type))
.find(M_GETOBJSUB_QRY, toGet.get(type).keySet())
.projection(M_GETOBJSUB_PROJ).as(Map.class);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
for (@SuppressWarnings("rawtypes") final Map m: subdata) {
final String md5 = (String) m.get(Fields.TYPE_CHKSUM);
@SuppressWarnings("unchecked")
final Map<String, Object> sd =
(Map<String, Object>) m.get(Fields.TYPE_SUBDATA);
for (final ObjectIDResolvedWS o: toGet.get(type).get(md5)) {
ret.put(o, sd);
}
}
}
return ret;
}
private static final Set<String> FLDS_VER_GET_OBJECT = newHashSet(
Fields.VER_VER, Fields.VER_META, Fields.VER_TYPE,
Fields.VER_SAVEDATE, Fields.VER_SAVEDBY,
Fields.VER_CHKSUM, Fields.VER_SIZE, Fields.VER_PROV,
Fields.VER_PROVREF, Fields.VER_REF);
@Override
public Map<ObjectIDResolvedWS, WorkspaceObjectData> getObjects(
final Set<ObjectIDResolvedWS> objectIDs) throws
NoSuchObjectException, WorkspaceCommunicationException,
CorruptWorkspaceDBException {
final Map<ObjectIDResolvedWS, ObjectPaths> paths =
new HashMap<ObjectIDResolvedWS, ObjectPaths>();
for (final ObjectIDResolvedWS o: objectIDs) {
paths.put(o, null);
}
try {
return getObjects(paths);
} catch (TypedObjectExtractionException toee) {
throw new RuntimeException(
"No extraction done, so something's very wrong here", toee);
}
}
@Override
public Map<ObjectIDResolvedWS, WorkspaceObjectData> getObjects(
final Map<ObjectIDResolvedWS, ObjectPaths> objects) throws
NoSuchObjectException, WorkspaceCommunicationException,
CorruptWorkspaceDBException, TypedObjectExtractionException {
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> oids =
resolveObjectIDs(objects.keySet());
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(
new HashSet<ResolvedMongoObjectID>(oids.values()),
FLDS_VER_GET_OBJECT);
final Map<ObjectId, MongoProvenance> provs = getProvenance(vers);
final Map<String, JsonNode> chksumToData = new HashMap<String, JsonNode>();
final Map<ObjectIDResolvedWS, WorkspaceObjectData> ret =
new HashMap<ObjectIDResolvedWS, WorkspaceObjectData>();
for (ObjectIDResolvedWS o: objects.keySet()) {
final ResolvedMongoObjectID roi = oids.get(o);
if (!vers.containsKey(roi)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", roi.getId(), roi.getName(),
roi.getVersion(),
roi.getWorkspaceIdentifier().getID()), o);
}
final MongoProvenance prov = provs.get((ObjectId) vers.get(roi)
.get(Fields.VER_PROV));
@SuppressWarnings("unchecked")
final List<String> refs =
(List<String>) vers.get(roi).get(Fields.VER_REF);
final MongoObjectInfo meta = generateObjectInfo(
roi, vers.get(roi));
if (chksumToData.containsKey(meta.getCheckSum())) {
/* might be subsetting the same object the same way multiple
* times, but probably unlikely. If it becomes a problem
* memoize the subset
*/
ret.put(o, new WorkspaceObjectData(getDataSubSet(
chksumToData.get(meta.getCheckSum()), objects.get(o)),
meta, prov, refs));
} else {
final JsonNode data;
try {
data = blob.getBlob(new MD5(meta.getCheckSum()));
} catch (BlobStoreCommunicationException e) {
throw new WorkspaceCommunicationException(
e.getLocalizedMessage(), e);
} catch (BlobStoreAuthorizationException e) {
throw new WorkspaceCommunicationException(
"Authorization error communicating with the backend storage system",
e);
} catch (NoSuchBlobException e) {
throw new CorruptWorkspaceDBException(String.format(
"No data present for valid object %s.%s.%s",
meta.getWorkspaceId(), meta.getObjectId(),
meta.getVersion()), e);
}
chksumToData.put(meta.getCheckSum(), data);
ret.put(o, new WorkspaceObjectData(getDataSubSet(
data, objects.get(o)), meta, prov, refs));
}
}
return ret;
}
private JsonNode getDataSubSet(final JsonNode data,
final ObjectPaths paths)
throws TypedObjectExtractionException {
if (paths == null || paths.isEmpty()) {
return data;
}
return TypedObjectExtractor.extract(paths, data);
}
private static final Set<String> FLDS_GETREFOBJ = newHashSet(
Fields.VER_VER, Fields.VER_TYPE, Fields.VER_META,
Fields.VER_SAVEDATE, Fields.VER_SAVEDBY,
Fields.VER_CHKSUM, Fields.VER_SIZE,
Fields.VER_PROVREF, Fields.VER_REF);
@Override
public Map<ObjectIDResolvedWS, Set<ObjectInformation>>
getReferencingObjects(final PermissionSet perms,
final Set<ObjectIDResolvedWS> objs)
throws NoSuchObjectException, WorkspaceCommunicationException {
final List<Long> wsids = new LinkedList<Long>();
for (final ResolvedWorkspaceID ws: perms.getWorkspaces()) {
wsids.add(ws.getID());
}
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> resobjs =
resolveObjectIDs(objs);
verifyVersions(new HashSet<ResolvedMongoObjectID>(resobjs.values()));
final Map<String, Set<ObjectIDResolvedWS>> ref2id =
new HashMap<String, Set<ObjectIDResolvedWS>>();
for (final ObjectIDResolvedWS oi: objs) {
final ResolvedMongoObjectID r = resobjs.get(oi);
final String ref = r.getReference().toString();
if (!ref2id.containsKey(ref)) {
ref2id.put(ref, new HashSet<ObjectIDResolvedWS>());
}
ref2id.get(ref).add(oi);
}
final DBObject q = new BasicDBObject(Fields.VER_WS_ID,
new BasicDBObject("$in", wsids));
q.put("$or", Arrays.asList(
new BasicDBObject(Fields.VER_REF,
new BasicDBObject("$in", ref2id.keySet())),
new BasicDBObject(Fields.VER_PROVREF,
new BasicDBObject("$in", ref2id.keySet()))));
final List<Map<String, Object>> vers = query.queryCollection(
COL_WORKSPACE_VERS, q, FLDS_GETREFOBJ);
final Map<Map<String, Object>, ObjectInformation> voi =
generateObjectInfo(perms, vers, true, false, false, true);
final Map<ObjectIDResolvedWS, Set<ObjectInformation>> ret =
new HashMap<ObjectIDResolvedWS, Set<ObjectInformation>>();
for (final ObjectIDResolvedWS o: objs) {
ret.put(o, new HashSet<ObjectInformation>());
}
for (final Map<String, Object> ver: voi.keySet()) {
@SuppressWarnings("unchecked")
final List<String> refs = (List<String>) ver.get(Fields.VER_REF);
@SuppressWarnings("unchecked")
final List<String> provrefs = (List<String>) ver.get(
Fields.VER_PROVREF);
refs.addAll(provrefs);
for (final String ref: refs) {
if (ref2id.containsKey(ref)) {
for (final ObjectIDResolvedWS oi: ref2id.get(ref)) {
ret.get(oi).add(voi.get(ver));
}
}
}
}
return ret;
}
private Map<ObjectId, MongoProvenance> getProvenance(
final Map<ResolvedMongoObjectID, Map<String, Object>> vers)
throws WorkspaceCommunicationException {
final Map<ObjectId, Map<String, Object>> provIDs =
new HashMap<ObjectId, Map<String,Object>>();
for (final ResolvedMongoObjectID id: vers.keySet()) {
provIDs.put((ObjectId) vers.get(id).get(Fields.VER_PROV),
vers.get(id));
}
final Iterable<MongoProvenance> provs;
try {
provs = wsjongo.getCollection(COL_PROVENANCE)
.find("{_id: {$in: #}}", provIDs.keySet())
.as(MongoProvenance.class);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final Map<ObjectId, MongoProvenance> ret =
new HashMap<ObjectId, MongoProvenance>();
for (MongoProvenance p: provs) {
@SuppressWarnings("unchecked")
final List<String> resolvedRefs = (List<String>) provIDs
.get(p.getMongoId()).get(Fields.VER_PROVREF);
ret.put(p.getMongoId(), p);
p.resolveReferences(resolvedRefs); //this is a gross hack. I'm rather proud of it actually
}
return ret;
}
private MongoObjectInfo generateObjectInfo(
final ResolvedMongoObjectID roi, final Map<String, Object> ver) {
return generateObjectInfo(roi.getWorkspaceIdentifier(), roi.getId(),
roi.getName(), ver);
}
private MongoObjectInfo generateObjectInfo(
final ResolvedMongoWSID rwsi, final long objid, final String name,
final Map<String, Object> ver) {
@SuppressWarnings("unchecked")
final List<Map<String, String>> meta =
(List<Map<String, String>>) ver.get(Fields.VER_META);
return new MongoObjectInfo(
objid,
name,
(String) ver.get(Fields.VER_TYPE),
(Date) ver.get(Fields.VER_SAVEDATE),
(Integer) ver.get(Fields.VER_VER),
new WorkspaceUser((String) ver.get(Fields.VER_SAVEDBY)),
rwsi,
(String) ver.get(Fields.VER_CHKSUM),
(Long) ver.get(Fields.VER_SIZE),
meta == null ? null : metaMongoArrayToHash(meta));
}
private static final Set<String> FLDS_VER_TYPE = newHashSet(
Fields.VER_TYPE, Fields.VER_VER);
public Map<ObjectIDResolvedWS, TypeAndReference> getObjectType(
final Set<ObjectIDResolvedWS> objectIDs) throws
NoSuchObjectException, WorkspaceCommunicationException {
//this method is a pattern - generalize somehow?
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> oids =
resolveObjectIDs(objectIDs);
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(
new HashSet<ResolvedMongoObjectID>(oids.values()),
FLDS_VER_TYPE);
final Map<ObjectIDResolvedWS, TypeAndReference> ret =
new HashMap<ObjectIDResolvedWS, TypeAndReference>();
for (ObjectIDResolvedWS o: objectIDs) {
final ResolvedMongoObjectID roi = oids.get(o);
if (!vers.containsKey(roi)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", roi.getId(), roi.getName(),
roi.getVersion(),
roi.getWorkspaceIdentifier().getID()), o);
}
ret.put(o, new TypeAndReference(
AbsoluteTypeDefId.fromAbsoluteTypeString(
(String) vers.get(roi).get(Fields.VER_TYPE)),
new MongoReference(roi.getWorkspaceIdentifier().getID(),
roi.getId(),
(Integer) vers.get(roi).get(Fields.VER_VER))));
}
return ret;
}
private static final Set<String> FLDS_LIST_OBJ_VER = newHashSet(
Fields.VER_VER, Fields.VER_TYPE, Fields.VER_SAVEDATE,
Fields.VER_SAVEDBY, Fields.VER_VER, Fields.VER_CHKSUM,
Fields.VER_SIZE, Fields.VER_ID, Fields.VER_WS_ID);
private static final Set<String> FLDS_LIST_OBJ = newHashSet(
Fields.OBJ_ID, Fields.OBJ_NAME, Fields.OBJ_DEL, Fields.OBJ_HIDE,
Fields.OBJ_LATEST, Fields.OBJ_VCNT, Fields.OBJ_WS_ID);
private static final String LATEST_VERSION = "latestVersion";
@Override
public List<ObjectInformation> getObjectInformation(
final PermissionSet pset, final TypeDefId type,
final List<WorkspaceUser> savedby, final Map<String, String> meta,
final boolean showHidden, final boolean showDeleted,
final boolean showOnlyDeleted, final boolean showAllVers,
final boolean includeMetadata)
throws WorkspaceCommunicationException {
/* Could make this method more efficient by doing different queries
* based on the filters. If there's no filters except the workspace,
* for example, just grab all the objects for the workspaces,
* filtering out hidden and deleted in the query and pull the most
* recent versions for the remaining objects. For now, just go
* with a dumb general method and add smarter heuristics as needed.
*/
if (!(pset instanceof MongoPermissionSet)) {
throw new IllegalArgumentException(
"Illegal implementation of PermissionSet: " +
pset.getClass().getName());
}
if (pset.isEmpty()) {
return new LinkedList<ObjectInformation>();
}
final Set<Long> ids = new HashSet<Long>();
for (final ResolvedWorkspaceID rwsi: pset.getWorkspaces()) {
ids.add(rwsi.getID());
}
final DBObject verq = new BasicDBObject();
verq.put(Fields.VER_WS_ID, new BasicDBObject("$in", ids));
if (type != null) {
verq.put(Fields.VER_TYPE,
new BasicDBObject("$regex", "^" + type.getTypePrefix()));
}
if (savedby != null && !savedby.isEmpty()) {
verq.put(Fields.VER_SAVEDBY,
new BasicDBObject("$in", convertWorkspaceUsers(savedby)));
}
if (meta != null && !meta.isEmpty()) {
final List<DBObject> andmetaq = new LinkedList<DBObject>();
for (final Entry<String, String> e: meta.entrySet()) {
final DBObject mentry = new BasicDBObject();
mentry.put(Fields.VER_META_KEY, e.getKey());
mentry.put(Fields.VER_META_VALUE, e.getValue());
andmetaq.add(new BasicDBObject(Fields.VER_META, mentry));
}
verq.put("$and", andmetaq); //note more than one entry is untested
}
final Set<String> fields;
if (includeMetadata) {
fields = new HashSet<String>(FLDS_LIST_OBJ_VER);
fields.add(Fields.VER_META);
} else {
fields = FLDS_LIST_OBJ_VER;
}
final List<Map<String, Object>> verobjs = query.queryCollection(
COL_WORKSPACE_VERS, verq, fields);
if (verobjs.isEmpty()) {
return new LinkedList<ObjectInformation>();
}
return new LinkedList<ObjectInformation>(
generateObjectInfo(pset, verobjs, showHidden, showDeleted,
showOnlyDeleted, showAllVers).values());
}
private Map<Map<String, Object>, ObjectInformation> generateObjectInfo(
final PermissionSet pset, final List<Map<String, Object>> verobjs,
final boolean includeHidden, final boolean includeDeleted,
final boolean onlyIncludeDeleted, final boolean includeAllVers)
throws WorkspaceCommunicationException {
final Map<Long, ResolvedWorkspaceID> ids =
new HashMap<Long, ResolvedWorkspaceID>();
for (final ResolvedWorkspaceID rwsi: pset.getWorkspaces()) {
final ResolvedMongoWSID rm = query.convertResolvedWSID(rwsi);
ids.put(rm.getID(), rm);
}
final Map<Long, Set<Long>> verdata = getObjectIDsFromVersions(verobjs);
//TODO This $or query might be better as multiple individual queries, test
final List<DBObject> orquery = new LinkedList<DBObject>();
for (final Long wsid: verdata.keySet()) {
final DBObject query = new BasicDBObject(Fields.VER_WS_ID, wsid);
query.put(Fields.VER_ID, new BasicDBObject(
"$in", verdata.get(wsid)));
orquery.add(query);
}
final DBObject objq = new BasicDBObject("$or", orquery);
//could include / exclude hidden and deleted objects here? Prob
// not worth the effort
final Map<Long, Map<Long, Map<String, Object>>> objdata =
organizeObjData(query.queryCollection(
COL_WORKSPACE_OBJS, objq, FLDS_LIST_OBJ));
final Map<Map<String, Object>, ObjectInformation> ret =
new HashMap<Map<String, Object>, ObjectInformation>();
for (final Map<String, Object> vo: verobjs) {
final long wsid = (Long) vo.get(Fields.VER_WS_ID);
final long id = (Long) vo.get(Fields.VER_ID);
final int ver = (Integer) vo.get(Fields.VER_VER);
final Map<String, Object> obj = objdata.get(wsid).get(id);
final int lastver = (Integer) obj.get(LATEST_VERSION);
final ResolvedMongoWSID rwsi = (ResolvedMongoWSID) ids.get(wsid);
boolean isDeleted = (Boolean) obj.get(Fields.OBJ_DEL);
if (!includeAllVers && lastver != ver) {
/* this is tricky. As is, if there's a failure between incrementing
* an object ver count and saving the object version no latest
* ver will be listed. On the other hand, if we just take
* the max ver we'd be adding incorrect latest vers when filters
* exclude the real max ver. To do this correctly we've have to
* get the max ver for all objects which is really expensive.
* Since the failure mode should be very rare and it fixable
* by simply reverting the object do nothing for now.
*/
continue;
}
if ((Boolean) obj.get(Fields.OBJ_HIDE) && !includeHidden) {
continue;
}
if (onlyIncludeDeleted) {
if (isDeleted && pset.hasPermission(rwsi, Permission.WRITE)) {
ret.put(vo, generateObjectInfo(rwsi, id,
(String) obj.get(Fields.OBJ_NAME), vo));
}
continue;
}
if (isDeleted && (!includeDeleted ||
!pset.hasPermission(rwsi, Permission.WRITE))) {
continue;
}
ret.put(vo, generateObjectInfo(rwsi, id,
(String) obj.get(Fields.OBJ_NAME), vo));
}
return ret;
}
private static final Set<String> FLDS_VER_OBJ_HIST = newHashSet(
Fields.VER_WS_ID, Fields.VER_ID, Fields.VER_VER,
Fields.VER_TYPE, Fields.VER_CHKSUM, Fields.VER_SIZE,
Fields.VER_META, Fields.VER_SAVEDATE, Fields.VER_SAVEDBY);
@Override
public List<ObjectInformation> getObjectHistory(
final ObjectIDResolvedWS oi)
throws NoSuchObjectException, WorkspaceCommunicationException {
final ResolvedMongoObjectID roi = resolveObjectIDs(
new HashSet<ObjectIDResolvedWS>(Arrays.asList(oi))).get(oi);
final ResolvedMongoObjectIDNoVer o =
new ResolvedMongoObjectIDNoVer(roi);
final List<Map<String, Object>> versions = query.queryAllVersions(
new HashSet<ResolvedMongoObjectIDNoVer>(Arrays.asList(o)),
FLDS_VER_OBJ_HIST).get(o);
final LinkedList<ObjectInformation> ret =
new LinkedList<ObjectInformation>();
for (final Map<String, Object> v: versions) {
ret.add(generateObjectInfo(roi, v));
}
return ret;
}
private Map<Long, Map<Long, Map<String, Object>>> organizeObjData(
final List<Map<String, Object>> objs) {
final Map<Long, Map<Long, Map<String, Object>>> ret =
new HashMap<Long, Map<Long,Map<String,Object>>>();
for (final Map<String, Object> o: objs) {
final long wsid = (Long) o.get(Fields.OBJ_WS_ID);
final long objid = (Long) o.get(Fields.OBJ_ID);
final int latestVersion;
if ((Integer) o.get(Fields.OBJ_LATEST) == null) {
latestVersion = (Integer) o.get(Fields.OBJ_VCNT);
} else {
//TODO check this works with GC
latestVersion = (Integer) o.get(Fields.OBJ_LATEST);
}
o.put(LATEST_VERSION, latestVersion);
if (!ret.containsKey(wsid)) {
ret.put(wsid, new HashMap<Long, Map<String, Object>>());
}
ret.get(wsid).put(objid, o);
}
return ret;
}
private Map<Long, Set<Long>> getObjectIDsFromVersions(
final List<Map<String, Object>> objs) {
final Map<Long, Set<Long>> ret = new HashMap<Long, Set<Long>>();
for (final Map<String, Object> o: objs) {
final long wsid = (Long) o.get(Fields.VER_WS_ID);
final long objid = (Long) o.get(Fields.VER_ID);
if (!ret.containsKey(wsid)) {
ret.put(wsid, new HashSet<Long>());
}
ret.get(wsid).add(objid);
}
return ret;
}
private static final Set<String> FLDS_VER_META = newHashSet(
Fields.VER_VER, Fields.VER_TYPE,
Fields.VER_SAVEDATE, Fields.VER_SAVEDBY,
Fields.VER_CHKSUM, Fields.VER_SIZE);
@Override
public Map<ObjectIDResolvedWS, ObjectInformation> getObjectInformation(
final Set<ObjectIDResolvedWS> objectIDs,
final boolean includeMetadata) throws
NoSuchObjectException, WorkspaceCommunicationException {
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> oids =
resolveObjectIDs(objectIDs);
final Set<String> fields;
if (includeMetadata) {
fields = new HashSet<String>(FLDS_VER_META);
fields.add(Fields.VER_META);
} else {
fields = FLDS_VER_META;
}
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(
new HashSet<ResolvedMongoObjectID>(oids.values()),
fields);
final Map<ObjectIDResolvedWS, ObjectInformation> ret =
new HashMap<ObjectIDResolvedWS, ObjectInformation>();
for (ObjectIDResolvedWS o: objectIDs) {
final ResolvedMongoObjectID roi = oids.get(o);
if (!vers.containsKey(roi)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", roi.getId(), roi.getName(),
roi.getVersion(),
roi.getWorkspaceIdentifier().getID()), o);
}
ret.put(o, generateObjectInfo(roi, vers.get(roi)));
}
return ret;
}
private Map<String, String> metaMongoArrayToHash(
final List<Map<String, String>> meta) {
final Map<String, String> ret = new HashMap<String, String>();
for (final Map<String, String> m: meta) {
ret.put(m.get(Fields.VER_META_KEY),
m.get(Fields.VER_META_VALUE));
}
return ret;
}
private static final Set<String> FLDS_RESOLVE_OBJS =
newHashSet(Fields.OBJ_ID, Fields.OBJ_NAME, Fields.OBJ_DEL,
Fields.OBJ_LATEST, Fields.OBJ_VCNT);
private Map<ObjectIDResolvedWS, ResolvedMongoObjectID> resolveObjectIDs(
final Set<ObjectIDResolvedWS> objectIDs)
throws NoSuchObjectException, WorkspaceCommunicationException {
return resolveObjectIDs(objectIDs, true, true);
}
private Map<ObjectIDResolvedWS, ResolvedMongoObjectID> resolveObjectIDs(
final Set<ObjectIDResolvedWS> objectIDs,
final boolean exceptIfDeleted, final boolean exceptIfMissing)
throws NoSuchObjectException, WorkspaceCommunicationException {
final Map<ObjectIDResolvedWS, ObjectIDResolvedWSNoVer> nover =
new HashMap<ObjectIDResolvedWS, ObjectIDResolvedWSNoVer>();
for (final ObjectIDResolvedWS o: objectIDs) {
nover.put(o, new ObjectIDResolvedWSNoVer(o));
}
final Map<ObjectIDResolvedWSNoVer, Map<String, Object>> ids =
query.queryObjects(
new HashSet<ObjectIDResolvedWSNoVer>(nover.values()),
FLDS_RESOLVE_OBJS);
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> ret =
new HashMap<ObjectIDResolvedWS, ResolvedMongoObjectID>();
for (final ObjectIDResolvedWS oid: nover.keySet()) {
final ObjectIDResolvedWSNoVer o = nover.get(oid);
if (!ids.containsKey(o)) {
if (exceptIfMissing) {
final String err = oid.getId() == null ? "name" : "id";
throw new NoSuchObjectException(String.format(
"No object with %s %s exists in workspace %s",
err, oid.getIdentifierString(),
oid.getWorkspaceIdentifier().getID()), oid);
} else {
continue;
}
}
final String name = (String) ids.get(o).get(Fields.OBJ_NAME);
final long id = (Long) ids.get(o).get(Fields.OBJ_ID);
if (exceptIfDeleted && (Boolean) ids.get(o).get(Fields.OBJ_DEL)) {
throw new NoSuchObjectException(String.format(
"Object %s (name %s) in workspace %s has been deleted",
id, name, oid.getWorkspaceIdentifier().getID()), oid);
}
final Integer latestVersion;
if ((Integer) ids.get(o).get(Fields.OBJ_LATEST) == null) {
latestVersion = (Integer) ids.get(o).get(Fields.OBJ_VCNT);
} else {
//TODO check this works with GC
latestVersion = (Integer) ids.get(o).get(Fields.OBJ_LATEST);
}
if (oid.getVersion() == null ||
oid.getVersion().equals(latestVersion)) {
//TODO this could be wrong if the vercount was incremented without a ver save, should verify and then sort if needed
ret.put(oid, new ResolvedMongoOIDWithObjLastVer(
query.convertResolvedWSID(oid.getWorkspaceIdentifier()),
name, id, latestVersion));
} else {
if (oid.getVersion().compareTo(latestVersion) > 0) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s" +
" exists in workspace %s", id, name,
oid.getVersion(),
oid.getWorkspaceIdentifier().getID()), oid);
} else {
ret.put(oid, new ResolvedMongoObjectID(
query.convertResolvedWSID(
oid.getWorkspaceIdentifier()),
name, id, oid.getVersion().intValue()));
}
}
}
return ret;
}
private void verifyVersions(final Set<ResolvedMongoObjectID> objs)
throws WorkspaceCommunicationException, NoSuchObjectException {
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(objs, new HashSet<String>()); //don't actually need the data
for (final ResolvedMongoObjectID o: objs) {
if (!vers.containsKey(o)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", o.getId(), o.getName(),
o.getVersion(),
o.getWorkspaceIdentifier().getID()));
}
}
}
@Override
public void setObjectsHidden(final Set<ObjectIDResolvedWS> objectIDs,
final boolean hide)
throws NoSuchObjectException, WorkspaceCommunicationException {
//TODO nearly identical to delete objects, generalize
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> ids =
resolveObjectIDs(objectIDs);
final Map<ResolvedMongoWSID, List<Long>> toModify =
new HashMap<ResolvedMongoWSID, List<Long>>();
for (final ObjectIDResolvedWS o: objectIDs) {
final ResolvedMongoWSID ws = query.convertResolvedWSID(
o.getWorkspaceIdentifier());
if (!toModify.containsKey(ws)) {
toModify.put(ws, new ArrayList<Long>());
}
toModify.get(ws).add(ids.get(o).getId());
}
//Do this by workspace since per mongo docs nested $ors are crappy
for (final ResolvedMongoWSID ws: toModify.keySet()) {
setObjectsHidden(ws, toModify.get(ws), hide);
}
}
private static final String M_HIDOBJ_WTH = String.format(
"{$set: {%s: #}}", Fields.OBJ_HIDE);
private static final String M_HIDOBJ_QRY = String.format(
"{%s: #, %s: {$in: #}}", Fields.OBJ_WS_ID, Fields.OBJ_ID);
private void setObjectsHidden(final ResolvedMongoWSID ws,
final List<Long> objectIDs, final boolean hide)
throws WorkspaceCommunicationException {
//TODO make general set field method?
if (objectIDs.isEmpty()) {
throw new IllegalArgumentException("Object IDs cannot be empty");
}
try {
wsjongo.getCollection(COL_WORKSPACE_OBJS)
.update(M_HIDOBJ_QRY, ws.getID(), objectIDs).multi()
.with(M_HIDOBJ_WTH, hide);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
@Override
public void setObjectsDeleted(final Set<ObjectIDResolvedWS> objectIDs,
final boolean delete)
throws NoSuchObjectException, WorkspaceCommunicationException {
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> ids =
resolveObjectIDs(objectIDs, delete, true);
final Map<ResolvedMongoWSID, List<Long>> toModify =
new HashMap<ResolvedMongoWSID, List<Long>>();
for (final ObjectIDResolvedWS o: objectIDs) {
final ResolvedMongoWSID ws = query.convertResolvedWSID(
o.getWorkspaceIdentifier());
if (!toModify.containsKey(ws)) {
toModify.put(ws, new ArrayList<Long>());
}
toModify.get(ws).add(ids.get(o).getId());
}
//Do this by workspace since per mongo docs nested $ors are crappy
for (final ResolvedMongoWSID ws: toModify.keySet()) {
setObjectsDeleted(ws, toModify.get(ws), delete);
}
}
private static final String M_DELOBJ_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.OBJ_DEL, Fields.OBJ_MODDATE);
private void setObjectsDeleted(final ResolvedMongoWSID ws,
final List<Long> objectIDs, final boolean delete)
throws WorkspaceCommunicationException {
final String query;
if (objectIDs.isEmpty()) {
query = String.format(
"{%s: %s, %s: %s}", Fields.OBJ_WS_ID, ws.getID(),
Fields.OBJ_DEL, !delete);
} else {
query = String.format(
"{%s: %s, %s: {$in: [%s]}, %s: %s}",
Fields.OBJ_WS_ID, ws.getID(), Fields.OBJ_ID,
StringUtils.join(objectIDs, ", "), Fields.OBJ_DEL, !delete);
}
try {
wsjongo.getCollection(COL_WORKSPACE_OBJS).update(query).multi()
.with(M_DELOBJ_WTH, delete, new Date());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
private static final String M_DELWS_UPD = String.format("{%s: #}",
Fields.WS_ID);
private static final String M_DELWS_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.WS_DEL, Fields.WS_MODDATE);
public void setWorkspaceDeleted(final ResolvedWorkspaceID rwsi,
final boolean delete) throws WorkspaceCommunicationException {
//there's a possibility of a race condition here if a workspace is
//deleted and undeleted or vice versa in a very short amount of time,
//but that seems so unlikely it's not worth the code
final ResolvedMongoWSID mrwsi = query.convertResolvedWSID(rwsi);
try {
wsjongo.getCollection(COL_WORKSPACES).update(
M_DELWS_UPD, mrwsi.getID())
.with(M_DELWS_WTH, delete, new Date());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
setObjectsDeleted(mrwsi, new ArrayList<Long>(), delete);
}
private static final String M_ADMIN_QRY = String.format(
"{%s: #}", Fields.ADMIN_NAME);
@Override
public boolean isAdmin(WorkspaceUser putativeAdmin)
throws WorkspaceCommunicationException {
try {
return wsjongo.getCollection(COL_ADMINS).count(M_ADMIN_QRY,
putativeAdmin.getUser()) > 0;
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
@Override
public Set<WorkspaceUser> getAdmins()
throws WorkspaceCommunicationException {
final Set<WorkspaceUser> ret = new HashSet<WorkspaceUser>();
final DBCursor cur;
try {
cur = wsmongo.getCollection(COL_ADMINS).find();
for (final DBObject dbo: cur) {
ret.add(new WorkspaceUser((String) dbo.get(Fields.ADMIN_NAME)));
}
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return ret;
}
@Override
public void removeAdmin(WorkspaceUser user)
throws WorkspaceCommunicationException {
try {
wsjongo.getCollection(COL_ADMINS).remove(M_ADMIN_QRY,
user.getUser());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
@Override
public void addAdmin(WorkspaceUser user)
throws WorkspaceCommunicationException {
try {
wsjongo.getCollection(COL_ADMINS).update(M_ADMIN_QRY,
user.getUser()).upsert().with(M_ADMIN_QRY, user.getUser());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
public static class TestMongoSuperInternals {
//screwy tests for methods that can't be tested in a black box manner
private static MongoWorkspaceDB testdb;
@BeforeClass
public static void setUpClass() throws Exception {
WorkspaceTestCommon.destroyAndSetupDB(1, "gridFS", "foo");
String host = WorkspaceTestCommon.getHost();
String db1 = WorkspaceTestCommon.getDB1();
String mUser = WorkspaceTestCommon.getMongoUser();
String mPwd = WorkspaceTestCommon.getMongoPwd();
final String kidlpath = new Util().getKIDLpath();
if (mUser == null || mUser == "") {
testdb = new MongoWorkspaceDB(host, db1, kidlpath, "foo", "foo",
"foo", null);
} else {
testdb = new MongoWorkspaceDB(host, db1, kidlpath, mUser, mPwd,
"foo", null);
}
}
@Test
public void createObject() throws Exception {
testdb.createWorkspace(new WorkspaceUser("u"), "ws", false, null);
Map<String, Object> data = new HashMap<String, Object>();
Map<String, String> meta = new HashMap<String, String>();
Map<String, Object> moredata = new HashMap<String, Object>();
moredata.put("foo", "bar");
data.put("fubar", moredata);
meta.put("metastuff", "meta");
Provenance p = new Provenance(new WorkspaceUser("kbasetest2"));
TypeDefId t = new TypeDefId(new TypeDefName("SomeModule", "AType"), 0, 1);
AbsoluteTypeDefId at = new AbsoluteTypeDefId(new TypeDefName("SomeModule", "AType"), 0, 1);
WorkspaceSaveObject wo = new WorkspaceSaveObject(
new ObjectIDNoWSNoVer("testobj"),
MAPPER.valueToTree(data), t, meta, p, false);
List<ResolvedSaveObject> wco = new ArrayList<ResolvedSaveObject>();
wco.add(wo.resolve(new DummyTypedObjectValidationReport(at, wo.getData()),
new HashSet<Reference>(), new LinkedList<Reference>()));
ObjectSavePackage pkg = new ObjectSavePackage();
pkg.wo = wo.resolve(new DummyTypedObjectValidationReport(at, wo.getData()),
new HashSet<Reference>(), new LinkedList<Reference>());
ResolvedMongoWSID rwsi = new ResolvedMongoWSID("ws", 1, false);
pkg.td = new TypeData(MAPPER.valueToTree(data), at, data);
testdb.saveObjects(new WorkspaceUser("u"), rwsi, wco);
IDName r = testdb.saveWorkspaceObject(rwsi, 3, "testobj");
pkg.name = r.name;
testdb.saveProvenance(Arrays.asList(pkg));
ObjectInformation md = testdb.saveObjectVersion(new WorkspaceUser("u"), rwsi, r.id, pkg);
assertThat("objectid is revised to existing object", md.getObjectId(), is(1L));
}
}
}
| src/us/kbase/workspace/database/mongo/MongoWorkspaceDB.java | package us.kbase.workspace.database.mongo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.jongo.FindAndModify;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.jongo.marshall.MarshallingException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import us.kbase.common.mongo.GetMongoDB;
import us.kbase.common.mongo.exceptions.InvalidHostException;
import us.kbase.common.mongo.exceptions.MongoAuthException;
import us.kbase.typedobj.core.AbsoluteTypeDefId;
import us.kbase.typedobj.core.MD5;
import us.kbase.typedobj.core.ObjectPaths;
import us.kbase.typedobj.core.TypeDefId;
import us.kbase.typedobj.core.TypeDefName;
import us.kbase.typedobj.core.TypedObjectExtractor;
import us.kbase.typedobj.core.TypedObjectValidator;
import us.kbase.typedobj.db.MongoTypeStorage;
import us.kbase.typedobj.db.TypeDefinitionDB;
import us.kbase.typedobj.exceptions.TypeStorageException;
import us.kbase.typedobj.exceptions.TypedObjectExtractionException;
import us.kbase.typedobj.tests.DummyTypedObjectValidationReport;
import us.kbase.workspace.database.AllUsers;
import us.kbase.workspace.database.ObjectIDNoWSNoVer;
import us.kbase.workspace.database.ObjectIDResolvedWS;
import us.kbase.workspace.database.ObjectInformation;
import us.kbase.workspace.database.Permission;
import us.kbase.workspace.database.PermissionSet;
import us.kbase.workspace.database.Provenance;
import us.kbase.workspace.database.Reference;
import us.kbase.workspace.database.ResolvedWorkspaceID;
import us.kbase.workspace.database.TypeAndReference;
import us.kbase.workspace.database.User;
import us.kbase.workspace.database.WorkspaceDatabase;
import us.kbase.workspace.database.WorkspaceIdentifier;
import us.kbase.workspace.database.WorkspaceInformation;
import us.kbase.workspace.database.WorkspaceObjectData;
import us.kbase.workspace.database.WorkspaceUser;
import us.kbase.workspace.database.exceptions.CorruptWorkspaceDBException;
import us.kbase.workspace.database.exceptions.DBAuthorizationException;
import us.kbase.workspace.database.exceptions.NoSuchObjectException;
import us.kbase.workspace.database.exceptions.NoSuchWorkspaceException;
import us.kbase.workspace.database.exceptions.PreExistingWorkspaceException;
import us.kbase.workspace.database.exceptions.UninitializedWorkspaceDBException;
import us.kbase.workspace.database.exceptions.WorkspaceCommunicationException;
import us.kbase.workspace.database.exceptions.WorkspaceDBException;
import us.kbase.workspace.database.exceptions.WorkspaceDBInitializationException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreAuthorizationException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreCommunicationException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreException;
import us.kbase.workspace.database.mongo.exceptions.NoSuchBlobException;
import us.kbase.workspace.kbase.Util;
import us.kbase.workspace.lib.ResolvedSaveObject;
import us.kbase.workspace.lib.WorkspaceSaveObject;
import us.kbase.workspace.test.WorkspaceTestCommon;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
@RunWith(Enclosed.class)
public class MongoWorkspaceDB implements WorkspaceDatabase {
//TODO query user metadata
//TODO save set of objects with same provenance if they were generated by same fn
private static final String COL_ADMINS = "admins";
private static final String COL_SETTINGS = "settings";
private static final String COL_WS_CNT = "workspaceCounter";
private static final String COL_WORKSPACES = "workspaces";
private static final String COL_WS_ACLS = "workspaceACLs";
private static final String COL_WORKSPACE_OBJS = "workspaceObjects";
private static final String COL_WORKSPACE_VERS = "workspaceObjVersions";
private static final String COL_PROVENANCE = "provenance";
private static final String COL_SHOCK_PREFIX = "shock_";
private static final User ALL_USERS = new AllUsers('*');
private static final long MAX_OBJECT_SIZE = 200005000;
private static final long MAX_SUBDATA_SIZE = 15000000;
private static final long MAX_PROV_SIZE = 1000000;
private final DB wsmongo;
private final Jongo wsjongo;
private final BlobStore blob;
private final QueryMethods query;
private final FindAndModify updateWScounter;
private final TypedObjectValidator typeValidator;
private final Set<String> typeIndexEnsured = new HashSet<String>();
//TODO constants class
private static final Map<String, Map<List<String>, List<String>>> INDEXES;
private static final String IDX_UNIQ = "unique";
private static final String IDX_SPARSE = "sparse";
static {
//hardcoded indexes
INDEXES = new HashMap<String, Map<List<String>, List<String>>>();
//workspaces indexes
Map<List<String>, List<String>> ws = new HashMap<List<String>, List<String>>();
//find workspaces you own
ws.put(Arrays.asList(Fields.WS_OWNER), Arrays.asList(""));
//find workspaces by permanent id
ws.put(Arrays.asList(Fields.WS_ID), Arrays.asList(IDX_UNIQ));
//find workspaces by mutable name
ws.put(Arrays.asList(Fields.WS_NAME), Arrays.asList(IDX_UNIQ));
INDEXES.put(COL_WORKSPACES, ws);
//workspace acl indexes
Map<List<String>, List<String>> wsACL = new HashMap<List<String>, List<String>>();
//get a user's permission for a workspace, index covers queries
wsACL.put(Arrays.asList(Fields.ACL_WSID, Fields.ACL_USER, Fields.ACL_PERM), Arrays.asList(IDX_UNIQ));
//find workspaces to which a user has some level of permission, index coves queries
wsACL.put(Arrays.asList(Fields.ACL_USER, Fields.ACL_PERM, Fields.ACL_WSID), Arrays.asList(""));
INDEXES.put(COL_WS_ACLS, wsACL);
//workspace object indexes
Map<List<String>, List<String>> wsObj = new HashMap<List<String>, List<String>>();
//find objects by workspace id & name
wsObj.put(Arrays.asList(Fields.OBJ_WS_ID, Fields.OBJ_NAME), Arrays.asList(IDX_UNIQ));
//find object by workspace id & object id
wsObj.put(Arrays.asList(Fields.OBJ_WS_ID, Fields.OBJ_ID), Arrays.asList(IDX_UNIQ));
//find recently modified objects
wsObj.put(Arrays.asList(Fields.OBJ_MODDATE), Arrays.asList(""));
//find object to garbage collect
wsObj.put(Arrays.asList(Fields.OBJ_DEL, Fields.OBJ_REFCOUNTS), Arrays.asList(""));
INDEXES.put(COL_WORKSPACE_OBJS, wsObj);
//workspace object version indexes
Map<List<String>, List<String>> wsVer = new HashMap<List<String>, List<String>>();
//find versions
wsVer.put(Arrays.asList(Fields.VER_WS_ID, Fields.VER_ID,
Fields.VER_VER), Arrays.asList(IDX_UNIQ));
//find versions by data object
wsVer.put(Arrays.asList(Fields.VER_TYPE, Fields.VER_CHKSUM), Arrays.asList(""));
//determine whether a particular object is referenced by this object
wsVer.put(Arrays.asList(Fields.VER_REF), Arrays.asList(IDX_SPARSE));
//determine whether a particular object is included in this object's provenance
wsVer.put(Arrays.asList(Fields.VER_PROVREF), Arrays.asList(IDX_SPARSE));
//find objects that have the same provenance
wsVer.put(Arrays.asList(Fields.VER_PROV), Arrays.asList(""));
//find objects by saved date
wsVer.put(Arrays.asList(Fields.VER_SAVEDATE), Arrays.asList(""));
//find objects by metadata
wsVer.put(Arrays.asList(Fields.VER_META), Arrays.asList(IDX_SPARSE));
INDEXES.put(COL_WORKSPACE_VERS, wsVer);
//no indexes needed for provenance since all lookups are by _id
//admin indexes
Map<List<String>, List<String>> admin = new HashMap<List<String>, List<String>>();
//find admins by name
admin.put(Arrays.asList(Fields.ADMIN_NAME), Arrays.asList(IDX_UNIQ));
INDEXES.put(COL_ADMINS, admin);
}
public MongoWorkspaceDB(final String host, final String database,
final String backendSecret)
throws UnknownHostException, IOException, InvalidHostException,
WorkspaceDBException, TypeStorageException {
wsmongo = GetMongoDB.getDB(host, database);
wsjongo = new Jongo(wsmongo);
query = new QueryMethods(wsmongo, (AllUsers) ALL_USERS, COL_WORKSPACES,
COL_WORKSPACE_OBJS, COL_WORKSPACE_VERS, COL_WS_ACLS);
final Settings settings = getSettings();
blob = setupBlobStore(settings, backendSecret);
updateWScounter = buildCounterQuery(wsjongo);
//TODO check a few random types and make sure they exist
this.typeValidator = new TypedObjectValidator(
new TypeDefinitionDB(
new MongoTypeStorage(
GetMongoDB.getDB(host, settings.getTypeDatabase()))));
ensureIndexes();
ensureTypeIndexes();
}
public MongoWorkspaceDB(final String host, final String database,
final String backendSecret, final String user,
final String password)
throws UnknownHostException, WorkspaceDBException,
TypeStorageException, IOException, InvalidHostException,
MongoAuthException {
wsmongo = GetMongoDB.getDB(host, database, user, password);
wsjongo = new Jongo(wsmongo);
query = new QueryMethods(wsmongo, (AllUsers) ALL_USERS, COL_WORKSPACES,
COL_WORKSPACE_OBJS, COL_WORKSPACE_VERS, COL_WS_ACLS);
final Settings settings = getSettings();
blob = setupBlobStore(settings, backendSecret);
updateWScounter = buildCounterQuery(wsjongo);
this.typeValidator = new TypedObjectValidator(
new TypeDefinitionDB(
new MongoTypeStorage(
GetMongoDB.getDB(host, settings.getTypeDatabase(),
user, password))));
ensureIndexes();
ensureTypeIndexes();
}
//test constructor - runs both the java and perl type compilers
public MongoWorkspaceDB(final String host, final String database,
final String backendSecret, final String user,
final String password, final String kidlpath,
final String typeDBdir)
throws UnknownHostException, IOException,
WorkspaceDBException, InvalidHostException, MongoAuthException,
TypeStorageException {
wsmongo = GetMongoDB.getDB(host, database, user, password);
wsjongo = new Jongo(wsmongo);
query = new QueryMethods(wsmongo, (AllUsers) ALL_USERS, COL_WORKSPACES,
COL_WORKSPACE_OBJS, COL_WORKSPACE_VERS, COL_WS_ACLS);
final Settings settings = getSettings();
blob = setupBlobStore(settings, backendSecret);
updateWScounter = buildCounterQuery(wsjongo);
this.typeValidator = new TypedObjectValidator(
new TypeDefinitionDB(
new MongoTypeStorage(
GetMongoDB.getDB(host, settings.getTypeDatabase(),
user, password)),
typeDBdir == null ? null : new File(typeDBdir), kidlpath, "both"));
ensureIndexes();
ensureTypeIndexes();
}
private void ensureIndexes() {
for (String col: INDEXES.keySet()) {
wsmongo.getCollection(col).resetIndexCache();
for (List<String> idx: INDEXES.get(col).keySet()) {
final DBObject index = new BasicDBObject();
final DBObject opts = new BasicDBObject();
for (String field: idx) {
index.put(field, 1);
}
for (String option: INDEXES.get(col).get(idx)) {
if (!option.equals("")) {
opts.put(option, 1);
}
}
wsmongo.getCollection(col).ensureIndex(index, opts);
}
}
}
private void ensureTypeIndexes() {
for (final String col: wsmongo.getCollectionNames()) {
if (col.startsWith(TypeData.TYPE_COL_PREFIX)) {
ensureTypeIndex(col);
}
}
}
private void ensureTypeIndex(final TypeDefId type) {
ensureTypeIndex(TypeData.getTypeCollection(type));
}
private void ensureTypeIndex(String col) {
if (typeIndexEnsured.contains(col)) {
return;
}
final DBObject chksum = new BasicDBObject();
chksum.put(Fields.TYPE_CHKSUM, 1);
final DBObject unique = new BasicDBObject();
unique.put(IDX_UNIQ, 1);
wsmongo.getCollection(col).resetIndexCache();
wsmongo.getCollection(col).ensureIndex(chksum, unique);
typeIndexEnsured.add(col);
}
private static FindAndModify buildCounterQuery(final Jongo j) {
return j.getCollection(COL_WS_CNT)
.findAndModify(String.format("{%s: #}",
Fields.CNT_ID), Fields.CNT_ID_VAL)
.upsert().returnNew()
.with("{$inc: {" + Fields.CNT_NUM + ": #}}", 1L)
.projection(String.format("{%s: 1, %s: 0}",
Fields.CNT_NUM, Fields.MONGO_ID));
}
private Settings getSettings() throws UninitializedWorkspaceDBException,
CorruptWorkspaceDBException {
if (!wsmongo.collectionExists(COL_SETTINGS)) {
throw new UninitializedWorkspaceDBException(
"No settings collection exists");
}
MongoCollection settings = wsjongo.getCollection(COL_SETTINGS);
if (settings.count() != 1) {
throw new CorruptWorkspaceDBException(
"More than one settings document exists");
}
Settings wsSettings = null;
try {
wsSettings = settings.findOne().as(Settings.class);
} catch (MarshallingException me) {
Throwable ex = me.getCause();
if (ex == null) {
throw new CorruptWorkspaceDBException(
"Unable to unmarshal settings document", me);
}
ex = ex.getCause();
if (ex == null || !(ex instanceof CorruptWorkspaceDBException)) {
throw new CorruptWorkspaceDBException(
"Unable to unmarshal settings document", me);
}
throw (CorruptWorkspaceDBException) ex;
}
return wsSettings;
}
private BlobStore setupBlobStore(final Settings settings,
final String backendSecret) throws CorruptWorkspaceDBException,
DBAuthorizationException, WorkspaceDBInitializationException {
if (settings.isGridFSBackend()) {
return new GridFSBackend(wsmongo);
}
if (settings.isShockBackend()) {
URL shockurl = null;
try {
shockurl = new URL(settings.getShockUrl());
} catch (MalformedURLException mue) {
throw new CorruptWorkspaceDBException(
"Settings has bad shock url: "
+ settings.getShockUrl(), mue);
}
BlobStore bs;
try {
bs = new ShockBackend(wsmongo, COL_SHOCK_PREFIX,
shockurl, settings.getShockUser(), backendSecret);
} catch (BlobStoreAuthorizationException e) {
throw new DBAuthorizationException(
"Not authorized to access the blob store database", e);
} catch (BlobStoreException e) {
throw new WorkspaceDBInitializationException(
"The database could not be initialized: " +
e.getLocalizedMessage(), e);
}
// TODO if shock, check a few random nodes to make sure they match
// the internal representation, die otherwise
return bs;
}
throw new RuntimeException("Something's real broke y'all");
}
@Override
public TypedObjectValidator getTypeValidator() {
return typeValidator;
}
@Override
public String getBackendType() {
return blob.getStoreType();
}
private static final String M_CREATE_WS_QRY = String.format("{%s: #}",
Fields.WS_NAME);
@Override
public WorkspaceInformation createWorkspace(final WorkspaceUser user,
final String wsname, final boolean globalRead,
final String description) throws PreExistingWorkspaceException,
WorkspaceCommunicationException, CorruptWorkspaceDBException {
//avoid incrementing the counter if we don't have to
try {
if (wsjongo.getCollection(COL_WORKSPACES).count(
M_CREATE_WS_QRY, wsname) > 0) {
throw new PreExistingWorkspaceException(String.format(
"Workspace %s already exists", wsname));
}
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final long count;
try {
count = ((Number) updateWScounter.as(DBObject.class)
.get(Fields.CNT_NUM)).longValue();
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final DBObject ws = new BasicDBObject();
ws.put(Fields.WS_OWNER, user.getUser());
ws.put(Fields.WS_ID, count);
Date moddate = new Date();
ws.put(Fields.WS_MODDATE, moddate);
ws.put(Fields.WS_NAME, wsname);
ws.put(Fields.WS_DEL, false);
ws.put(Fields.WS_NUMOBJ, 0L);
ws.put(Fields.WS_DESC, description);
ws.put(Fields.WS_LOCKED, false);
try {
wsmongo.getCollection(COL_WORKSPACES).insert(ws);
} catch (MongoException.DuplicateKey mdk) {
//this is almost impossible to test and will probably almost never happen
throw new PreExistingWorkspaceException(String.format(
"Workspace %s already exists", wsname));
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
setPermissionsForWorkspaceUsers(
new ResolvedMongoWSID(wsname, count, false),
Arrays.asList(user), Permission.OWNER, false);
if (globalRead) {
setPermissions(new ResolvedMongoWSID(wsname, count, false),
Arrays.asList(ALL_USERS), Permission.READ, false);
}
return new MongoWSInfo(count, wsname, user, moddate, 0L,
Permission.OWNER, globalRead, false);
}
private static final Set<String> FLDS_CLONE_WS =
newHashSet(Fields.OBJ_ID, Fields.OBJ_NAME, Fields.OBJ_DEL,
Fields.OBJ_HIDE);
@Override
public WorkspaceInformation cloneWorkspace(final WorkspaceUser user,
final ResolvedWorkspaceID wsid, final String newname,
final boolean globalRead, final String description)
throws PreExistingWorkspaceException,
WorkspaceCommunicationException, CorruptWorkspaceDBException {
// looked at using copyObject to do this but was too messy
final ResolvedMongoWSID fromWS = query.convertResolvedWSID(wsid);
final WorkspaceInformation wsinfo =
createWorkspace(user, newname, globalRead, description);
final ResolvedMongoWSID toWS = new ResolvedMongoWSID(wsinfo.getName(),
wsinfo.getId(), wsinfo.isLocked());
final DBObject q = new BasicDBObject(Fields.OBJ_WS_ID, fromWS.getID());
final List<Map<String, Object>> wsobjects =
query.queryCollection(COL_WORKSPACE_OBJS, q, FLDS_CLONE_WS);
for (Map<String, Object> o: wsobjects) {
if ((Boolean) o.get(Fields.OBJ_DEL)) {
continue;
}
final long oldid = (Long) o.get(Fields.OBJ_ID);
final String name = (String) o.get(Fields.OBJ_NAME);
final boolean hidden = (Boolean) o.get(Fields.OBJ_HIDE);
final ResolvedMongoObjectIDNoVer roi =
new ResolvedMongoObjectIDNoVer(fromWS, name, oldid);
final List<Map<String, Object>> versions = query.queryAllVersions(
new HashSet<ResolvedMongoObjectIDNoVer>(Arrays.asList(roi)),
FLDS_VER_COPYOBJ).get(roi);
for (final Map<String, Object> v: versions) {
final int ver = (Integer) v.get(Fields.VER_VER);
v.remove(Fields.MONGO_ID);
v.put(Fields.VER_SAVEDBY, user.getUser());
v.put(Fields.VER_RVRT, null);
v.put(Fields.VER_COPIED, new MongoReference(
fromWS.getID(), oldid, ver).toString());
}
updateReferenceCountsForVersions(versions);
final long newid = incrementWorkspaceCounter(toWS, 1);
final long objid = saveWorkspaceObject(toWS, newid, name).id;
saveObjectVersions(user, toWS, objid, versions, hidden);
}
return getWorkspaceInformation(user, toWS);
}
private final static String M_LOCK_WS_QRY = String.format("{%s: #}",
Fields.WS_ID);
private final static String M_LOCK_WS_WTH = String.format("{$set: {%s: #}}",
Fields.WS_LOCKED);
@Override
public WorkspaceInformation lockWorkspace(final WorkspaceUser user,
final ResolvedWorkspaceID rwsi)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
try {
wsjongo.getCollection(COL_WORKSPACES)
.update(M_LOCK_WS_QRY, rwsi.getID())
.with(M_LOCK_WS_WTH, true);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return getWorkspaceInformation(user, rwsi);
}
private static final Set<String> FLDS_VER_COPYOBJ = newHashSet(
Fields.VER_WS_ID, Fields.VER_ID, Fields.VER_VER,
Fields.VER_TYPE, Fields.VER_CHKSUM, Fields.VER_SIZE,
Fields.VER_PROV, Fields.VER_REF, Fields.VER_PROVREF,
Fields.VER_COPIED, Fields.VER_META);
@Override
public ObjectInformation copyObject(final WorkspaceUser user,
final ObjectIDResolvedWS from, final ObjectIDResolvedWS to)
throws NoSuchObjectException, WorkspaceCommunicationException {
return copyOrRevert(user, from, to, false);
}
@Override
public ObjectInformation revertObject(final WorkspaceUser user,
final ObjectIDResolvedWS oi)
throws NoSuchObjectException, WorkspaceCommunicationException {
return copyOrRevert(user, oi, null, true);
}
private ObjectInformation copyOrRevert(final WorkspaceUser user,
final ObjectIDResolvedWS from, ObjectIDResolvedWS to,
final boolean revert)
throws NoSuchObjectException, WorkspaceCommunicationException {
final ResolvedMongoObjectID rfrom = resolveObjectIDs(
new HashSet<ObjectIDResolvedWS>(Arrays.asList(from))).get(from);
final ResolvedMongoObjectID rto;
if (revert) {
to = from;
rto = rfrom;
} else {
rto = resolveObjectIDs(
new HashSet<ObjectIDResolvedWS>(Arrays.asList(to)),
true, false).get(to); //don't except if there's no object
}
if (rto == null && to.getId() != null) {
throw new NoSuchObjectException(String.format(
"Copy destination is specified as object id %s in workspace %s which does not exist.",
to.getId(), to.getWorkspaceIdentifier().getID()));
}
final List<Map<String, Object>> versions;
if (rto == null && from.getVersion() == null) {
final ResolvedMongoObjectIDNoVer o =
new ResolvedMongoObjectIDNoVer(rfrom);
versions = query.queryAllVersions(
new HashSet<ResolvedMongoObjectIDNoVer>(Arrays.asList(o)),
FLDS_VER_COPYOBJ).get(o);
} else {
versions = Arrays.asList(query.queryVersions(
new HashSet<ResolvedMongoObjectID>(Arrays.asList(rfrom)),
FLDS_VER_COPYOBJ).get(rfrom));
}
for (final Map<String, Object> v: versions) {
int ver = (Integer) v.get(Fields.VER_VER);
v.remove(Fields.MONGO_ID);
v.put(Fields.VER_SAVEDBY, user.getUser());
if (revert) {
v.put(Fields.VER_RVRT, ver);
} else {
v.put(Fields.VER_RVRT, null);
v.put(Fields.VER_COPIED, new MongoReference(
rfrom.getWorkspaceIdentifier().getID(), rfrom.getId(),
ver).toString());
}
}
updateReferenceCountsForVersions(versions);
final ResolvedMongoWSID toWS = query.convertResolvedWSID(
to.getWorkspaceIdentifier());
final long objid;
if (rto == null) { //need to make a new object
final long id = incrementWorkspaceCounter(toWS, 1);
objid = saveWorkspaceObject(toWS, id, to.getName()).id;
} else {
objid = rto.getId();
}
saveObjectVersions(user, toWS, objid, versions, null);
final Map<String, Object> info = versions.get(versions.size() - 1);
return generateObjectInfo(toWS, objid, rto == null ? to.getName() :
rto.getName(), info);
}
final private static String M_RENAME_WS_QRY = String.format(
"{%s: #}", Fields.WS_ID);
final private static String M_RENAME_WS_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.WS_NAME, Fields.WS_MODDATE);
@Override
public WorkspaceInformation renameWorkspace(final WorkspaceUser user,
final ResolvedWorkspaceID rwsi, final String newname)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
if (newname.equals(rwsi.getName())) {
throw new IllegalArgumentException("Workspace is already named " +
newname);
}
try {
wsjongo.getCollection(COL_WORKSPACES)
.update(M_RENAME_WS_QRY, rwsi.getID())
.with(M_RENAME_WS_WTH, newname, new Date());
} catch (MongoException.DuplicateKey medk) {
throw new IllegalArgumentException(
"There is already a workspace named " + newname);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return getWorkspaceInformation(user, rwsi);
}
final private static String M_RENAME_OBJ_QRY = String.format(
"{%s: #, %s: #}", Fields.OBJ_WS_ID, Fields.OBJ_ID);
final private static String M_RENAME_OBJ_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.OBJ_NAME, Fields.OBJ_MODDATE);
@Override
public ObjectInformation renameObject(final ObjectIDResolvedWS oi,
final String newname)
throws NoSuchObjectException, WorkspaceCommunicationException {
Set<ObjectIDResolvedWS> input = new HashSet<ObjectIDResolvedWS>(
Arrays.asList(oi));
final ResolvedMongoObjectID roi = resolveObjectIDs(input).get(oi);
if (newname.equals(roi.getName())) {
throw new IllegalArgumentException("Object is already named " +
newname);
}
try {
wsjongo.getCollection(COL_WORKSPACE_OBJS)
.update(M_RENAME_OBJ_QRY,
roi.getWorkspaceIdentifier().getID(), roi.getId())
.with(M_RENAME_OBJ_WTH, newname, new Date());
} catch (MongoException.DuplicateKey medk) {
throw new IllegalArgumentException(
"There is already an object in the workspace named " +
newname);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final ObjectIDResolvedWS oid = new ObjectIDResolvedWS(
roi.getWorkspaceIdentifier(), roi.getId(), roi.getVersion());
input = new HashSet<ObjectIDResolvedWS>(Arrays.asList(oid));
return getObjectInformation(input, false).get(oid);
}
//projection lists
private static final Set<String> FLDS_WS_DESC = newHashSet(Fields.WS_DESC);
private static final Set<String> FLDS_WS_OWNER = newHashSet(Fields.WS_OWNER);
//http://stackoverflow.com/questions/2041778/initialize-java-hashset-values-by-construction
@SafeVarargs
private static <T> Set<T> newHashSet(T... objs) {
Set<T> set = new HashSet<T>();
for (T o : objs) {
set.add(o);
}
return set;
}
@Override
public String getWorkspaceDescription(final ResolvedWorkspaceID rwsi) throws
CorruptWorkspaceDBException, WorkspaceCommunicationException {
return (String) query.queryWorkspace(query.convertResolvedWSID(rwsi),
FLDS_WS_DESC).get(Fields.WS_DESC);
}
private final static String M_WS_ID_QRY = String.format("{%s: #}",
Fields.WS_ID);
private final static String M_WS_ID_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.WS_DESC, Fields.WS_MODDATE);
@Override
public void setWorkspaceDescription(final ResolvedWorkspaceID rwsi,
final String description) throws WorkspaceCommunicationException {
//TODO generalized method for setting fields?
try {
wsjongo.getCollection(COL_WORKSPACES)
.update(M_WS_ID_QRY, rwsi.getID())
.with(M_WS_ID_WTH, description, new Date());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
@Override
public ResolvedWorkspaceID resolveWorkspace(final WorkspaceIdentifier wsi)
throws NoSuchWorkspaceException, WorkspaceCommunicationException {
return resolveWorkspace(wsi, false);
}
@Override
public ResolvedWorkspaceID resolveWorkspace(final WorkspaceIdentifier wsi,
final boolean allowDeleted)
throws NoSuchWorkspaceException, WorkspaceCommunicationException {
Set<WorkspaceIdentifier> wsiset = new HashSet<WorkspaceIdentifier>();
wsiset.add(wsi);
return resolveWorkspaces(wsiset, allowDeleted).get(wsi);
}
@Override
public Map<WorkspaceIdentifier, ResolvedWorkspaceID> resolveWorkspaces(
final Set<WorkspaceIdentifier> wsis) throws NoSuchWorkspaceException,
WorkspaceCommunicationException {
return resolveWorkspaces(wsis, false);
}
private static final Set<String> FLDS_WS_ID_NAME_DEL =
newHashSet(Fields.WS_ID, Fields.WS_NAME, Fields.WS_DEL,
Fields.WS_LOCKED);
@Override
public Map<WorkspaceIdentifier, ResolvedWorkspaceID> resolveWorkspaces(
final Set<WorkspaceIdentifier> wsis, final boolean allowDeleted)
throws NoSuchWorkspaceException, WorkspaceCommunicationException {
final Map<WorkspaceIdentifier, ResolvedWorkspaceID> ret =
new HashMap<WorkspaceIdentifier, ResolvedWorkspaceID>();
if (wsis.isEmpty()) {
return ret;
}
final Map<WorkspaceIdentifier, Map<String, Object>> res =
query.queryWorkspacesByIdentifier(wsis, FLDS_WS_ID_NAME_DEL);
for (final WorkspaceIdentifier wsi: wsis) {
if (!res.containsKey(wsi)) {
throw new NoSuchWorkspaceException(String.format(
"No workspace with %s exists", getWSErrorId(wsi)),
wsi);
}
if (!allowDeleted && (Boolean) res.get(wsi).get(Fields.WS_DEL)) {
throw new NoSuchWorkspaceException("Workspace " +
wsi.getIdentifierString() + " is deleted", wsi);
}
ResolvedMongoWSID r = new ResolvedMongoWSID(
(String) res.get(wsi).get(Fields.WS_NAME),
(Long) res.get(wsi).get(Fields.WS_ID),
(Boolean) res.get(wsi).get(Fields.WS_LOCKED));
ret.put(wsi, r);
}
return ret;
}
@Override
public PermissionSet getPermissions(
final WorkspaceUser user, final Permission perm,
final boolean excludeGlobalRead)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
return getPermissions(user,
new HashSet<ResolvedWorkspaceID>(), perm, excludeGlobalRead);
}
@Override
public PermissionSet getPermissions(
final WorkspaceUser user, final Set<ResolvedWorkspaceID> rwsis,
final Permission perm, final boolean excludeGlobalRead)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
if (perm == null || Permission.NONE.equals(perm)) {
throw new IllegalArgumentException(
"Permission cannot be null or NONE");
}
Set<ResolvedMongoWSID> rmwsis = query.convertResolvedWSID(rwsis);
final Map<ResolvedMongoWSID, Map<User, Permission>> userperms;
if (user != null) {
userperms = query.queryPermissions(rmwsis,
new HashSet<User>(Arrays.asList(user)), perm);
} else {
userperms = new HashMap<ResolvedMongoWSID, Map<User,Permission>>();
}
final Set<User> allusers = new HashSet<User>(Arrays.asList(ALL_USERS));
final Map<ResolvedMongoWSID, Map<User, Permission>> globalperms;
if (excludeGlobalRead || perm.compareTo(Permission.WRITE) >= 0) {
if (userperms.isEmpty()) {
globalperms =
new HashMap<ResolvedMongoWSID, Map<User,Permission>>();
} else {
globalperms = query.queryPermissions(userperms.keySet(),
allusers);
}
} else {
globalperms = query.queryPermissions(rmwsis, allusers,
Permission.READ);
}
final MongoPermissionSet pset = new MongoPermissionSet(user, ALL_USERS);
for (final ResolvedMongoWSID rwsi: userperms.keySet()) {
Permission gl = globalperms.get(rwsi) == null ? Permission.NONE :
globalperms.get(rwsi).get(ALL_USERS);
gl = gl == null ? Permission.NONE : gl;
Permission p = userperms.get(rwsi).get(user);
p = p == null ? Permission.NONE : p;
if (!p.equals(Permission.NONE) || !gl.equals(Permission.NONE)) {
pset.setPermission(rwsi, p, gl);
}
globalperms.remove(rwsi);
}
for (final ResolvedMongoWSID rwsi: globalperms.keySet()) {
final Permission gl = globalperms.get(rwsi).get(ALL_USERS);
if (gl != null && !gl.equals(Permission.NONE)) {
pset.setPermission(rwsi, Permission.NONE, gl);
}
}
return pset;
}
private static String getWSErrorId(final WorkspaceIdentifier wsi) {
if (wsi.getId() == null) {
return "name " + wsi.getName();
}
return "id " + wsi.getId();
}
@Override
public void setPermissions(final ResolvedWorkspaceID rwsi,
final List<WorkspaceUser> users, final Permission perm) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
setPermissionsForWorkspaceUsers(query.convertResolvedWSID(rwsi),
users, perm, true);
}
@Override
public void setGlobalPermission(final ResolvedWorkspaceID rwsi,
final Permission perm)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
setPermissions(query.convertResolvedWSID(rwsi),
Arrays.asList(ALL_USERS), perm, false);
}
//wsid must exist as a workspace
private void setPermissionsForWorkspaceUsers(final ResolvedMongoWSID wsid,
final List<WorkspaceUser> users, final Permission perm,
final boolean checkowner) throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
List<User> u = new ArrayList<User>();
for (User user: users) {
u.add(user);
}
setPermissions(wsid, u, perm, checkowner);
}
private static final String M_PERMS_QRY = String.format("{%s: #, %s: #}",
Fields.ACL_WSID, Fields.ACL_USER);
private static final String M_PERMS_UPD = String.format("{$set: {%s: #}}",
Fields.ACL_PERM);
private void setPermissions(final ResolvedMongoWSID wsid, final List<User> users,
final Permission perm, final boolean checkowner) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
final WorkspaceUser owner;
if (checkowner) {
final Map<String, Object> ws =
query.queryWorkspace(wsid, FLDS_WS_OWNER);
if (ws == null) {
throw new CorruptWorkspaceDBException(String.format(
"Workspace %s was unexpectedly deleted from the database",
wsid.getID()));
}
owner = new WorkspaceUser((String) ws.get(Fields.WS_OWNER));
} else {
owner = null;
}
for (User user: users) {
if (owner != null && owner.getUser().equals(user.getUser())) {
continue; // can't change owner permissions
}
try {
if (perm.equals(Permission.NONE)) {
wsjongo.getCollection(COL_WS_ACLS).remove(
M_PERMS_QRY, wsid.getID(), user.getUser());
} else {
wsjongo.getCollection(COL_WS_ACLS).update(
M_PERMS_QRY, wsid.getID(), user.getUser())
.upsert().with(M_PERMS_UPD, perm.getPermission());
}
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
}
@Override
public Permission getPermission(final WorkspaceUser user,
final ResolvedWorkspaceID wsi) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
return getPermissions(user, wsi).getPermission(wsi, true);
}
public PermissionSet getPermissions(final WorkspaceUser user,
final ResolvedWorkspaceID rwsi) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
final Set<ResolvedWorkspaceID> wsis =
new HashSet<ResolvedWorkspaceID>();
wsis.add(rwsi);
return getPermissions(user, wsis);
}
@Override
public PermissionSet getPermissions(
final WorkspaceUser user, final Set<ResolvedWorkspaceID> rwsis)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
return getPermissions(user, rwsis, Permission.READ, false);
}
@Override
public Map<User, Permission> getAllPermissions(
final ResolvedWorkspaceID rwsi) throws
WorkspaceCommunicationException, CorruptWorkspaceDBException {
return query.queryPermissions(query.convertResolvedWSID(rwsi));
}
private static final Set<String> FLDS_WS_NO_DESC =
newHashSet(Fields.WS_ID, Fields.WS_NAME, Fields.WS_OWNER,
Fields.WS_MODDATE, Fields.WS_NUMOBJ, Fields.WS_DEL,
Fields.WS_LOCKED);
@Override
public List<WorkspaceInformation> getWorkspaceInformation(
final PermissionSet pset, final List<WorkspaceUser> owners,
final boolean showDeleted, final boolean showOnlyDeleted)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
if (!(pset instanceof MongoPermissionSet)) {
throw new IllegalArgumentException(
"Illegal implementation of PermissionSet: " +
pset.getClass().getName());
}
final Map<Long, ResolvedMongoWSID> rwsis =
new HashMap<Long, ResolvedMongoWSID>();
for (final ResolvedWorkspaceID rwsi: pset.getWorkspaces()) {
rwsis.put(rwsi.getID(), query.convertResolvedWSID(rwsi));
}
final DBObject q = new BasicDBObject(Fields.WS_ID,
new BasicDBObject("$in", rwsis.keySet()));
if (owners != null && !owners.isEmpty()) {
q.put(Fields.WS_OWNER, new BasicDBObject("$in",
convertWorkspaceUsers(owners)));
}
final List<Map<String, Object>> ws = query.queryCollection(
COL_WORKSPACES, q, FLDS_WS_NO_DESC);
final List<WorkspaceInformation> ret =
new LinkedList<WorkspaceInformation>();
for (final Map<String, Object> w: ws) {
final ResolvedWorkspaceID rwsi =
rwsis.get((Long) w.get(Fields.WS_ID));
final boolean isDeleted = (Boolean) w.get(Fields.WS_DEL);
if (showOnlyDeleted) {
if (isDeleted &&
pset.hasUserPermission(rwsi, Permission.OWNER)) {
ret.add(generateWSInfo(rwsi, pset, w));
}
} else if (!isDeleted || (showDeleted &&
pset.hasUserPermission(rwsi, Permission.OWNER))) {
ret.add(generateWSInfo(rwsi, pset, w));
}
}
return ret;
}
private List<String> convertWorkspaceUsers(final List<WorkspaceUser> owners) {
final List<String> own = new ArrayList<String>();
for (final WorkspaceUser wu: owners) {
own.add(wu.getUser());
}
return own;
}
@Override
public WorkspaceInformation getWorkspaceInformation(
final WorkspaceUser user, final ResolvedWorkspaceID rwsi)
throws WorkspaceCommunicationException,
CorruptWorkspaceDBException {
final ResolvedMongoWSID m = query.convertResolvedWSID(rwsi);
final Map<String, Object> ws = query.queryWorkspace(m,
FLDS_WS_NO_DESC);
final PermissionSet perms = getPermissions(user, m);
return generateWSInfo(rwsi, perms, ws);
}
private WorkspaceInformation generateWSInfo(final ResolvedWorkspaceID rwsi,
final PermissionSet perms, final Map<String, Object> wsdata) {
return new MongoWSInfo((Long) wsdata.get(Fields.WS_ID),
(String) wsdata.get(Fields.WS_NAME),
new WorkspaceUser((String) wsdata.get(Fields.WS_OWNER)),
(Date) wsdata.get(Fields.WS_MODDATE),
(Long) wsdata.get(Fields.WS_NUMOBJ),
perms.getUserPermission(rwsi),
perms.isWorldReadable(rwsi),
(Boolean) wsdata.get(Fields.WS_LOCKED));
}
private Map<ObjectIDNoWSNoVer, ResolvedMongoObjectID> resolveObjectIDs(
final ResolvedMongoWSID workspaceID,
final Set<ObjectIDNoWSNoVer> objects) throws
WorkspaceCommunicationException {
final Map<ObjectIDNoWSNoVer, ObjectIDResolvedWS> queryobjs =
new HashMap<ObjectIDNoWSNoVer, ObjectIDResolvedWS>();
for (final ObjectIDNoWSNoVer o: objects) {
queryobjs.put(o, new ObjectIDResolvedWS(workspaceID, o));
}
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> res;
try {
res = resolveObjectIDs(
new HashSet<ObjectIDResolvedWS>(queryobjs.values()),
false, false);
} catch (NoSuchObjectException nsoe) {
throw new RuntimeException(
"Threw a NoSuchObjectException when explicitly told not to");
}
final Map<ObjectIDNoWSNoVer, ResolvedMongoObjectID> ret =
new HashMap<ObjectIDNoWSNoVer, ResolvedMongoObjectID>();
for (final ObjectIDNoWSNoVer o: objects) {
if (res.containsKey(queryobjs.get(o))) {
ret.put(o, res.get(queryobjs.get(o)));
}
}
return ret;
}
// save object in preexisting object container
private ObjectInformation saveObjectVersion(final WorkspaceUser user,
final ResolvedMongoWSID wsid, final long objectid,
final ObjectSavePackage pkg)
throws WorkspaceCommunicationException {
final Map<String, Object> version = new HashMap<String, Object>();
version.put(Fields.VER_SAVEDBY, user.getUser());
version.put(Fields.VER_CHKSUM, pkg.td.getChksum());
final List<Map<String, String>> meta =
new ArrayList<Map<String, String>>();
if (pkg.wo.getUserMeta() != null) {
for (String key: pkg.wo.getUserMeta().keySet()) {
Map<String, String> m = new LinkedHashMap<String, String>(2);
m.put(Fields.VER_META_KEY, key);
m.put(Fields.VER_META_VALUE, pkg.wo.getUserMeta().get(key));
meta.add(m);
}
}
version.put(Fields.VER_META, meta);
version.put(Fields.VER_REF, pkg.refs);
version.put(Fields.VER_PROVREF, pkg.provrefs);
version.put(Fields.VER_PROV, pkg.mprov.getMongoId());
version.put(Fields.VER_TYPE, pkg.wo.getRep().getValidationTypeDefId()
.getTypeString());
version.put(Fields.VER_SIZE, pkg.td.getSize());
version.put(Fields.VER_RVRT, null);
version.put(Fields.VER_COPIED, null);
saveObjectVersions(user, wsid, objectid, Arrays.asList(version),
pkg.wo.isHidden());
return new MongoObjectInfo(objectid, pkg.name,
pkg.wo.getRep().getValidationTypeDefId().getTypeString(),
(Date) version.get(Fields.VER_SAVEDATE),
(Integer) version.get(Fields.VER_VER),
user, wsid, pkg.td.getChksum(), pkg.td.getSize(),
pkg.wo.getUserMeta() == null ? new HashMap<String, String>() :
pkg.wo.getUserMeta());
}
private static final String M_SAVEINS_QRY = String.format("{%s: #, %s: #}",
Fields.OBJ_WS_ID, Fields.OBJ_ID);
private static final String M_SAVEINS_PROJ = String.format("{%s: 1, %s: 0}",
Fields.OBJ_VCNT, Fields.MONGO_ID);
private static final String M_SAVEINS_WTH = String.format(
"{$inc: {%s: #}, $set: {%s: false, %s: #, %s: null, %s: #}, $push: {%s: {$each: #}}}",
Fields.OBJ_VCNT, Fields.OBJ_DEL, Fields.OBJ_MODDATE,
Fields.OBJ_LATEST, Fields.OBJ_HIDE, Fields.OBJ_REFCOUNTS);
private static final String M_SAVEINS_NO_HIDE_WTH = String.format(
"{$inc: {%s: #}, $set: {%s: false, %s: #, %s: null}, $push: {%s: {$each: #}}}",
Fields.OBJ_VCNT, Fields.OBJ_DEL, Fields.OBJ_MODDATE,
Fields.OBJ_LATEST, Fields.OBJ_REFCOUNTS);
private void saveObjectVersions(final WorkspaceUser user,
final ResolvedMongoWSID wsid, final long objectid,
final List<Map<String, Object>> versions, final Boolean hidden)
throws WorkspaceCommunicationException {
// collection objects might be batchable if saves are slow
/* TODO deal with rare failure modes below as much as possible at some point. Not high prio since rare
* 1) save an object, crash w/ 0 versions. 2) increment versions, crash w/o saving
* check all places counter incremented (ws, obj, ver) to see if any other problems
* known issues in resolveObjects and listObjects
* can't necc count on the fact that vercount or latestVersion is accurate
* ignore listObjs for now, in resolveObjs mark vers with class and
* have queryVersions pull the right version if it's missing. Make a test for this.
* Have queryVersions revert to the newest version if the latest is missing, autorevert
*
* None of the above addresses the object w/ 0 versions failure. Not sure what to do about that.
*
*/
int ver;
final List<Integer> zeros = new LinkedList<Integer>();
for (int i = 0; i < versions.size(); i++) {
zeros.add(0);
}
final Date saved = new Date();
try {
FindAndModify q = wsjongo.getCollection(COL_WORKSPACE_OBJS)
.findAndModify(M_SAVEINS_QRY, wsid.getID(), objectid)
.returnNew();
if (hidden == null) {
q = q.with(M_SAVEINS_NO_HIDE_WTH, versions.size(),
saved, zeros);
} else {
q = q.with(M_SAVEINS_WTH, versions.size(), saved,
hidden, zeros);
}
ver = (Integer) q
.projection(M_SAVEINS_PROJ).as(DBObject.class)
.get(Fields.OBJ_VCNT)
- versions.size() + 1;
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
//TODO look into why saving array of maps via List.ToArray() /w Jongo makes Lazy?Objects return, which screw up everything
final List<DBObject> dbo = new LinkedList<DBObject>();
for (final Map<String, Object> v: versions) {
v.put(Fields.VER_SAVEDATE, saved);
v.put(Fields.VER_WS_ID, wsid.getID());
v.put(Fields.VER_ID, objectid);
v.put(Fields.VER_VER, ver++);
final DBObject d = new BasicDBObject();
for (final Entry<String, Object> e: v.entrySet()) {
d.put(e.getKey(), e.getValue());
}
dbo.add(d);
}
try {
wsmongo.getCollection(COL_WORKSPACE_VERS).insert(dbo);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
//TODO make all projections not include _id unless specified
private static final String M_UNIQ_NAME_QRY = String.format(
"{%s: #, %s: {$regex: '^#(-\\\\d+)?$'}}", Fields.OBJ_WS_ID,
Fields.OBJ_NAME);
private static final String M_UNIQ_NAME_PROJ = String.format(
"{%s: 1, %s: 0}", Fields.OBJ_NAME, Fields.MONGO_ID);
private String generateUniqueNameForObject(final ResolvedWorkspaceID wsid,
final long objectid) throws WorkspaceCommunicationException {
final String prefix = "auto" + objectid;
@SuppressWarnings("rawtypes")
Iterable<Map> ids;
try {
ids = wsjongo.getCollection(COL_WORKSPACE_OBJS)
.find(M_UNIQ_NAME_QRY, wsid.getID(), prefix)
.projection(M_UNIQ_NAME_PROJ).as(Map.class);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
boolean exact = false;
final Set<Long> suffixes = new HashSet<Long>();
for (@SuppressWarnings("rawtypes") Map m: ids) {
final String[] id = ((String) m.get(Fields.OBJ_NAME)).split("-");
if (id.length == 2) {
try {
suffixes.add(Long.parseLong(id[1]));
} catch (NumberFormatException e) {
// do nothing
}
} else if (id.length == 1) {
try {
exact = exact || prefix.equals(id[0]);
} catch (NumberFormatException e) {
// do nothing
}
}
}
if (!exact) {
return prefix;
}
long counter = 1;
while (suffixes.contains(counter)) {
counter++;
}
return prefix + "-" + counter;
}
//save brand new object - create container
//objectid *must not exist* in the workspace otherwise this method will recurse indefinitely
//the workspace must exist
private IDName saveWorkspaceObject(
final ResolvedMongoWSID wsid, final long objectid,
final String name)
throws WorkspaceCommunicationException {
String newName = name;
if (name == null) {
newName = generateUniqueNameForObject(wsid, objectid);
}
final DBObject dbo = new BasicDBObject();
dbo.put(Fields.OBJ_WS_ID, wsid.getID());
dbo.put(Fields.OBJ_ID, objectid);
dbo.put(Fields.OBJ_VCNT, 0); //Integer
dbo.put(Fields.OBJ_REFCOUNTS, new LinkedList<Integer>());
dbo.put(Fields.OBJ_NAME, newName);
dbo.put(Fields.OBJ_LATEST, null);
dbo.put(Fields.OBJ_DEL, false);
dbo.put(Fields.OBJ_HIDE, false);
try {
//maybe could speed things up with batch inserts but dealing with
//errors would really suck
//do this later if it becomes a bottleneck
wsmongo.getCollection(COL_WORKSPACE_OBJS).insert(dbo);
} catch (MongoException.DuplicateKey dk) {
//ok, someone must've just this second added this name to an object
//asshole
//this should be a rare event
//TODO is this a name or id clash? if the latter, something is broken
if (name == null) {
//not much chance of this happening again, let's just recurse
//and make a new name again
return saveWorkspaceObject(wsid, objectid, name);
}
final ObjectIDNoWSNoVer o = new ObjectIDNoWSNoVer(name);
final Map<ObjectIDNoWSNoVer, ResolvedMongoObjectID> objID =
resolveObjectIDs(wsid,
new HashSet<ObjectIDNoWSNoVer>(Arrays.asList(o)));
if (objID.isEmpty()) {
//oh ffs, name deleted again, try again
return saveWorkspaceObject(wsid, objectid, name);
}
//save version via the id associated with our name which already exists
return new IDName(objID.get(o).getId(), objID.get(o).getName());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return new IDName(objectid, newName);
}
private class IDName {
public long id;
public String name;
public IDName(long id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "IDName [id=" + id + ", name=" + name + "]";
}
}
private static class ObjectSavePackage {
public ResolvedSaveObject wo;
public String name;
public TypeData td;
public Set<String> refs;
public List<String> provrefs;
public MongoProvenance mprov;
@Override
public String toString() {
return "ObjectSavePackage [wo=" + wo + ", name=" + name + ", td="
+ td + ", mprov =" + mprov + "]";
}
}
private static final ObjectMapper MAPPER = new ObjectMapper();
private static String getObjectErrorId(final ObjectIDNoWSNoVer oi,
final int objcount) {
String objErrId = "#" + objcount;
objErrId += oi == null ? "" : ", " + oi.getIdentifierString();
return objErrId;
}
//at this point the objects are expected to be validated and references rewritten
private List<ObjectSavePackage> saveObjectsBuildPackages(
final List<ResolvedSaveObject> objects) {
//this method must maintain the order of the objects
int objnum = 1;
final List<ObjectSavePackage> ret = new LinkedList<ObjectSavePackage>();
for (ResolvedSaveObject o: objects) {
if (o.getRep().getValidationTypeDefId().getMd5() != null) {
throw new RuntimeException("MD5 types are not accepted");
}
final ObjectSavePackage pkg = new ObjectSavePackage();
pkg.refs = checkRefsAreMongo(o.getRefs());
//cannot do by combining in one set since a non-MongoReference
//could be overwritten by a MongoReference if they have the same
//hash
pkg.provrefs = checkRefsAreMongo(o.getProvRefs());
pkg.wo = o;
checkObjectLength(o.getProvenance(), MAX_PROV_SIZE,
o.getObjectIdentifier(), objnum, "provenance");
final Map<String, Object> subdata;
try {
@SuppressWarnings("unchecked")
final Map<String, Object> subdata2 = (Map<String, Object>)
MAPPER.treeToValue(
o.getRep().extractSearchableWsSubset(),
Map.class);
subdata = subdata2;
} catch (JsonProcessingException jpe) {
throw new RuntimeException(
"Should never get a JSON exception here", jpe);
}
escapeSubdata(subdata);
checkObjectLength(subdata, MAX_SUBDATA_SIZE,
o.getObjectIdentifier(), objnum, "subdata");
//could save time by making type->data->TypeData map and reusing
//already calced TDs, but hardly seems worth it - unlikely event
pkg.td = new TypeData(o.getRep().getJsonInstance(),
o.getRep().getValidationTypeDefId(), subdata);
if (pkg.td.getSize() > MAX_OBJECT_SIZE) {
throw new IllegalArgumentException(String.format(
"Object %s data size %s exceeds limit of %s",
getObjectErrorId(o.getObjectIdentifier(), objnum),
pkg.td.getSize(), MAX_OBJECT_SIZE));
}
ret.add(pkg);
objnum++;
}
return ret;
}
//is there some way to combine these with generics?
private Set<String> checkRefsAreMongo(final Set<Reference> refs) {
final Set<String> newrefs = new HashSet<String>();
checkRefsAreMongoInternal(refs, newrefs);
return newrefs;
}
//order must be maintained
private List<String> checkRefsAreMongo(final List<Reference> refs) {
final List<String> newrefs = new LinkedList<String>();
checkRefsAreMongoInternal(refs, newrefs);
return newrefs;
}
private void checkRefsAreMongoInternal(final Collection<Reference> refs,
final Collection<String> newrefs) {
for (final Reference r: refs) {
if (!(r instanceof MongoReference)) {
throw new RuntimeException(
"Improper reference implementation: " +
(r == null ? null : r.getClass()));
}
newrefs.add(r.toString());
}
}
private void checkObjectLength(final Object o, final long max,
final ObjectIDNoWSNoVer oi, final int objnum,
final String objtype) {
final CountingOutputStream cos = new CountingOutputStream();
try {
//writes in UTF8
MAPPER.writeValue(cos, o);
} catch (IOException ioe) {
throw new RuntimeException("something's broken", ioe);
} finally {
try {
cos.close();
} catch (IOException ioe) {
throw new RuntimeException("something's broken", ioe);
}
}
if (cos.getSize() > max) {
throw new IllegalArgumentException(String.format(
"Object %s %s size %s exceeds limit of %s",
getObjectErrorId(oi, objnum), objtype, cos.getSize(), max));
}
}
private void escapeSubdata(final Map<String, Object> subdata) {
escapeSubdataInternal(subdata);
}
//rewrite w/o recursion?
private Object escapeSubdataInternal(final Object o) {
if (o instanceof String || o instanceof Number ||
o instanceof Boolean || o == null) {
return o;
} else if (o instanceof List) {
@SuppressWarnings("unchecked")
final List<Object> l = (List<Object>)o;
for (Object lo: l) {
escapeSubdataInternal(lo);
}
return o;
} else if (o instanceof Map) {
@SuppressWarnings("unchecked")
final Map<String, Object> m = (Map<String, Object>)o;
//save updated keys in separate map so we don't overwrite
//keys before they're escaped
final Map<String, Object> newm = new HashMap<String, Object>();
final Iterator<Entry<String, Object>> iter = m.entrySet().iterator();
while (iter.hasNext()) {
final Entry<String, Object> e = iter.next();
final String key = e.getKey();
//need side effect
final Object value = escapeSubdataInternal(e.getValue());
final String newkey = mongoHTMLEscape(key);
//works since mongoHTMLEscape returns same string object if no change
if (key != newkey) {
iter.remove();
newm.put(newkey, value);
}
}
m.putAll(newm);
return o;
} else {
throw new RuntimeException("Unsupported class: " + o.getClass());
}
}
private static final int CODEPOINT_PERC = new String("%").codePointAt(0);
private static final int CODEPOINT_DLR = new String("$").codePointAt(0);
private static final int CODEPOINT_PNT = new String(".").codePointAt(0);
//might be faster just using std string replace() method
private String mongoHTMLEscape(final String s) {
final StringBuilder ret = new StringBuilder();
boolean mod = false;
for (int offset = 0; offset < s.length(); ) {
final int codepoint = s.codePointAt(offset);
if (codepoint == CODEPOINT_PERC) {
ret.append("%25");
mod = true;
} else if (codepoint == CODEPOINT_DLR) {
ret.append("%24");
mod = true;
} else if (codepoint == CODEPOINT_PNT) {
ret.append("%2e");
mod = true;
} else {
ret.appendCodePoint(codepoint);
}
offset += Character.charCount(codepoint);
}
if (mod) {
return ret.toString();
} else {
return s;
}
}
private static final String M_SAVE_QRY = String.format("{%s: #}",
Fields.WS_ID);
private static final String M_SAVE_WTH = String.format("{$inc: {%s: #}}",
Fields.WS_NUMOBJ);
private static final String M_SAVE_PROJ = String.format("{%s: 1, %s: 0}",
Fields.WS_NUMOBJ, Fields.MONGO_ID);
//at this point the objects are expected to be validated and references rewritten
@Override
public List<ObjectInformation> saveObjects(final WorkspaceUser user,
final ResolvedWorkspaceID rwsi,
final List<ResolvedSaveObject> objects)
throws WorkspaceCommunicationException,
NoSuchObjectException {
//TODO break this up
//this method must maintain the order of the objects
final ResolvedMongoWSID wsidmongo = query.convertResolvedWSID(rwsi);
final List<ObjectSavePackage> packages = saveObjectsBuildPackages(
objects);
final Map<ObjectIDNoWSNoVer, List<ObjectSavePackage>> idToPkg =
new HashMap<ObjectIDNoWSNoVer, List<ObjectSavePackage>>();
int newobjects = 0;
for (final ObjectSavePackage p: packages) {
final ObjectIDNoWSNoVer o = p.wo.getObjectIdentifier();
if (o != null) {
if (idToPkg.get(o) == null) {
idToPkg.put(o, new ArrayList<ObjectSavePackage>());
}
idToPkg.get(o).add(p);
} else {
newobjects++;
}
}
final Map<ObjectIDNoWSNoVer, ResolvedMongoObjectID> objIDs =
resolveObjectIDs(wsidmongo, idToPkg.keySet());
for (ObjectIDNoWSNoVer o: idToPkg.keySet()) {
if (!objIDs.containsKey(o)) {
if (o.getId() != null) {
throw new NoSuchObjectException(
"There is no object with id " + o.getId());
} else {
for (ObjectSavePackage pkg: idToPkg.get(o)) {
pkg.name = o.getName();
}
newobjects++;
}
} else {
for (ObjectSavePackage pkg: idToPkg.get(o)) {
pkg.name = objIDs.get(o).getName();
}
}
}
//at this point everything should be ready to save, only comm errors
//can stop us now, the world is doomed
saveData(wsidmongo, packages);
saveProvenance(packages);
updateReferenceCounts(packages);
long newid = incrementWorkspaceCounter(wsidmongo, newobjects);
/* alternate impl: 1) make all save objects 2) increment all version
* counters 3) batch save versions
* This probably won't help much. Firstly, saving the same object
* multiple times (e.g. save over the same object in the same
* saveObjects call) is going to be a rare op - who wants to do that?
* Hence batching up the version increments is probably not going to
* help much.
* Secondly, the write lock is on a per document basis, so batching
* writes has no effect on write locking.
* That means that the gain from batching writes is removal of the
* flight time to/from the server between each object. This may
* be significant for many small objects, but is probably
* insignificant for a few objects, or many large objects.
* Summary: probably not worth the trouble and increase in code
* complexity.
*/
final List<ObjectInformation> ret = new ArrayList<ObjectInformation>();
final Map<String, Long> seenNames = new HashMap<String, Long>();
for (final ObjectSavePackage p: packages) {
final ObjectIDNoWSNoVer oi = p.wo.getObjectIdentifier();
if (oi == null) { //no name given, need to generate one
final IDName obj = saveWorkspaceObject(wsidmongo, newid++,
null);
p.name = obj.name;
ret.add(saveObjectVersion(user, wsidmongo, obj.id, p));
} else if (oi.getId() != null) { //confirmed ok id
ret.add(saveObjectVersion(user, wsidmongo, oi.getId(), p));
} else if (objIDs.get(oi) != null) {//given name translated to id
ret.add(saveObjectVersion(user, wsidmongo, objIDs.get(oi).getId(), p));
} else if (seenNames.containsKey(oi.getName())) {
//we've already generated an id for this name
ret.add(saveObjectVersion(user, wsidmongo, seenNames.get(oi.getName()), p));
} else {//new name, need to generate new id
final IDName obj = saveWorkspaceObject(wsidmongo, newid++,
oi.getName());
p.name = obj.name;
seenNames.put(obj.name, obj.id);
ret.add(saveObjectVersion(user, wsidmongo, obj.id, p));
}
}
return ret;
}
//returns starting object number
private long incrementWorkspaceCounter(final ResolvedMongoWSID wsidmongo,
final int newobjects) throws WorkspaceCommunicationException {
final long lastid;
try {
lastid = ((Number) wsjongo.getCollection(COL_WORKSPACES)
.findAndModify(M_SAVE_QRY, wsidmongo.getID())
.returnNew().with(M_SAVE_WTH, (long) newobjects)
.projection(M_SAVE_PROJ)
.as(DBObject.class).get(Fields.WS_NUMOBJ)).longValue();
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
long newid = lastid - newobjects + 1;
return newid;
}
private void saveProvenance(final List<ObjectSavePackage> packages)
throws WorkspaceCommunicationException {
final List<MongoProvenance> prov = new LinkedList<MongoProvenance>();
for (final ObjectSavePackage p: packages) {
final MongoProvenance mp = new MongoProvenance(
p.wo.getProvenance());
prov.add(mp);
p.mprov = mp;
}
try {
wsjongo.getCollection(COL_PROVENANCE).insert((Object[])
prov.toArray(new MongoProvenance[prov.size()]));
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
private class VerCount {
final public int ver;
final public int count;
public VerCount (final int ver, final int count) {
this.ver = ver;
this.count = count;
}
@Override
public String toString() {
return "VerCount [ver=" + ver + ", count=" + count + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + count;
result = prime * result + ver;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof VerCount)) {
return false;
}
VerCount other = (VerCount) obj;
if (!getOuterType().equals(other.getOuterType())) {
return false;
}
if (count != other.count) {
return false;
}
if (ver != other.ver) {
return false;
}
return true;
}
private MongoWorkspaceDB getOuterType() {
return MongoWorkspaceDB.this;
}
}
private void updateReferenceCounts(final List<ObjectSavePackage> packages)
throws WorkspaceCommunicationException {
//TODO when garbage collection working much more testing of these methods
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts =
countReferences(packages);
/* since the version numbers are probably highly skewed towards 1 and
* the reference counts are also highly skewed towards 1 we can
* probably minimize the number of updates by running one update
* per version/count combination
*/
updateReferenceCounts(refcounts);
}
private void updateReferenceCountsForVersions(
final List<Map<String, Object>> versions)
throws WorkspaceCommunicationException {
//TODO when garbage collection working much more testing of these methods
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts =
countReferencesForVersions(versions);
/* since the version numbers are probably highly skewed towards 1 and
* the reference counts are also highly skewed towards 1 we can
* probably minimize the number of updates by running one update
* per version/count combination
*/
updateReferenceCounts(refcounts);
}
private void updateReferenceCounts(
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts)
throws WorkspaceCommunicationException {
final Map<VerCount, Map<Long, List<Long>>> queries =
new HashMap<VerCount, Map<Long,List<Long>>>();
for (final Long ws: refcounts.keySet()) {
for (final Long obj: refcounts.get(ws).keySet()) {
for (final Integer ver: refcounts.get(ws).get(obj).keySet()) {
final VerCount vc = new VerCount(ver,
refcounts.get(ws).get(obj).get(ver).getValue());
if (!queries.containsKey(vc)) {
queries.put(vc, new HashMap<Long, List<Long>>());
}
if (!queries.get(vc).containsKey(ws)) {
queries.get(vc).put(ws, new LinkedList<Long>());
}
queries.get(vc).get(ws).add(obj);
}
}
}
for (final VerCount vc: queries.keySet()) {
updateReferenceCounts(vc, queries.get(vc));
}
}
private void updateReferenceCounts(final VerCount vc,
final Map<Long, List<Long>> wsToObjs)
throws WorkspaceCommunicationException {
final DBObject update = new BasicDBObject("$inc",
new BasicDBObject(Fields.OBJ_REFCOUNTS + "." + (vc.ver - 1),
vc.count));
final List<DBObject> orquery = new LinkedList<DBObject>();
for (final Long ws: wsToObjs.keySet()) {
final DBObject query = new BasicDBObject(Fields.OBJ_WS_ID, ws);
query.put(Fields.OBJ_ID, new BasicDBObject("$in",
wsToObjs.get(ws)));
orquery.add(query);
}
try {
wsmongo.getCollection(COL_WORKSPACE_OBJS).update(
new BasicDBObject("$or", orquery), update, false, true);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
private Map<Long, Map<Long, Map<Integer, Counter>>> countReferences(
final List<ObjectSavePackage> packages) {
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts =
new HashMap<Long, Map<Long,Map<Integer,Counter>>>();
for (final ObjectSavePackage p: packages) {
//these were checked to be MongoReferences in saveObjectBuildPackages
final Set<Reference> refs = new HashSet<Reference>();
refs.addAll(p.wo.getRefs());
refs.addAll(p.wo.getProvRefs());
countReferences(refcounts, refs);
}
return refcounts;
}
private Map<Long, Map<Long, Map<Integer, Counter>>> countReferencesForVersions(
final List<Map<String, Object>> versions) {
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts =
new HashMap<Long, Map<Long,Map<Integer,Counter>>>();
for (final Map<String, Object> p: versions) {
//these were checked to be MongoReferences in saveObjectBuildPackages
final Set<Reference> refs = new HashSet<Reference>();
@SuppressWarnings("unchecked")
final List<String> objrefs = (List<String>) p.get(Fields.VER_REF);
@SuppressWarnings("unchecked")
final List<String> provrefs = (List<String>) p.get(Fields.VER_PROVREF);
// objrefs.addAll(provrefs); //DON'T DO THIS YOU MORON
for (final String s: objrefs) {
refs.add(new MongoReference(s));
}
for (final String s: provrefs) {
refs.add(new MongoReference(s));
}
countReferences(refcounts, refs);
}
return refcounts;
}
private void countReferences(
final Map<Long, Map<Long, Map<Integer, Counter>>> refcounts,
final Set<Reference> refs) {
for (final Reference r: refs) {
if (!refcounts.containsKey(r.getWorkspaceID())) {
refcounts.put(r.getWorkspaceID(),
new HashMap<Long, Map<Integer, Counter>>());
}
if (!refcounts.get(r.getWorkspaceID())
.containsKey(r.getObjectID())) {
refcounts.get(r.getWorkspaceID()).put(r.getObjectID(),
new HashMap<Integer, Counter>());
}
if (!refcounts.get(r.getWorkspaceID()).get(r.getObjectID())
.containsKey(r.getVersion())) {
refcounts.get(r.getWorkspaceID()).get(r.getObjectID())
.put(r.getVersion(), new Counter());
}
refcounts.get(r.getWorkspaceID()).get(r.getObjectID())
.get(r.getVersion()).increment();
}
}
private void saveData(final ResolvedMongoWSID workspaceid,
final List<ObjectSavePackage> data) throws
WorkspaceCommunicationException {
final Map<TypeDefId, List<ObjectSavePackage>> pkgByType =
new HashMap<TypeDefId, List<ObjectSavePackage>>();
for (final ObjectSavePackage p: data) {
if (pkgByType.get(p.td.getType()) == null) {
pkgByType.put(p.td.getType(), new ArrayList<ObjectSavePackage>());
}
pkgByType.get(p.td.getType()).add(p);
}
for (final TypeDefId type: pkgByType.keySet()) {
ensureTypeIndex(type);
final String col = TypeData.getTypeCollection(type);
final Map<String, TypeData> chksum = new HashMap<String, TypeData>();
for (ObjectSavePackage p: pkgByType.get(type)) {
chksum.put(p.td.getChksum(), p.td);
}
final DBObject query = new BasicDBObject(Fields.TYPE_CHKSUM,
new BasicDBObject("$in", new ArrayList<String>(
chksum.keySet())));
final DBObject proj = new BasicDBObject(Fields.TYPE_CHKSUM, 1);
proj.put(Fields.MONGO_ID, 0);
DBCursor res;
try {
res = wsmongo.getCollection(col).find(query, proj);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final Set<String> existChksum = new HashSet<String>();
for (DBObject dbo: res) {
existChksum.add((String)dbo.get(Fields.TYPE_CHKSUM));
}
final List<TypeData> newdata = new ArrayList<TypeData>();
for (String md5: chksum.keySet()) {
if (existChksum.contains(md5)) {
continue;
}
newdata.add(chksum.get(md5));
try {
//this is kind of stupid, but no matter how you slice it you have
//to calc md5s before you save the data
blob.saveBlob(new MD5(md5), chksum.get(md5).getData());
} catch (BlobStoreCommunicationException e) {
throw new WorkspaceCommunicationException(
e.getLocalizedMessage(), e);
} catch (BlobStoreAuthorizationException e) {
throw new WorkspaceCommunicationException(
"Authorization error communicating with the backend storage system",
e);
}
}
try {
wsjongo.getCollection(col).insert((Object[]) newdata.toArray(
new TypeData[newdata.size()]));
} catch (MongoException.DuplicateKey dk) {
//At least one of the data objects was just inserted by another
//thread, which is fine - do nothing
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
}
private static final Set<String> FLDS_VER_GET_OBJECT_SUBDATA = newHashSet(
Fields.VER_VER, Fields.VER_TYPE, Fields.VER_CHKSUM);
private static final String M_GETOBJSUB_QRY = String.format(
"{%s: {$in: #}}", Fields.TYPE_CHKSUM);
private static final String M_GETOBJSUB_PROJ = String.format(
"{%s: 1, %s: 1, %s: 0}",
Fields.TYPE_CHKSUM, Fields.TYPE_SUBDATA, Fields.MONGO_ID);
public Map<ObjectIDResolvedWS, Map<String, Object>> getObjectSubData(
final Set<ObjectIDResolvedWS> objectIDs)
throws NoSuchObjectException, WorkspaceCommunicationException {
//keep doing the next two lines over and over, should probably extract
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> oids =
resolveObjectIDs(objectIDs);
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(
new HashSet<ResolvedMongoObjectID>(oids.values()),
FLDS_VER_GET_OBJECT_SUBDATA);
final Map<TypeDefId, Map<String, Set<ObjectIDResolvedWS>>> toGet =
new HashMap<TypeDefId, Map<String,Set<ObjectIDResolvedWS>>>();
for (final ObjectIDResolvedWS oid: objectIDs) {
final ResolvedMongoObjectID roi = oids.get(oid);
if (!vers.containsKey(roi)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", roi.getId(), roi.getName(),
roi.getVersion(),
roi.getWorkspaceIdentifier().getID()), oid);
}
final Map<String, Object> v = vers.get(roi);
final TypeDefId type = TypeDefId.fromTypeString(
(String) v.get(Fields.VER_TYPE));
final String md5 = (String) v.get(Fields.VER_CHKSUM);
if (!toGet.containsKey(type)) {
toGet.put(type, new HashMap<String, Set<ObjectIDResolvedWS>>());
}
if (!toGet.get(type).containsKey(md5)) {
toGet.get(type).put(md5, new HashSet<ObjectIDResolvedWS>());
}
toGet.get(type).get(md5).add(oid);
}
final Map<ObjectIDResolvedWS, Map<String, Object>> ret =
new HashMap<ObjectIDResolvedWS, Map<String,Object>>();
for (final TypeDefId type: toGet.keySet()) {
@SuppressWarnings("rawtypes")
final Iterable<Map> subdata;
try {
subdata = wsjongo.getCollection(TypeData.getTypeCollection(type))
.find(M_GETOBJSUB_QRY, toGet.get(type).keySet())
.projection(M_GETOBJSUB_PROJ).as(Map.class);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
for (@SuppressWarnings("rawtypes") final Map m: subdata) {
final String md5 = (String) m.get(Fields.TYPE_CHKSUM);
@SuppressWarnings("unchecked")
final Map<String, Object> sd =
(Map<String, Object>) m.get(Fields.TYPE_SUBDATA);
for (final ObjectIDResolvedWS o: toGet.get(type).get(md5)) {
ret.put(o, sd);
}
}
}
return ret;
}
private static final Set<String> FLDS_VER_GET_OBJECT = newHashSet(
Fields.VER_VER, Fields.VER_META, Fields.VER_TYPE,
Fields.VER_SAVEDATE, Fields.VER_SAVEDBY,
Fields.VER_CHKSUM, Fields.VER_SIZE, Fields.VER_PROV,
Fields.VER_PROVREF, Fields.VER_REF);
@Override
public Map<ObjectIDResolvedWS, WorkspaceObjectData> getObjects(
final Set<ObjectIDResolvedWS> objectIDs) throws
NoSuchObjectException, WorkspaceCommunicationException,
CorruptWorkspaceDBException {
final Map<ObjectIDResolvedWS, ObjectPaths> paths =
new HashMap<ObjectIDResolvedWS, ObjectPaths>();
for (final ObjectIDResolvedWS o: objectIDs) {
paths.put(o, null);
}
try {
return getObjects(paths);
} catch (TypedObjectExtractionException toee) {
throw new RuntimeException(
"No extraction done, so something's very wrong here", toee);
}
}
@Override
public Map<ObjectIDResolvedWS, WorkspaceObjectData> getObjects(
final Map<ObjectIDResolvedWS, ObjectPaths> objects) throws
NoSuchObjectException, WorkspaceCommunicationException,
CorruptWorkspaceDBException, TypedObjectExtractionException {
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> oids =
resolveObjectIDs(objects.keySet());
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(
new HashSet<ResolvedMongoObjectID>(oids.values()),
FLDS_VER_GET_OBJECT);
final Map<ObjectId, MongoProvenance> provs = getProvenance(vers);
final Map<String, JsonNode> chksumToData = new HashMap<String, JsonNode>();
final Map<ObjectIDResolvedWS, WorkspaceObjectData> ret =
new HashMap<ObjectIDResolvedWS, WorkspaceObjectData>();
for (ObjectIDResolvedWS o: objects.keySet()) {
final ResolvedMongoObjectID roi = oids.get(o);
if (!vers.containsKey(roi)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", roi.getId(), roi.getName(),
roi.getVersion(),
roi.getWorkspaceIdentifier().getID()), o);
}
final MongoProvenance prov = provs.get((ObjectId) vers.get(roi)
.get(Fields.VER_PROV));
@SuppressWarnings("unchecked")
final List<String> refs =
(List<String>) vers.get(roi).get(Fields.VER_REF);
final MongoObjectInfo meta = generateObjectInfo(
roi, vers.get(roi));
if (chksumToData.containsKey(meta.getCheckSum())) {
/* might be subsetting the same object the same way multiple
* times, but probably unlikely. If it becomes a problem
* memoize the subset
*/
ret.put(o, new WorkspaceObjectData(getDataSubSet(
chksumToData.get(meta.getCheckSum()), objects.get(o)),
meta, prov, refs));
} else {
final JsonNode data;
try {
data = blob.getBlob(new MD5(meta.getCheckSum()));
} catch (BlobStoreCommunicationException e) {
throw new WorkspaceCommunicationException(
e.getLocalizedMessage(), e);
} catch (BlobStoreAuthorizationException e) {
throw new WorkspaceCommunicationException(
"Authorization error communicating with the backend storage system",
e);
} catch (NoSuchBlobException e) {
throw new CorruptWorkspaceDBException(String.format(
"No data present for valid object %s.%s.%s",
meta.getWorkspaceId(), meta.getObjectId(),
meta.getVersion()), e);
}
chksumToData.put(meta.getCheckSum(), data);
ret.put(o, new WorkspaceObjectData(getDataSubSet(
data, objects.get(o)), meta, prov, refs));
}
}
return ret;
}
private JsonNode getDataSubSet(final JsonNode data,
final ObjectPaths paths)
throws TypedObjectExtractionException {
if (paths == null || paths.isEmpty()) {
return data;
}
return TypedObjectExtractor.extract(paths, data);
}
private static final Set<String> FLDS_GETREFOBJ = newHashSet(
Fields.VER_VER, Fields.VER_TYPE, Fields.VER_META,
Fields.VER_SAVEDATE, Fields.VER_SAVEDBY,
Fields.VER_CHKSUM, Fields.VER_SIZE,
Fields.VER_PROVREF, Fields.VER_REF);
@Override
public Map<ObjectIDResolvedWS, Set<ObjectInformation>>
getReferencingObjects(final PermissionSet perms,
final Set<ObjectIDResolvedWS> objs)
throws NoSuchObjectException, WorkspaceCommunicationException {
final List<Long> wsids = new LinkedList<Long>();
for (final ResolvedWorkspaceID ws: perms.getWorkspaces()) {
wsids.add(ws.getID());
}
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> resobjs =
resolveObjectIDs(objs);
verifyVersions(new HashSet<ResolvedMongoObjectID>(resobjs.values()));
final Map<String, Set<ObjectIDResolvedWS>> ref2id =
new HashMap<String, Set<ObjectIDResolvedWS>>();
for (final ObjectIDResolvedWS oi: objs) {
final ResolvedMongoObjectID r = resobjs.get(oi);
final String ref = r.getReference().toString();
if (!ref2id.containsKey(ref)) {
ref2id.put(ref, new HashSet<ObjectIDResolvedWS>());
}
ref2id.get(ref).add(oi);
}
final DBObject q = new BasicDBObject(Fields.VER_WS_ID,
new BasicDBObject("$in", wsids));
q.put("$or", Arrays.asList(
new BasicDBObject(Fields.VER_REF,
new BasicDBObject("$in", ref2id.keySet())),
new BasicDBObject(Fields.VER_PROVREF,
new BasicDBObject("$in", ref2id.keySet()))));
final List<Map<String, Object>> vers = query.queryCollection(
COL_WORKSPACE_VERS, q, FLDS_GETREFOBJ);
final Map<Map<String, Object>, ObjectInformation> voi =
generateObjectInfo(perms, vers, true, false, false, true);
final Map<ObjectIDResolvedWS, Set<ObjectInformation>> ret =
new HashMap<ObjectIDResolvedWS, Set<ObjectInformation>>();
for (final ObjectIDResolvedWS o: objs) {
ret.put(o, new HashSet<ObjectInformation>());
}
for (final Map<String, Object> ver: voi.keySet()) {
@SuppressWarnings("unchecked")
final List<String> refs = (List<String>) ver.get(Fields.VER_REF);
@SuppressWarnings("unchecked")
final List<String> provrefs = (List<String>) ver.get(
Fields.VER_PROVREF);
refs.addAll(provrefs);
for (final String ref: refs) {
if (ref2id.containsKey(ref)) {
for (final ObjectIDResolvedWS oi: ref2id.get(ref)) {
ret.get(oi).add(voi.get(ver));
}
}
}
}
return ret;
}
private Map<ObjectId, MongoProvenance> getProvenance(
final Map<ResolvedMongoObjectID, Map<String, Object>> vers)
throws WorkspaceCommunicationException {
final Map<ObjectId, Map<String, Object>> provIDs =
new HashMap<ObjectId, Map<String,Object>>();
for (final ResolvedMongoObjectID id: vers.keySet()) {
provIDs.put((ObjectId) vers.get(id).get(Fields.VER_PROV),
vers.get(id));
}
final Iterable<MongoProvenance> provs;
try {
provs = wsjongo.getCollection(COL_PROVENANCE)
.find("{_id: {$in: #}}", provIDs.keySet())
.as(MongoProvenance.class);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
final Map<ObjectId, MongoProvenance> ret =
new HashMap<ObjectId, MongoProvenance>();
for (MongoProvenance p: provs) {
@SuppressWarnings("unchecked")
final List<String> resolvedRefs = (List<String>) provIDs
.get(p.getMongoId()).get(Fields.VER_PROVREF);
ret.put(p.getMongoId(), p);
p.resolveReferences(resolvedRefs); //this is a gross hack. I'm rather proud of it actually
}
return ret;
}
private MongoObjectInfo generateObjectInfo(
final ResolvedMongoObjectID roi, final Map<String, Object> ver) {
return generateObjectInfo(roi.getWorkspaceIdentifier(), roi.getId(),
roi.getName(), ver);
}
private MongoObjectInfo generateObjectInfo(
final ResolvedMongoWSID rwsi, final long objid, final String name,
final Map<String, Object> ver) {
@SuppressWarnings("unchecked")
final List<Map<String, String>> meta =
(List<Map<String, String>>) ver.get(Fields.VER_META);
return new MongoObjectInfo(
objid,
name,
(String) ver.get(Fields.VER_TYPE),
(Date) ver.get(Fields.VER_SAVEDATE),
(Integer) ver.get(Fields.VER_VER),
new WorkspaceUser((String) ver.get(Fields.VER_SAVEDBY)),
rwsi,
(String) ver.get(Fields.VER_CHKSUM),
(Long) ver.get(Fields.VER_SIZE),
meta == null ? null : metaMongoArrayToHash(meta));
}
private static final Set<String> FLDS_VER_TYPE = newHashSet(
Fields.VER_TYPE, Fields.VER_VER);
public Map<ObjectIDResolvedWS, TypeAndReference> getObjectType(
final Set<ObjectIDResolvedWS> objectIDs) throws
NoSuchObjectException, WorkspaceCommunicationException {
//this method is a pattern - generalize somehow?
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> oids =
resolveObjectIDs(objectIDs);
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(
new HashSet<ResolvedMongoObjectID>(oids.values()),
FLDS_VER_TYPE);
final Map<ObjectIDResolvedWS, TypeAndReference> ret =
new HashMap<ObjectIDResolvedWS, TypeAndReference>();
for (ObjectIDResolvedWS o: objectIDs) {
final ResolvedMongoObjectID roi = oids.get(o);
if (!vers.containsKey(roi)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", roi.getId(), roi.getName(),
roi.getVersion(),
roi.getWorkspaceIdentifier().getID()), o);
}
ret.put(o, new TypeAndReference(
AbsoluteTypeDefId.fromAbsoluteTypeString(
(String) vers.get(roi).get(Fields.VER_TYPE)),
new MongoReference(roi.getWorkspaceIdentifier().getID(),
roi.getId(),
(Integer) vers.get(roi).get(Fields.VER_VER))));
}
return ret;
}
private static final Set<String> FLDS_LIST_OBJ_VER = newHashSet(
Fields.VER_VER, Fields.VER_TYPE, Fields.VER_SAVEDATE,
Fields.VER_SAVEDBY, Fields.VER_VER, Fields.VER_CHKSUM,
Fields.VER_SIZE, Fields.VER_ID, Fields.VER_WS_ID);
private static final Set<String> FLDS_LIST_OBJ = newHashSet(
Fields.OBJ_ID, Fields.OBJ_NAME, Fields.OBJ_DEL, Fields.OBJ_HIDE,
Fields.OBJ_LATEST, Fields.OBJ_VCNT, Fields.OBJ_WS_ID);
private static final String LATEST_VERSION = "latestVersion";
@Override
public List<ObjectInformation> getObjectInformation(
final PermissionSet pset, final TypeDefId type,
final List<WorkspaceUser> savedby, final Map<String, String> meta,
final boolean showHidden, final boolean showDeleted,
final boolean showOnlyDeleted, final boolean showAllVers,
final boolean includeMetadata)
throws WorkspaceCommunicationException {
//TODO yet another long method that needs pruning
/* Could make this method more efficient by doing different queries
* based on the filters. If there's no filters except the workspace,
* for example, just grab all the objects for the workspaces,
* filtering out hidden and deleted in the query and pull the most
* recent versions for the remaining objects. For now, just go
* with a dumb general method and add smarter heuristics as needed.
*/
if (!(pset instanceof MongoPermissionSet)) {
throw new IllegalArgumentException(
"Illegal implementation of PermissionSet: " +
pset.getClass().getName());
}
if (pset.isEmpty()) {
return new LinkedList<ObjectInformation>();
}
final DBObject verq = new BasicDBObject();
final Map<Long, ResolvedWorkspaceID> ids =
new HashMap<Long, ResolvedWorkspaceID>();
for (final ResolvedWorkspaceID rwsi: pset.getWorkspaces()) {
final ResolvedMongoWSID rm = query.convertResolvedWSID(rwsi);
ids.put(rm.getID(), rm);
}
verq.put(Fields.VER_WS_ID, new BasicDBObject("$in", ids.keySet()));
if (type != null) {
verq.put(Fields.VER_TYPE,
new BasicDBObject("$regex", "^" + type.getTypePrefix()));
}
if (savedby != null && !savedby.isEmpty()) {
verq.put(Fields.VER_SAVEDBY,
new BasicDBObject("$in", convertWorkspaceUsers(savedby)));
}
if (meta != null && !meta.isEmpty()) {
final List<DBObject> andmetaq = new LinkedList<DBObject>();
for (final Entry<String, String> e: meta.entrySet()) {
final DBObject mentry = new BasicDBObject();
mentry.put(Fields.VER_META_KEY, e.getKey());
mentry.put(Fields.VER_META_VALUE, e.getValue());
andmetaq.add(new BasicDBObject(Fields.VER_META, mentry));
}
verq.put("$and", andmetaq); //note more than one entry is untested
}
final Set<String> fields;
if (includeMetadata) {
fields = new HashSet<String>(FLDS_LIST_OBJ_VER);
fields.add(Fields.VER_META);
} else {
fields = FLDS_LIST_OBJ_VER;
}
final List<Map<String, Object>> verobjs = query.queryCollection(
COL_WORKSPACE_VERS, verq, fields);
if (verobjs.isEmpty()) {
return new LinkedList<ObjectInformation>();
}
//wsid -> obj ids
return new LinkedList<ObjectInformation>(
generateObjectInfo(pset, verobjs, showHidden, showDeleted,
showOnlyDeleted, showAllVers).values());
}
private Map<Map<String, Object>, ObjectInformation> generateObjectInfo(
final PermissionSet pset, final List<Map<String, Object>> verobjs,
final boolean includeHidden, final boolean includeDeleted,
final boolean onlyIncludeDeleted, final boolean includeAllVers)
throws WorkspaceCommunicationException {
final Map<Long, ResolvedWorkspaceID> ids =
new HashMap<Long, ResolvedWorkspaceID>();
for (final ResolvedWorkspaceID rwsi: pset.getWorkspaces()) {
final ResolvedMongoWSID rm = query.convertResolvedWSID(rwsi);
ids.put(rm.getID(), rm);
}
final Map<Long, Set<Long>> verdata = getObjectIDsFromVersions(verobjs);
//TODO This $or query might be better as multiple individual queries, test
final List<DBObject> orquery = new LinkedList<DBObject>();
for (final Long wsid: verdata.keySet()) {
final DBObject query = new BasicDBObject(Fields.VER_WS_ID, wsid);
query.put(Fields.VER_ID, new BasicDBObject(
"$in", verdata.get(wsid)));
orquery.add(query);
}
final DBObject objq = new BasicDBObject("$or", orquery);
//could include / exclude hidden and deleted objects here? Prob
// not worth the effort
final Map<Long, Map<Long, Map<String, Object>>> objdata =
organizeObjData(query.queryCollection(
COL_WORKSPACE_OBJS, objq, FLDS_LIST_OBJ));
final Map<Map<String, Object>, ObjectInformation> ret =
new HashMap<Map<String, Object>, ObjectInformation>();
for (final Map<String, Object> vo: verobjs) {
final long wsid = (Long) vo.get(Fields.VER_WS_ID);
final long id = (Long) vo.get(Fields.VER_ID);
final int ver = (Integer) vo.get(Fields.VER_VER);
final Map<String, Object> obj = objdata.get(wsid).get(id);
final int lastver = (Integer) obj.get(LATEST_VERSION);
final ResolvedMongoWSID rwsi = (ResolvedMongoWSID) ids.get(wsid);
boolean isDeleted = (Boolean) obj.get(Fields.OBJ_DEL);
if (!includeAllVers && lastver != ver) {
/* this is tricky. As is, if there's a failure between incrementing
* an object ver count and saving the object version no latest
* ver will be listed. On the other hand, if we just take
* the max ver we'd be adding incorrect latest vers when filters
* exclude the real max ver. To do this correctly we've have to
* get the max ver for all objects which is really expensive.
* Since the failure mode should be very rare and it fixable
* by simply reverting the object do nothing for now.
*/
continue;
}
if ((Boolean) obj.get(Fields.OBJ_HIDE) && !includeHidden) {
continue;
}
if (onlyIncludeDeleted) {
if (isDeleted && pset.hasPermission(rwsi, Permission.WRITE)) {
ret.put(vo, generateObjectInfo(rwsi, id,
(String) obj.get(Fields.OBJ_NAME), vo));
}
continue;
}
if (isDeleted && (!includeDeleted ||
!pset.hasPermission(rwsi, Permission.WRITE))) {
continue;
}
ret.put(vo, generateObjectInfo(rwsi, id,
(String) obj.get(Fields.OBJ_NAME), vo));
}
return ret;
}
private static final Set<String> FLDS_VER_OBJ_HIST = newHashSet(
Fields.VER_WS_ID, Fields.VER_ID, Fields.VER_VER,
Fields.VER_TYPE, Fields.VER_CHKSUM, Fields.VER_SIZE,
Fields.VER_META, Fields.VER_SAVEDATE, Fields.VER_SAVEDBY);
@Override
public List<ObjectInformation> getObjectHistory(
final ObjectIDResolvedWS oi)
throws NoSuchObjectException, WorkspaceCommunicationException {
final ResolvedMongoObjectID roi = resolveObjectIDs(
new HashSet<ObjectIDResolvedWS>(Arrays.asList(oi))).get(oi);
final ResolvedMongoObjectIDNoVer o =
new ResolvedMongoObjectIDNoVer(roi);
final List<Map<String, Object>> versions = query.queryAllVersions(
new HashSet<ResolvedMongoObjectIDNoVer>(Arrays.asList(o)),
FLDS_VER_OBJ_HIST).get(o);
final LinkedList<ObjectInformation> ret =
new LinkedList<ObjectInformation>();
for (final Map<String, Object> v: versions) {
ret.add(generateObjectInfo(roi, v));
}
return ret;
}
private Map<Long, Map<Long, Map<String, Object>>> organizeObjData(
final List<Map<String, Object>> objs) {
final Map<Long, Map<Long, Map<String, Object>>> ret =
new HashMap<Long, Map<Long,Map<String,Object>>>();
for (final Map<String, Object> o: objs) {
final long wsid = (Long) o.get(Fields.OBJ_WS_ID);
final long objid = (Long) o.get(Fields.OBJ_ID);
final int latestVersion;
if ((Integer) o.get(Fields.OBJ_LATEST) == null) {
latestVersion = (Integer) o.get(Fields.OBJ_VCNT);
} else {
//TODO check this works with GC
latestVersion = (Integer) o.get(Fields.OBJ_LATEST);
}
o.put(LATEST_VERSION, latestVersion);
if (!ret.containsKey(wsid)) {
ret.put(wsid, new HashMap<Long, Map<String, Object>>());
}
ret.get(wsid).put(objid, o);
}
return ret;
}
private Map<Long, Set<Long>> getObjectIDsFromVersions(
final List<Map<String, Object>> objs) {
final Map<Long, Set<Long>> ret = new HashMap<Long, Set<Long>>();
for (final Map<String, Object> o: objs) {
final long wsid = (Long) o.get(Fields.VER_WS_ID);
final long objid = (Long) o.get(Fields.VER_ID);
if (!ret.containsKey(wsid)) {
ret.put(wsid, new HashSet<Long>());
}
ret.get(wsid).add(objid);
}
return ret;
}
private static final Set<String> FLDS_VER_META = newHashSet(
Fields.VER_VER, Fields.VER_TYPE,
Fields.VER_SAVEDATE, Fields.VER_SAVEDBY,
Fields.VER_CHKSUM, Fields.VER_SIZE);
@Override
public Map<ObjectIDResolvedWS, ObjectInformation> getObjectInformation(
final Set<ObjectIDResolvedWS> objectIDs,
final boolean includeMetadata) throws
NoSuchObjectException, WorkspaceCommunicationException {
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> oids =
resolveObjectIDs(objectIDs);
final Set<String> fields;
if (includeMetadata) {
fields = new HashSet<String>(FLDS_VER_META);
fields.add(Fields.VER_META);
} else {
fields = FLDS_VER_META;
}
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(
new HashSet<ResolvedMongoObjectID>(oids.values()),
fields);
final Map<ObjectIDResolvedWS, ObjectInformation> ret =
new HashMap<ObjectIDResolvedWS, ObjectInformation>();
for (ObjectIDResolvedWS o: objectIDs) {
final ResolvedMongoObjectID roi = oids.get(o);
if (!vers.containsKey(roi)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", roi.getId(), roi.getName(),
roi.getVersion(),
roi.getWorkspaceIdentifier().getID()), o);
}
ret.put(o, generateObjectInfo(roi, vers.get(roi)));
}
return ret;
}
private Map<String, String> metaMongoArrayToHash(
final List<Map<String, String>> meta) {
final Map<String, String> ret = new HashMap<String, String>();
for (final Map<String, String> m: meta) {
ret.put(m.get(Fields.VER_META_KEY),
m.get(Fields.VER_META_VALUE));
}
return ret;
}
private static final Set<String> FLDS_RESOLVE_OBJS =
newHashSet(Fields.OBJ_ID, Fields.OBJ_NAME, Fields.OBJ_DEL,
Fields.OBJ_LATEST, Fields.OBJ_VCNT);
private Map<ObjectIDResolvedWS, ResolvedMongoObjectID> resolveObjectIDs(
final Set<ObjectIDResolvedWS> objectIDs)
throws NoSuchObjectException, WorkspaceCommunicationException {
return resolveObjectIDs(objectIDs, true, true);
}
private Map<ObjectIDResolvedWS, ResolvedMongoObjectID> resolveObjectIDs(
final Set<ObjectIDResolvedWS> objectIDs,
final boolean exceptIfDeleted, final boolean exceptIfMissing)
throws NoSuchObjectException, WorkspaceCommunicationException {
final Map<ObjectIDResolvedWS, ObjectIDResolvedWSNoVer> nover =
new HashMap<ObjectIDResolvedWS, ObjectIDResolvedWSNoVer>();
for (final ObjectIDResolvedWS o: objectIDs) {
nover.put(o, new ObjectIDResolvedWSNoVer(o));
}
final Map<ObjectIDResolvedWSNoVer, Map<String, Object>> ids =
query.queryObjects(
new HashSet<ObjectIDResolvedWSNoVer>(nover.values()),
FLDS_RESOLVE_OBJS);
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> ret =
new HashMap<ObjectIDResolvedWS, ResolvedMongoObjectID>();
for (final ObjectIDResolvedWS oid: nover.keySet()) {
final ObjectIDResolvedWSNoVer o = nover.get(oid);
if (!ids.containsKey(o)) {
if (exceptIfMissing) {
final String err = oid.getId() == null ? "name" : "id";
throw new NoSuchObjectException(String.format(
"No object with %s %s exists in workspace %s",
err, oid.getIdentifierString(),
oid.getWorkspaceIdentifier().getID()), oid);
} else {
continue;
}
}
final String name = (String) ids.get(o).get(Fields.OBJ_NAME);
final long id = (Long) ids.get(o).get(Fields.OBJ_ID);
if (exceptIfDeleted && (Boolean) ids.get(o).get(Fields.OBJ_DEL)) {
throw new NoSuchObjectException(String.format(
"Object %s (name %s) in workspace %s has been deleted",
id, name, oid.getWorkspaceIdentifier().getID()), oid);
}
final Integer latestVersion;
if ((Integer) ids.get(o).get(Fields.OBJ_LATEST) == null) {
latestVersion = (Integer) ids.get(o).get(Fields.OBJ_VCNT);
} else {
//TODO check this works with GC
latestVersion = (Integer) ids.get(o).get(Fields.OBJ_LATEST);
}
if (oid.getVersion() == null ||
oid.getVersion().equals(latestVersion)) {
//TODO this could be wrong if the vercount was incremented without a ver save, should verify and then sort if needed
ret.put(oid, new ResolvedMongoOIDWithObjLastVer(
query.convertResolvedWSID(oid.getWorkspaceIdentifier()),
name, id, latestVersion));
} else {
if (oid.getVersion().compareTo(latestVersion) > 0) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s" +
" exists in workspace %s", id, name,
oid.getVersion(),
oid.getWorkspaceIdentifier().getID()), oid);
} else {
ret.put(oid, new ResolvedMongoObjectID(
query.convertResolvedWSID(
oid.getWorkspaceIdentifier()),
name, id, oid.getVersion().intValue()));
}
}
}
return ret;
}
private void verifyVersions(final Set<ResolvedMongoObjectID> objs)
throws WorkspaceCommunicationException, NoSuchObjectException {
final Map<ResolvedMongoObjectID, Map<String, Object>> vers =
query.queryVersions(objs, new HashSet<String>()); //don't actually need the data
for (final ResolvedMongoObjectID o: objs) {
if (!vers.containsKey(o)) {
throw new NoSuchObjectException(String.format(
"No object with id %s (name %s) and version %s exists "
+ "in workspace %s", o.getId(), o.getName(),
o.getVersion(),
o.getWorkspaceIdentifier().getID()));
}
}
}
@Override
public void setObjectsHidden(final Set<ObjectIDResolvedWS> objectIDs,
final boolean hide)
throws NoSuchObjectException, WorkspaceCommunicationException {
//TODO nearly identical to delete objects, generalize
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> ids =
resolveObjectIDs(objectIDs);
final Map<ResolvedMongoWSID, List<Long>> toModify =
new HashMap<ResolvedMongoWSID, List<Long>>();
for (final ObjectIDResolvedWS o: objectIDs) {
final ResolvedMongoWSID ws = query.convertResolvedWSID(
o.getWorkspaceIdentifier());
if (!toModify.containsKey(ws)) {
toModify.put(ws, new ArrayList<Long>());
}
toModify.get(ws).add(ids.get(o).getId());
}
//Do this by workspace since per mongo docs nested $ors are crappy
for (final ResolvedMongoWSID ws: toModify.keySet()) {
setObjectsHidden(ws, toModify.get(ws), hide);
}
}
private static final String M_HIDOBJ_WTH = String.format(
"{$set: {%s: #}}", Fields.OBJ_HIDE);
private static final String M_HIDOBJ_QRY = String.format(
"{%s: #, %s: {$in: #}}", Fields.OBJ_WS_ID, Fields.OBJ_ID);
private void setObjectsHidden(final ResolvedMongoWSID ws,
final List<Long> objectIDs, final boolean hide)
throws WorkspaceCommunicationException {
//TODO make general set field method?
if (objectIDs.isEmpty()) {
throw new IllegalArgumentException("Object IDs cannot be empty");
}
try {
wsjongo.getCollection(COL_WORKSPACE_OBJS)
.update(M_HIDOBJ_QRY, ws.getID(), objectIDs).multi()
.with(M_HIDOBJ_WTH, hide);
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
@Override
public void setObjectsDeleted(final Set<ObjectIDResolvedWS> objectIDs,
final boolean delete)
throws NoSuchObjectException, WorkspaceCommunicationException {
final Map<ObjectIDResolvedWS, ResolvedMongoObjectID> ids =
resolveObjectIDs(objectIDs, delete, true);
final Map<ResolvedMongoWSID, List<Long>> toModify =
new HashMap<ResolvedMongoWSID, List<Long>>();
for (final ObjectIDResolvedWS o: objectIDs) {
final ResolvedMongoWSID ws = query.convertResolvedWSID(
o.getWorkspaceIdentifier());
if (!toModify.containsKey(ws)) {
toModify.put(ws, new ArrayList<Long>());
}
toModify.get(ws).add(ids.get(o).getId());
}
//Do this by workspace since per mongo docs nested $ors are crappy
for (final ResolvedMongoWSID ws: toModify.keySet()) {
setObjectsDeleted(ws, toModify.get(ws), delete);
}
}
private static final String M_DELOBJ_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.OBJ_DEL, Fields.OBJ_MODDATE);
private void setObjectsDeleted(final ResolvedMongoWSID ws,
final List<Long> objectIDs, final boolean delete)
throws WorkspaceCommunicationException {
final String query;
if (objectIDs.isEmpty()) {
query = String.format(
"{%s: %s, %s: %s}", Fields.OBJ_WS_ID, ws.getID(),
Fields.OBJ_DEL, !delete);
} else {
query = String.format(
"{%s: %s, %s: {$in: [%s]}, %s: %s}",
Fields.OBJ_WS_ID, ws.getID(), Fields.OBJ_ID,
StringUtils.join(objectIDs, ", "), Fields.OBJ_DEL, !delete);
}
try {
wsjongo.getCollection(COL_WORKSPACE_OBJS).update(query).multi()
.with(M_DELOBJ_WTH, delete, new Date());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
private static final String M_DELWS_UPD = String.format("{%s: #}",
Fields.WS_ID);
private static final String M_DELWS_WTH = String.format(
"{$set: {%s: #, %s: #}}", Fields.WS_DEL, Fields.WS_MODDATE);
public void setWorkspaceDeleted(final ResolvedWorkspaceID rwsi,
final boolean delete) throws WorkspaceCommunicationException {
//there's a possibility of a race condition here if a workspace is
//deleted and undeleted or vice versa in a very short amount of time,
//but that seems so unlikely it's not worth the code
final ResolvedMongoWSID mrwsi = query.convertResolvedWSID(rwsi);
try {
wsjongo.getCollection(COL_WORKSPACES).update(
M_DELWS_UPD, mrwsi.getID())
.with(M_DELWS_WTH, delete, new Date());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
setObjectsDeleted(mrwsi, new ArrayList<Long>(), delete);
}
private static final String M_ADMIN_QRY = String.format(
"{%s: #}", Fields.ADMIN_NAME);
@Override
public boolean isAdmin(WorkspaceUser putativeAdmin)
throws WorkspaceCommunicationException {
try {
return wsjongo.getCollection(COL_ADMINS).count(M_ADMIN_QRY,
putativeAdmin.getUser()) > 0;
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
@Override
public Set<WorkspaceUser> getAdmins()
throws WorkspaceCommunicationException {
final Set<WorkspaceUser> ret = new HashSet<WorkspaceUser>();
final DBCursor cur;
try {
cur = wsmongo.getCollection(COL_ADMINS).find();
for (final DBObject dbo: cur) {
ret.add(new WorkspaceUser((String) dbo.get(Fields.ADMIN_NAME)));
}
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
return ret;
}
@Override
public void removeAdmin(WorkspaceUser user)
throws WorkspaceCommunicationException {
try {
wsjongo.getCollection(COL_ADMINS).remove(M_ADMIN_QRY,
user.getUser());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
@Override
public void addAdmin(WorkspaceUser user)
throws WorkspaceCommunicationException {
try {
wsjongo.getCollection(COL_ADMINS).update(M_ADMIN_QRY,
user.getUser()).upsert().with(M_ADMIN_QRY, user.getUser());
} catch (MongoException me) {
throw new WorkspaceCommunicationException(
"There was a problem communicating with the database", me);
}
}
public static class TestMongoSuperInternals {
//screwy tests for methods that can't be tested in a black box manner
private static MongoWorkspaceDB testdb;
@BeforeClass
public static void setUpClass() throws Exception {
WorkspaceTestCommon.destroyAndSetupDB(1, "gridFS", "foo");
String host = WorkspaceTestCommon.getHost();
String db1 = WorkspaceTestCommon.getDB1();
String mUser = WorkspaceTestCommon.getMongoUser();
String mPwd = WorkspaceTestCommon.getMongoPwd();
final String kidlpath = new Util().getKIDLpath();
if (mUser == null || mUser == "") {
testdb = new MongoWorkspaceDB(host, db1, kidlpath, "foo", "foo",
"foo", null);
} else {
testdb = new MongoWorkspaceDB(host, db1, kidlpath, mUser, mPwd,
"foo", null);
}
}
@Test
public void createObject() throws Exception {
testdb.createWorkspace(new WorkspaceUser("u"), "ws", false, null);
Map<String, Object> data = new HashMap<String, Object>();
Map<String, String> meta = new HashMap<String, String>();
Map<String, Object> moredata = new HashMap<String, Object>();
moredata.put("foo", "bar");
data.put("fubar", moredata);
meta.put("metastuff", "meta");
Provenance p = new Provenance(new WorkspaceUser("kbasetest2"));
TypeDefId t = new TypeDefId(new TypeDefName("SomeModule", "AType"), 0, 1);
AbsoluteTypeDefId at = new AbsoluteTypeDefId(new TypeDefName("SomeModule", "AType"), 0, 1);
WorkspaceSaveObject wo = new WorkspaceSaveObject(
new ObjectIDNoWSNoVer("testobj"),
MAPPER.valueToTree(data), t, meta, p, false);
List<ResolvedSaveObject> wco = new ArrayList<ResolvedSaveObject>();
wco.add(wo.resolve(new DummyTypedObjectValidationReport(at, wo.getData()),
new HashSet<Reference>(), new LinkedList<Reference>()));
ObjectSavePackage pkg = new ObjectSavePackage();
pkg.wo = wo.resolve(new DummyTypedObjectValidationReport(at, wo.getData()),
new HashSet<Reference>(), new LinkedList<Reference>());
ResolvedMongoWSID rwsi = new ResolvedMongoWSID("ws", 1, false);
pkg.td = new TypeData(MAPPER.valueToTree(data), at, data);
testdb.saveObjects(new WorkspaceUser("u"), rwsi, wco);
IDName r = testdb.saveWorkspaceObject(rwsi, 3, "testobj");
pkg.name = r.name;
testdb.saveProvenance(Arrays.asList(pkg));
ObjectInformation md = testdb.saveObjectVersion(new WorkspaceUser("u"), rwsi, r.id, pkg);
assertThat("objectid is revised to existing object", md.getObjectId(), is(1L));
}
}
}
| trivial clean up | src/us/kbase/workspace/database/mongo/MongoWorkspaceDB.java | trivial clean up | <ide><path>rc/us/kbase/workspace/database/mongo/MongoWorkspaceDB.java
<ide> final boolean showOnlyDeleted, final boolean showAllVers,
<ide> final boolean includeMetadata)
<ide> throws WorkspaceCommunicationException {
<del> //TODO yet another long method that needs pruning
<ide> /* Could make this method more efficient by doing different queries
<ide> * based on the filters. If there's no filters except the workspace,
<ide> * for example, just grab all the objects for the workspaces,
<ide> if (pset.isEmpty()) {
<ide> return new LinkedList<ObjectInformation>();
<ide> }
<add> final Set<Long> ids = new HashSet<Long>();
<add> for (final ResolvedWorkspaceID rwsi: pset.getWorkspaces()) {
<add> ids.add(rwsi.getID());
<add> }
<ide> final DBObject verq = new BasicDBObject();
<del> final Map<Long, ResolvedWorkspaceID> ids =
<del> new HashMap<Long, ResolvedWorkspaceID>();
<del> for (final ResolvedWorkspaceID rwsi: pset.getWorkspaces()) {
<del> final ResolvedMongoWSID rm = query.convertResolvedWSID(rwsi);
<del> ids.put(rm.getID(), rm);
<del> }
<del> verq.put(Fields.VER_WS_ID, new BasicDBObject("$in", ids.keySet()));
<add> verq.put(Fields.VER_WS_ID, new BasicDBObject("$in", ids));
<ide> if (type != null) {
<ide> verq.put(Fields.VER_TYPE,
<ide> new BasicDBObject("$regex", "^" + type.getTypePrefix()));
<ide> if (verobjs.isEmpty()) {
<ide> return new LinkedList<ObjectInformation>();
<ide> }
<del> //wsid -> obj ids
<ide> return new LinkedList<ObjectInformation>(
<ide> generateObjectInfo(pset, verobjs, showHidden, showDeleted,
<ide> showOnlyDeleted, showAllVers).values()); |
|
Java | mit | 9049d293a1a8ca7ac0cd356c1176e297201fc406 | 0 | intuit/karate,intuit/karate,intuit/karate,intuit/karate | /*
* The MIT License
*
* Copyright 2018 Intuit Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.driver;
import com.intuit.karate.Config;
import com.intuit.karate.FileUtils;
import com.intuit.karate.LogAppender;
import com.intuit.karate.Logger;
import com.intuit.karate.core.Embed;
import com.intuit.karate.core.ScenarioContext;
import com.intuit.karate.driver.android.AndroidDriver;
import com.intuit.karate.driver.chrome.Chrome;
import com.intuit.karate.driver.chrome.ChromeWebDriver;
import com.intuit.karate.driver.edge.EdgeDevToolsDriver;
import com.intuit.karate.driver.edge.MicrosoftWebDriver;
import com.intuit.karate.driver.firefox.GeckoWebDriver;
import com.intuit.karate.driver.ios.IosDriver;
import com.intuit.karate.driver.safari.SafariWebDriver;
import com.intuit.karate.driver.windows.WinAppDriver;
import com.intuit.karate.shell.Command;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
*
* @author pthomas3
*/
public class DriverOptions {
// 15 seconds, as of now this is only used by the chrome / CDP reply timeout
public static final long DEFAULT_TIMEOUT = 15 * 1000;
public final Map<String, Object> options;
public final long timeout;
public final boolean start;
public final String executable;
public final String type;
public final int port;
public final String host;
public final int pollAttempts;
public final int pollInterval;
public final boolean headless;
public final boolean showProcessLog;
public final boolean showDriverLog;
public final Logger logger;
public final LogAppender appender;
public final Logger processLogger;
public final Logger driverLogger;
public final String uniqueName;
public final File workingDir;
public final String workingDirPath;
public final String processLogFile;
public final int maxPayloadSize;
public final List<String> addOptions;
public final List<String> args = new ArrayList();
public final Map<String, Object> proxy;
public final Target target;
public final String beforeStart;
public final String afterStop;
public final String videoFile;
// mutable during a test
private boolean retryEnabled;
private Integer retryInterval = null;
private Integer retryCount = null;
private String preSubmitHash = null;
// mutable when we return from called features
private ScenarioContext context;
public static final String SCROLL_JS_FUNCTION = "function(e){ var d = window.getComputedStyle(e).display;"
+ " while(d == 'none'){ e = e.parentElement; d = window.getComputedStyle(e).display }"
+ " e.scrollIntoView({block: 'center'}) }";
public static final String KARATE_REF_GENERATOR = "function(e){"
+ " if (!document._karate) document._karate = { seq: (new Date()).getTime() };"
+ " var ref = 'ref' + document._karate.seq++; document._karate[ref] = e; return ref }";
public void setContext(ScenarioContext context) {
this.context = context;
}
public ScenarioContext getContext() {
return context;
}
public boolean isRetryEnabled() {
return retryEnabled;
}
public String getPreSubmitHash() {
return preSubmitHash;
}
public void setPreSubmitHash(String preSubmitHash) {
this.preSubmitHash = preSubmitHash;
}
private <T> T get(String key, T defaultValue) {
T temp = (T) options.get(key);
return temp == null ? defaultValue : temp;
}
public DriverOptions(ScenarioContext context, Map<String, Object> options, LogAppender appender, int defaultPort, String defaultExecutable) {
this.context = context;
this.options = options;
this.appender = appender;
logger = new Logger(getClass());
logger.setAppender(appender);
timeout = get("timeout", DEFAULT_TIMEOUT);
type = get("type", null);
start = get("start", true);
executable = get("executable", defaultExecutable);
headless = get("headless", false);
showProcessLog = get("showProcessLog", false);
addOptions = get("addOptions", null);
uniqueName = type + "_" + System.currentTimeMillis();
String packageName = getClass().getPackage().getName();
processLogger = showProcessLog ? logger : new Logger(packageName + "." + uniqueName);
showDriverLog = get("showDriverLog", false);
driverLogger = showDriverLog ? logger : new Logger(packageName + "." + uniqueName);
if (executable != null) {
if (executable.startsWith(".")) { // honor path even when we set working dir
args.add(new File(executable).getAbsolutePath());
} else {
args.add(executable);
}
}
workingDir = new File(FileUtils.getBuildDir() + File.separator + uniqueName);
workingDirPath = workingDir.getAbsolutePath();
processLogFile = workingDir.getPath() + File.separator + type + ".log";
maxPayloadSize = get("maxPayloadSize", 4194304);
target = get("target", null);
host = get("host", "localhost");
proxy = get("proxy", null);
beforeStart = get("beforeStart", null);
afterStop = get("afterStop", null);
videoFile = get("videoFile", null);
pollAttempts = get("pollAttempts", 20);
pollInterval = get("pollInterval", 250);
// do this last to ensure things like logger, start-flag and all are set
port = resolvePort(defaultPort);
}
private int resolvePort(int defaultPort) {
int preferredPort = get("port", defaultPort);
if (start) {
int freePort = Command.getFreePort(preferredPort);
if (freePort != preferredPort) {
logger.warn("preferred port {} not available, will use: {}", preferredPort, freePort);
}
return freePort;
}
return preferredPort;
}
public void arg(String arg) {
args.add(arg);
}
public Command startProcess() {
if (beforeStart != null) {
Command.execLine(null, beforeStart);
}
Command command;
if (target != null || !start) {
command = null;
} else {
if (addOptions != null) {
args.addAll(addOptions);
}
command = new Command(false, processLogger, uniqueName, processLogFile, workingDir, args.toArray(new String[]{}));
command.start();
}
// try to wait for a slow booting browser / driver process
waitForPort(host, port);
return command;
}
public static Driver start(ScenarioContext context, Map<String, Object> options, LogAppender appender) {
Target target = (Target) options.get("target");
Logger logger = context.logger;
if (target != null) {
logger.debug("custom target configured, calling start()");
Map<String, Object> map = target.start(logger);
logger.debug("custom target returned options: {}", map);
options.putAll(map);
}
String type = (String) options.get("type");
if (type == null) {
logger.warn("type was null, defaulting to 'chrome'");
type = "chrome";
options.put("type", type);
}
try { // to make troubleshooting errors easier
switch (type) {
case "chrome":
return Chrome.start(context, options, appender);
case "msedge":
return EdgeDevToolsDriver.start(context, options, appender);
case "chromedriver":
return ChromeWebDriver.start(context, options, appender);
case "geckodriver":
return GeckoWebDriver.start(context, options, appender);
case "safaridriver":
return SafariWebDriver.start(context, options, appender);
case "mswebdriver":
return MicrosoftWebDriver.start(context, options, appender);
case "winappdriver":
return WinAppDriver.start(context, options, appender);
case "android":
return AndroidDriver.start(context, options, appender);
case "ios":
return IosDriver.start(context, options, appender);
default:
logger.warn("unknown driver type: {}, defaulting to 'chrome'", type);
options.put("type", "chrome");
return Chrome.start(context, options, appender);
}
} catch (Exception e) {
String message = "driver config / start failed: " + e.getMessage() + ", options: " + options;
logger.error(message);
if (target != null) {
target.stop(logger);
}
throw new RuntimeException(message, e);
}
}
private Map<String, Object> getCapabilities(String browserName) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("browserName", browserName);
if (proxy != null) {
map.put("proxy", proxy);
}
if (headless && browserName.equals("firefox")) {
map.put("moz:firefoxOptions",
Collections.singletonMap("args", Collections.singletonList("-headless")));
map = Collections.singletonMap("alwaysMatch", map);
}
return Collections.singletonMap("capabilities", map);
}
public Map<String, Object> getCapabilities() {
switch (type) {
case "chromedriver":
return getCapabilities("chrome");
case "geckodriver":
return getCapabilities("firefox");
case "safaridriver":
return getCapabilities("safari");
case "mswebdriver":
return getCapabilities("edge");
default:
return null;
}
}
public static String preProcessWildCard(String locator) {
boolean contains;
String tag, prefix, text;
int index;
int pos = locator.indexOf('}');
if (pos == -1) {
throw new RuntimeException("bad locator prefix: " + locator);
}
if (locator.charAt(1) == '^') {
contains = true;
prefix = locator.substring(2, pos);
} else {
contains = false;
prefix = locator.substring(1, pos);
}
text = locator.substring(pos + 1);
pos = prefix.indexOf(':');
if (pos != -1) {
String tagTemp = prefix.substring(0, pos);
tag = tagTemp.isEmpty() ? "*" : tagTemp;
String indexTemp = prefix.substring(pos + 1);
if (indexTemp.isEmpty()) {
index = 0;
} else {
try {
index = Integer.valueOf(indexTemp);
} catch (Exception e) {
throw new RuntimeException("bad locator prefix: " + locator + ", " + e.getMessage());
}
}
} else {
tag = prefix.isEmpty() ? "*" : prefix;
index = 0;
}
if (!tag.startsWith("/")) {
tag = "//" + tag;
}
String xpath;
if (contains) {
xpath = tag + "[contains(normalize-space(text()),'" + text + "')]";
} else {
xpath = tag + "[normalize-space(text())='" + text + "']";
}
if (index == 0) {
return xpath;
}
return "/(" + xpath + ")[" + index + "]";
}
public String selector(String locator) {
if (locator.startsWith("(")) {
return locator; // pure js !
}
if (locator.startsWith("{")) {
locator = preProcessWildCard(locator);
}
if (locator.startsWith("/")) { // XPathResult.FIRST_ORDERED_NODE_TYPE = 9
if (locator.startsWith("/(")) {
locator = locator.substring(1); // hack for wildcard with index (see preProcessWildCard last line)
}
return "document.evaluate(\"" + locator + "\", document, null, 9, null).singleNodeValue";
}
return "document.querySelector(\"" + locator + "\")";
}
public void setRetryInterval(Integer retryInterval) {
this.retryInterval = retryInterval;
}
public int getRetryInterval() {
if (retryInterval != null) {
return retryInterval;
}
if (context == null) {
return Config.DEFAULT_RETRY_INTERVAL;
} else {
return context.getConfig().getRetryInterval();
}
}
public int getRetryCount() {
if (retryCount != null) {
return retryCount;
}
if (context == null) {
return Config.DEFAULT_RETRY_COUNT;
} else {
return context.getConfig().getRetryCount();
}
}
public <T> T retry(Supplier<T> action, Predicate<T> condition, String logDescription) {
long startTime = System.currentTimeMillis();
int count = 0, max = getRetryCount();
T result;
boolean success;
do {
if (count > 0) {
logger.debug("{} - retry #{}", logDescription, count);
sleep();
}
result = action.get();
success = condition.test(result);
} while (!success && count++ < max);
if (!success) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.warn("failed after {} retries and {} milliseconds", (count - 1), elapsedTime);
}
return result;
}
public static String wrapInFunctionInvoke(String text) {
return "(function(){ " + text + " })()";
}
private static final String HIGHLIGHT_FN = "function(e){ var old = e.getAttribute('style');"
+ " e.setAttribute('style', 'background: yellow; border: 2px solid red;');"
+ " setTimeout(function(){ e.setAttribute('style', old) }, 3000) }";
public String highlight(String locator) {
String e = selector(locator);
String temp = "var e = " + e + "; var fun = " + HIGHLIGHT_FN + "; fun(e)";
return wrapInFunctionInvoke(temp);
}
public String highlightAll(String locator) {
return scriptAllSelector(locator, HIGHLIGHT_FN);
}
public String optionSelector(String id, String text) {
boolean textEquals = text.startsWith("{}");
boolean textContains = text.startsWith("{^}");
String condition;
if (textEquals || textContains) {
text = text.substring(text.indexOf('}') + 1);
condition = textContains ? "e.options[i].text.indexOf(t) !== -1" : "e.options[i].text === t";
} else {
condition = "e.options[i].value === t";
}
String e = selector(id);
String temp = "var e = " + e + "; var t = \"" + text + "\";"
+ " for (var i = 0; i < e.options.length; ++i)"
+ " if (" + condition + ") { e.options[i].selected = true; e.dispatchEvent(new Event('change')) }";
return wrapInFunctionInvoke(temp);
}
public String optionSelector(String id, int index) {
String e = selector(id);
String temp = "var e = " + e + "; var t = " + index + ";"
+ " for (var i = 0; i < e.options.length; ++i)"
+ " if (i === t) { e.options[i].selected = true; e.dispatchEvent(new Event('change')) }";
return wrapInFunctionInvoke(temp);
}
private String fun(String expression) {
char first = expression.charAt(0);
return (first == '_' || first == '!') ? "function(_){ return " + expression + " }" : expression;
}
public String scriptSelector(String locator, String expression) {
String temp = "var fun = " + fun(expression) + "; var e = " + selector(locator) + "; return fun(e)";
return wrapInFunctionInvoke(temp);
}
public String scriptAllSelector(String locator, String expression) {
if (locator.startsWith("{")) {
locator = preProcessWildCard(locator);
}
boolean isXpath = locator.startsWith("/");
String selector;
if (isXpath) {
selector = "document.evaluate(\"" + locator + "\", document, null, 5, null)";
} else {
selector = "document.querySelectorAll(\"" + locator + "\")";
}
String temp = "var res = []; var fun = " + fun(expression) + "; var es = " + selector + "; ";
if (isXpath) {
temp = temp + "var e = null; while(e = es.iterateNext()) res.push(fun(e)); return res";
} else {
temp = temp + "es.forEach(function(e){ res.push(fun(e)) }); return res";
}
return wrapInFunctionInvoke(temp);
}
public void sleep() {
sleep(getRetryInterval());
}
public void sleep(int millis) {
if (millis == 0) {
return;
}
try {
processLogger.trace("sleeping for millis: {}", millis);
Thread.sleep(millis);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean waitForPort(String host, int port) {
int attempts = 0;
do {
SocketAddress address = new InetSocketAddress(host, port);
try {
processLogger.debug("poll attempt #{} for port to be ready - {}:{}", attempts, host, port);
SocketChannel sock = SocketChannel.open(address);
sock.close();
return true;
} catch (IOException e) {
sleep(pollInterval);
}
} while (attempts++ < pollAttempts);
return false;
}
public Map<String, Object> newMapWithSelectedKeys(Map<String, Object> map, String... keys) {
Map<String, Object> out = new HashMap(keys.length);
for (String key : keys) {
Object o = map.get(key);
if (o != null) {
out.put(key, o);
}
}
return out;
}
public String removeProtocol(String url) {
int pos = url.indexOf("://");
return pos == -1 ? url : url.substring(pos + 3);
}
public void embedPngImage(byte[] bytes) {
if (context != null) { // can be null if chrome java api
context.embed(bytes, "image/png");
}
}
public void embedContent(Embed embed) {
if (context != null) {
context.embed(embed);
}
}
public static final Set<String> DRIVER_METHOD_NAMES = new HashSet();
static {
for (Method m : Driver.class.getDeclaredMethods()) {
DRIVER_METHOD_NAMES.add(m.getName());
}
}
public void disableRetry() {
retryEnabled = false;
retryCount = null;
retryInterval = null;
}
public void enableRetry(Integer count, Integer interval) {
retryEnabled = true;
retryCount = count; // can be null
retryInterval = interval; // can be null
}
public Element waitUntil(Driver driver, String locator, String expression) {
long startTime = System.currentTimeMillis();
String js = scriptSelector(locator, expression);
boolean found = driver.waitUntil(js);
if (!found) {
long elapsedTime = System.currentTimeMillis() - startTime;
throw new RuntimeException("wait failed for: " + locator
+ " and condition: " + expression + " after " + elapsedTime + " milliseconds");
}
return DriverElement.locatorExists(driver, locator);
}
public String waitForUrl(Driver driver, String expected) {
return retry(() -> driver.getUrl(), url -> url.contains(expected), "waitForUrl");
}
public Element waitForAny(Driver driver, String... locators) {
long startTime = System.currentTimeMillis();
List<String> list = Arrays.asList(locators);
Iterator<String> iterator = list.iterator();
StringBuilder sb = new StringBuilder();
while (iterator.hasNext()) {
String locator = iterator.next();
String js = selector(locator);
sb.append("(").append(js).append(" != null)");
if (iterator.hasNext()) {
sb.append(" || ");
}
}
boolean found = driver.waitUntil(sb.toString());
// important: un-set the retry flag
disableRetry();
if (!found) {
long elapsedTime = System.currentTimeMillis() - startTime;
throw new RuntimeException("wait failed for: " + list + " after " + elapsedTime + " milliseconds");
}
if (locators.length == 1) {
return DriverElement.locatorExists(driver, locators[0]);
}
for (String locator : locators) {
Element temp = driver.exists(locator);
if (temp.isExists()) {
return temp;
}
}
// this should never happen
throw new RuntimeException("unexpected wait failure for locators: " + list);
}
public Element exists(Driver driver, String locator) {
String js = selector(locator);
String evalJs = js + " != null";
Object o = driver.script(evalJs);
if (o instanceof Boolean && (Boolean) o) {
return DriverElement.locatorExists(driver, locator);
} else {
return new MissingElement(driver, locator);
}
}
public static String karateLocator(String karateRef) {
return "(document._karate." + karateRef + ")";
}
public String focusJs(String locator) {
return "var e = " + selector(locator) + "; e.focus(); try { e.selectionStart = e.selectionEnd = e.value.length } catch(x) {}";
}
public List<Element> findAll(Driver driver, String locator) {
List<String> list = driver.scriptAll(locator, DriverOptions.KARATE_REF_GENERATOR);
List<Element> elements = new ArrayList(list.size());
for (String karateRef : list) {
String karateLocator = karateLocator(karateRef);
elements.add(DriverElement.locatorExists(driver, karateLocator));
}
return elements;
}
}
| karate-core/src/main/java/com/intuit/karate/driver/DriverOptions.java | /*
* The MIT License
*
* Copyright 2018 Intuit Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.intuit.karate.driver;
import com.intuit.karate.Config;
import com.intuit.karate.FileUtils;
import com.intuit.karate.LogAppender;
import com.intuit.karate.Logger;
import com.intuit.karate.core.Embed;
import com.intuit.karate.core.ScenarioContext;
import com.intuit.karate.driver.android.AndroidDriver;
import com.intuit.karate.driver.chrome.Chrome;
import com.intuit.karate.driver.chrome.ChromeWebDriver;
import com.intuit.karate.driver.edge.EdgeDevToolsDriver;
import com.intuit.karate.driver.edge.MicrosoftWebDriver;
import com.intuit.karate.driver.firefox.GeckoWebDriver;
import com.intuit.karate.driver.ios.IosDriver;
import com.intuit.karate.driver.safari.SafariWebDriver;
import com.intuit.karate.driver.windows.WinAppDriver;
import com.intuit.karate.shell.Command;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
*
* @author pthomas3
*/
public class DriverOptions {
// 15 seconds, as of now this is only used by the chrome / CDP reply timeout
public static final long DEFAULT_TIMEOUT = 15 * 1000;
public final Map<String, Object> options;
public final long timeout;
public final boolean start;
public final String executable;
public final String type;
public final int port;
public final String host;
public final int pollAttempts;
public final int pollInterval;
public final boolean headless;
public final boolean showProcessLog;
public final boolean showDriverLog;
public final Logger logger;
public final LogAppender appender;
public final Logger processLogger;
public final Logger driverLogger;
public final String uniqueName;
public final File workingDir;
public final String workingDirPath;
public final String processLogFile;
public final int maxPayloadSize;
public final List<String> addOptions;
public final List<String> args = new ArrayList();
public final Map<String, Object> proxy;
public final Target target;
public final String beforeStart;
public final String afterStop;
public final String videoFile;
// mutable during a test
private boolean retryEnabled;
private Integer retryInterval = null;
private Integer retryCount = null;
private String preSubmitHash = null;
// mutable when we return from called features
private ScenarioContext context;
public static final String SCROLL_JS_FUNCTION = "function(e){ var d = window.getComputedStyle(e).display;"
+ " while(d == 'none'){ e = e.parentElement; d = window.getComputedStyle(e).display }"
+ " e.scrollIntoView({block: 'center'}) }";
public static final String KARATE_REF_GENERATOR = "function(e){"
+ " if (!document._karate) document._karate = { seq: (new Date()).getTime() };"
+ " var ref = 'ref' + document._karate.seq++; document._karate[ref] = e; return ref }";
public void setContext(ScenarioContext context) {
this.context = context;
}
public ScenarioContext getContext() {
return context;
}
public boolean isRetryEnabled() {
return retryEnabled;
}
public String getPreSubmitHash() {
return preSubmitHash;
}
public void setPreSubmitHash(String preSubmitHash) {
this.preSubmitHash = preSubmitHash;
}
private <T> T get(String key, T defaultValue) {
T temp = (T) options.get(key);
return temp == null ? defaultValue : temp;
}
public DriverOptions(ScenarioContext context, Map<String, Object> options, LogAppender appender, int defaultPort, String defaultExecutable) {
this.context = context;
this.options = options;
this.appender = appender;
logger = new Logger(getClass());
logger.setAppender(appender);
timeout = get("timeout", DEFAULT_TIMEOUT);
type = get("type", null);
start = get("start", true);
executable = get("executable", defaultExecutable);
headless = get("headless", false);
showProcessLog = get("showProcessLog", false);
addOptions = get("addOptions", null);
uniqueName = type + "_" + System.currentTimeMillis();
String packageName = getClass().getPackage().getName();
processLogger = showProcessLog ? logger : new Logger(packageName + "." + uniqueName);
showDriverLog = get("showDriverLog", false);
driverLogger = showDriverLog ? logger : new Logger(packageName + "." + uniqueName);
if (executable != null) {
if (executable.startsWith(".")) { // honor path even when we set working dir
args.add(new File(executable).getAbsolutePath());
} else {
args.add(executable);
}
}
workingDir = new File(FileUtils.getBuildDir() + File.separator + uniqueName);
workingDirPath = workingDir.getAbsolutePath();
processLogFile = workingDir.getPath() + File.separator + type + ".log";
maxPayloadSize = get("maxPayloadSize", 4194304);
target = get("target", null);
host = get("host", "localhost");
proxy = get("proxy", null);
beforeStart = get("beforeStart", null);
afterStop = get("afterStop", null);
videoFile = get("videoFile", null);
pollAttempts = get("pollAttempts", 20);
pollInterval = get("pollInterval", 250);
// do this last to ensure things like logger, start-flag and all are set
port = resolvePort(defaultPort);
}
private int resolvePort(int defaultPort) {
int preferredPort = get("port", defaultPort);
if (start) {
int freePort = Command.getFreePort(preferredPort);
if (freePort != preferredPort) {
logger.warn("preferred port {} not available, will use: {}", preferredPort, freePort);
}
return freePort;
}
return preferredPort;
}
public void arg(String arg) {
args.add(arg);
}
public Command startProcess() {
if (beforeStart != null) {
Command.execLine(null, beforeStart);
}
Command command;
if (target != null || !start) {
command = null;
} else {
if (addOptions != null) {
args.addAll(addOptions);
}
command = new Command(false, processLogger, uniqueName, processLogFile, workingDir, args.toArray(new String[]{}));
command.start();
}
// try to wait for a slow booting browser / driver process
waitForPort(host, port);
return command;
}
public static Driver start(ScenarioContext context, Map<String, Object> options, LogAppender appender) {
Target target = (Target) options.get("target");
Logger logger = context.logger;
if (target != null) {
logger.debug("custom target configured, calling start()");
Map<String, Object> map = target.start(logger);
logger.debug("custom target returned options: {}", map);
options.putAll(map);
}
String type = (String) options.get("type");
if (type == null) {
logger.warn("type was null, defaulting to 'chrome'");
type = "chrome";
options.put("type", type);
}
try { // to make troubleshooting errors easier
switch (type) {
case "chrome":
return Chrome.start(context, options, appender);
case "msedge":
return EdgeDevToolsDriver.start(context, options, appender);
case "chromedriver":
return ChromeWebDriver.start(context, options, appender);
case "geckodriver":
return GeckoWebDriver.start(context, options, appender);
case "safaridriver":
return SafariWebDriver.start(context, options, appender);
case "mswebdriver":
return MicrosoftWebDriver.start(context, options, appender);
case "winappdriver":
return WinAppDriver.start(context, options, appender);
case "android":
return AndroidDriver.start(context, options, appender);
case "ios":
return IosDriver.start(context, options, appender);
default:
logger.warn("unknown driver type: {}, defaulting to 'chrome'", type);
options.put("type", "chrome");
return Chrome.start(context, options, appender);
}
} catch (Exception e) {
String message = "driver config / start failed: " + e.getMessage() + ", options: " + options;
logger.error(message);
if (target != null) {
target.stop(logger);
}
throw new RuntimeException(message, e);
}
}
private Map<String, Object> getCapabilities(String browserName) {
Map<String, Object> map = new LinkedHashMap();
map.put("browserName", browserName);
if (proxy != null) {
map.put("proxy", proxy);
}
return Collections.singletonMap("capabilities", map);
}
public Map<String, Object> getCapabilities() {
switch (type) {
case "chromedriver":
return getCapabilities("Chrome");
case "geckodriver":
return getCapabilities("Firefox");
case "safaridriver":
return getCapabilities("Safari");
case "mswebdriver":
return getCapabilities("Edge");
default:
return null;
}
}
public static String preProcessWildCard(String locator) {
boolean contains;
String tag, prefix, text;
int index;
int pos = locator.indexOf('}');
if (pos == -1) {
throw new RuntimeException("bad locator prefix: " + locator);
}
if (locator.charAt(1) == '^') {
contains = true;
prefix = locator.substring(2, pos);
} else {
contains = false;
prefix = locator.substring(1, pos);
}
text = locator.substring(pos + 1);
pos = prefix.indexOf(':');
if (pos != -1) {
String tagTemp = prefix.substring(0, pos);
tag = tagTemp.isEmpty() ? "*" : tagTemp;
String indexTemp = prefix.substring(pos + 1);
if (indexTemp.isEmpty()) {
index = 0;
} else {
try {
index = Integer.valueOf(indexTemp);
} catch (Exception e) {
throw new RuntimeException("bad locator prefix: " + locator + ", " + e.getMessage());
}
}
} else {
tag = prefix.isEmpty() ? "*" : prefix;
index = 0;
}
if (!tag.startsWith("/")) {
tag = "//" + tag;
}
String xpath;
if (contains) {
xpath = tag + "[contains(normalize-space(text()),'" + text + "')]";
} else {
xpath = tag + "[normalize-space(text())='" + text + "']";
}
if (index == 0) {
return xpath;
}
return "/(" + xpath + ")[" + index + "]";
}
public String selector(String locator) {
if (locator.startsWith("(")) {
return locator; // pure js !
}
if (locator.startsWith("{")) {
locator = preProcessWildCard(locator);
}
if (locator.startsWith("/")) { // XPathResult.FIRST_ORDERED_NODE_TYPE = 9
if (locator.startsWith("/(")) {
locator = locator.substring(1); // hack for wildcard with index (see preProcessWildCard last line)
}
return "document.evaluate(\"" + locator + "\", document, null, 9, null).singleNodeValue";
}
return "document.querySelector(\"" + locator + "\")";
}
public void setRetryInterval(Integer retryInterval) {
this.retryInterval = retryInterval;
}
public int getRetryInterval() {
if (retryInterval != null) {
return retryInterval;
}
if (context == null) {
return Config.DEFAULT_RETRY_INTERVAL;
} else {
return context.getConfig().getRetryInterval();
}
}
public int getRetryCount() {
if (retryCount != null) {
return retryCount;
}
if (context == null) {
return Config.DEFAULT_RETRY_COUNT;
} else {
return context.getConfig().getRetryCount();
}
}
public <T> T retry(Supplier<T> action, Predicate<T> condition, String logDescription) {
long startTime = System.currentTimeMillis();
int count = 0, max = getRetryCount();
T result;
boolean success;
do {
if (count > 0) {
logger.debug("{} - retry #{}", logDescription, count);
sleep();
}
result = action.get();
success = condition.test(result);
} while (!success && count++ < max);
if (!success) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.warn("failed after {} retries and {} milliseconds", (count - 1), elapsedTime);
}
return result;
}
public static String wrapInFunctionInvoke(String text) {
return "(function(){ " + text + " })()";
}
private static final String HIGHLIGHT_FN = "function(e){ var old = e.getAttribute('style');"
+ " e.setAttribute('style', 'background: yellow; border: 2px solid red;');"
+ " setTimeout(function(){ e.setAttribute('style', old) }, 3000) }";
public String highlight(String locator) {
String e = selector(locator);
String temp = "var e = " + e + "; var fun = " + HIGHLIGHT_FN + "; fun(e)";
return wrapInFunctionInvoke(temp);
}
public String highlightAll(String locator) {
return scriptAllSelector(locator, HIGHLIGHT_FN);
}
public String optionSelector(String id, String text) {
boolean textEquals = text.startsWith("{}");
boolean textContains = text.startsWith("{^}");
String condition;
if (textEquals || textContains) {
text = text.substring(text.indexOf('}') + 1);
condition = textContains ? "e.options[i].text.indexOf(t) !== -1" : "e.options[i].text === t";
} else {
condition = "e.options[i].value === t";
}
String e = selector(id);
String temp = "var e = " + e + "; var t = \"" + text + "\";"
+ " for (var i = 0; i < e.options.length; ++i)"
+ " if (" + condition + ") { e.options[i].selected = true; e.dispatchEvent(new Event('change')) }";
return wrapInFunctionInvoke(temp);
}
public String optionSelector(String id, int index) {
String e = selector(id);
String temp = "var e = " + e + "; var t = " + index + ";"
+ " for (var i = 0; i < e.options.length; ++i)"
+ " if (i === t) { e.options[i].selected = true; e.dispatchEvent(new Event('change')) }";
return wrapInFunctionInvoke(temp);
}
private String fun(String expression) {
char first = expression.charAt(0);
return (first == '_' || first == '!') ? "function(_){ return " + expression + " }" : expression;
}
public String scriptSelector(String locator, String expression) {
String temp = "var fun = " + fun(expression) + "; var e = " + selector(locator) + "; return fun(e)";
return wrapInFunctionInvoke(temp);
}
public String scriptAllSelector(String locator, String expression) {
if (locator.startsWith("{")) {
locator = preProcessWildCard(locator);
}
boolean isXpath = locator.startsWith("/");
String selector;
if (isXpath) {
selector = "document.evaluate(\"" + locator + "\", document, null, 5, null)";
} else {
selector = "document.querySelectorAll(\"" + locator + "\")";
}
String temp = "var res = []; var fun = " + fun(expression) + "; var es = " + selector + "; ";
if (isXpath) {
temp = temp + "var e = null; while(e = es.iterateNext()) res.push(fun(e)); return res";
} else {
temp = temp + "es.forEach(function(e){ res.push(fun(e)) }); return res";
}
return wrapInFunctionInvoke(temp);
}
public void sleep() {
sleep(getRetryInterval());
}
public void sleep(int millis) {
if (millis == 0) {
return;
}
try {
processLogger.trace("sleeping for millis: {}", millis);
Thread.sleep(millis);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean waitForPort(String host, int port) {
int attempts = 0;
do {
SocketAddress address = new InetSocketAddress(host, port);
try {
processLogger.debug("poll attempt #{} for port to be ready - {}:{}", attempts, host, port);
SocketChannel sock = SocketChannel.open(address);
sock.close();
return true;
} catch (IOException e) {
sleep(pollInterval);
}
} while (attempts++ < pollAttempts);
return false;
}
public Map<String, Object> newMapWithSelectedKeys(Map<String, Object> map, String... keys) {
Map<String, Object> out = new HashMap(keys.length);
for (String key : keys) {
Object o = map.get(key);
if (o != null) {
out.put(key, o);
}
}
return out;
}
public String removeProtocol(String url) {
int pos = url.indexOf("://");
return pos == -1 ? url : url.substring(pos + 3);
}
public void embedPngImage(byte[] bytes) {
if (context != null) { // can be null if chrome java api
context.embed(bytes, "image/png");
}
}
public void embedContent(Embed embed) {
if (context != null) {
context.embed(embed);
}
}
public static final Set<String> DRIVER_METHOD_NAMES = new HashSet();
static {
for (Method m : Driver.class.getDeclaredMethods()) {
DRIVER_METHOD_NAMES.add(m.getName());
}
}
public void disableRetry() {
retryEnabled = false;
retryCount = null;
retryInterval = null;
}
public void enableRetry(Integer count, Integer interval) {
retryEnabled = true;
retryCount = count; // can be null
retryInterval = interval; // can be null
}
public Element waitUntil(Driver driver, String locator, String expression) {
long startTime = System.currentTimeMillis();
String js = scriptSelector(locator, expression);
boolean found = driver.waitUntil(js);
if (!found) {
long elapsedTime = System.currentTimeMillis() - startTime;
throw new RuntimeException("wait failed for: " + locator
+ " and condition: " + expression + " after " + elapsedTime + " milliseconds");
}
return DriverElement.locatorExists(driver, locator);
}
public String waitForUrl(Driver driver, String expected) {
return retry(() -> driver.getUrl(), url -> url.contains(expected), "waitForUrl");
}
public Element waitForAny(Driver driver, String... locators) {
long startTime = System.currentTimeMillis();
List<String> list = Arrays.asList(locators);
Iterator<String> iterator = list.iterator();
StringBuilder sb = new StringBuilder();
while (iterator.hasNext()) {
String locator = iterator.next();
String js = selector(locator);
sb.append("(").append(js).append(" != null)");
if (iterator.hasNext()) {
sb.append(" || ");
}
}
boolean found = driver.waitUntil(sb.toString());
// important: un-set the retry flag
disableRetry();
if (!found) {
long elapsedTime = System.currentTimeMillis() - startTime;
throw new RuntimeException("wait failed for: " + list + " after " + elapsedTime + " milliseconds");
}
if (locators.length == 1) {
return DriverElement.locatorExists(driver, locators[0]);
}
for (String locator : locators) {
Element temp = driver.exists(locator);
if (temp.isExists()) {
return temp;
}
}
// this should never happen
throw new RuntimeException("unexpected wait failure for locators: " + list);
}
public Element exists(Driver driver, String locator) {
String js = selector(locator);
String evalJs = js + " != null";
Object o = driver.script(evalJs);
if (o instanceof Boolean && (Boolean) o) {
return DriverElement.locatorExists(driver, locator);
} else {
return new MissingElement(driver, locator);
}
}
public static String karateLocator(String karateRef) {
return "(document._karate." + karateRef + ")";
}
public String focusJs(String locator) {
return "var e = " + selector(locator) + "; e.focus(); try { e.selectionStart = e.selectionEnd = e.value.length } catch(x) {}";
}
public List<Element> findAll(Driver driver, String locator) {
List<String> list = driver.scriptAll(locator, DriverOptions.KARATE_REF_GENERATOR);
List<Element> elements = new ArrayList(list.size());
for (String karateRef : list) {
String karateLocator = karateLocator(karateRef);
elements.add(DriverElement.locatorExists(driver, karateLocator));
}
return elements;
}
}
| support headless flag for firefox
| karate-core/src/main/java/com/intuit/karate/driver/DriverOptions.java | support headless flag for firefox | <ide><path>arate-core/src/main/java/com/intuit/karate/driver/DriverOptions.java
<ide> }
<ide>
<ide> private Map<String, Object> getCapabilities(String browserName) {
<del> Map<String, Object> map = new LinkedHashMap();
<add> Map<String, Object> map = new LinkedHashMap<>();
<ide> map.put("browserName", browserName);
<ide> if (proxy != null) {
<ide> map.put("proxy", proxy);
<ide> }
<add> if (headless && browserName.equals("firefox")) {
<add> map.put("moz:firefoxOptions",
<add> Collections.singletonMap("args", Collections.singletonList("-headless")));
<add> map = Collections.singletonMap("alwaysMatch", map);
<add> }
<ide> return Collections.singletonMap("capabilities", map);
<ide> }
<ide>
<ide> public Map<String, Object> getCapabilities() {
<ide> switch (type) {
<ide> case "chromedriver":
<del> return getCapabilities("Chrome");
<add> return getCapabilities("chrome");
<ide> case "geckodriver":
<del> return getCapabilities("Firefox");
<add> return getCapabilities("firefox");
<ide> case "safaridriver":
<del> return getCapabilities("Safari");
<add> return getCapabilities("safari");
<ide> case "mswebdriver":
<del> return getCapabilities("Edge");
<add> return getCapabilities("edge");
<ide> default:
<ide> return null;
<ide> } |
|
Java | apache-2.0 | e68bc5212356c675ddb4cb2f7874c0654023e2b6 | 0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | // Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.notedb;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.server.notedb.NoteDbTable.CHANGES;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.Project;
import com.google.gerrit.entities.RefNames;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.git.RefUpdateUtil;
import com.google.gerrit.metrics.Timer1;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.update.ChainedReceiveCommands;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.PushCertificate;
import org.eclipse.jgit.transport.ReceiveCommand;
/**
* Object to manage a single sequence of updates to NoteDb.
*
* <p>Instances are one-time-use. Handles updating both the change repo and the All-Users repo for
* any affected changes, with proper ordering.
*
* <p>To see the state that would be applied prior to executing the full sequence of updates, use
* {@link #stage()}.
*/
public class NoteDbUpdateManager implements AutoCloseable {
public interface Factory {
NoteDbUpdateManager create(Project.NameKey projectName);
}
private final Provider<PersonIdent> serverIdent;
private final GitRepositoryManager repoManager;
private final AllUsersName allUsersName;
private final NoteDbMetrics metrics;
private final Project.NameKey projectName;
private final int maxUpdates;
private final ListMultimap<String, ChangeUpdate> changeUpdates;
private final ListMultimap<String, ChangeDraftUpdate> draftUpdates;
private final ListMultimap<String, RobotCommentUpdate> robotCommentUpdates;
private final ListMultimap<String, NoteDbRewriter> rewriters;
private final Set<Change.Id> changesToDelete;
private OpenRepo changeRepo;
private OpenRepo allUsersRepo;
private AllUsersAsyncUpdate updateAllUsersAsync;
private boolean executed;
private String refLogMessage;
private PersonIdent refLogIdent;
private PushCertificate pushCert;
@Inject
NoteDbUpdateManager(
@GerritServerConfig Config cfg,
@GerritPersonIdent Provider<PersonIdent> serverIdent,
GitRepositoryManager repoManager,
AllUsersName allUsersName,
NoteDbMetrics metrics,
AllUsersAsyncUpdate updateAllUsersAsync,
@Assisted Project.NameKey projectName) {
this.serverIdent = serverIdent;
this.repoManager = repoManager;
this.allUsersName = allUsersName;
this.metrics = metrics;
this.updateAllUsersAsync = updateAllUsersAsync;
this.projectName = projectName;
maxUpdates = cfg.getInt("change", null, "maxUpdates", 1000);
changeUpdates = MultimapBuilder.hashKeys().arrayListValues().build();
draftUpdates = MultimapBuilder.hashKeys().arrayListValues().build();
robotCommentUpdates = MultimapBuilder.hashKeys().arrayListValues().build();
rewriters = MultimapBuilder.hashKeys().arrayListValues().build();
changesToDelete = new HashSet<>();
}
@Override
public void close() {
try {
if (allUsersRepo != null) {
OpenRepo r = allUsersRepo;
allUsersRepo = null;
r.close();
}
} finally {
if (changeRepo != null) {
OpenRepo r = changeRepo;
changeRepo = null;
r.close();
}
}
}
public NoteDbUpdateManager setChangeRepo(
Repository repo, RevWalk rw, @Nullable ObjectInserter ins, ChainedReceiveCommands cmds) {
checkState(changeRepo == null, "change repo already initialized");
changeRepo = new OpenRepo(repo, rw, ins, cmds, false);
return this;
}
public NoteDbUpdateManager setRefLogMessage(String message) {
this.refLogMessage = message;
return this;
}
public NoteDbUpdateManager setRefLogIdent(PersonIdent ident) {
this.refLogIdent = ident;
return this;
}
/**
* Set a push certificate for the push that originally triggered this NoteDb update.
*
* <p>The pusher will not necessarily have specified any of the NoteDb refs explicitly, such as
* when processing a push to {@code refs/for/master}. That's fine; this is just passed to the
* underlying {@link BatchRefUpdate}, and the implementation decides what to do with it.
*
* <p>The cert should be associated with the main repo. There is currently no way of associating a
* push cert with the {@code All-Users} repo, since it is not currently possible to update draft
* changes via push.
*
* @param pushCert push certificate; may be null.
* @return this
*/
public NoteDbUpdateManager setPushCertificate(PushCertificate pushCert) {
this.pushCert = pushCert;
return this;
}
private void initChangeRepo() throws IOException {
if (changeRepo == null) {
changeRepo = OpenRepo.open(repoManager, projectName);
}
}
private void initAllUsersRepo() throws IOException {
if (allUsersRepo == null) {
allUsersRepo = OpenRepo.open(repoManager, allUsersName);
}
}
private boolean isEmpty() {
return changeUpdates.isEmpty()
&& draftUpdates.isEmpty()
&& robotCommentUpdates.isEmpty()
&& rewriters.isEmpty()
&& changesToDelete.isEmpty()
&& !hasCommands(changeRepo)
&& !hasCommands(allUsersRepo)
&& updateAllUsersAsync.isEmpty();
}
private static boolean hasCommands(@Nullable OpenRepo or) {
return or != null && !or.cmds.isEmpty();
}
/**
* Add an update to the list of updates to execute.
*
* <p>Updates should only be added to the manager after all mutations have been made, as this
* method may eagerly access the update.
*
* @param update the update to add.
*/
public void add(ChangeUpdate update) {
checkNotExecuted();
checkArgument(
update.getProjectName().equals(projectName),
"update for project %s cannot be added to manager for project %s",
update.getProjectName(),
projectName);
checkArgument(
!rewriters.containsKey(update.getRefName()),
"cannot update & rewrite ref %s in one BatchUpdate",
update.getRefName());
ChangeDraftUpdate du = update.getDraftUpdate();
if (du != null) {
draftUpdates.put(du.getRefName(), du);
}
RobotCommentUpdate rcu = update.getRobotCommentUpdate();
if (rcu != null) {
robotCommentUpdates.put(rcu.getRefName(), rcu);
}
DeleteCommentRewriter deleteCommentRewriter = update.getDeleteCommentRewriter();
if (deleteCommentRewriter != null) {
// Checks whether there is any ChangeUpdate or rewriter added earlier for the same ref.
checkArgument(
!changeUpdates.containsKey(deleteCommentRewriter.getRefName()),
"cannot update & rewrite ref %s in one BatchUpdate",
deleteCommentRewriter.getRefName());
checkArgument(
!rewriters.containsKey(deleteCommentRewriter.getRefName()),
"cannot rewrite the same ref %s in one BatchUpdate",
deleteCommentRewriter.getRefName());
rewriters.put(deleteCommentRewriter.getRefName(), deleteCommentRewriter);
}
DeleteChangeMessageRewriter deleteChangeMessageRewriter =
update.getDeleteChangeMessageRewriter();
if (deleteChangeMessageRewriter != null) {
// Checks whether there is any ChangeUpdate or rewriter added earlier for the same ref.
checkArgument(
!changeUpdates.containsKey(deleteChangeMessageRewriter.getRefName()),
"cannot update & rewrite ref %s in one BatchUpdate",
deleteChangeMessageRewriter.getRefName());
checkArgument(
!rewriters.containsKey(deleteChangeMessageRewriter.getRefName()),
"cannot rewrite the same ref %s in one BatchUpdate",
deleteChangeMessageRewriter.getRefName());
rewriters.put(deleteChangeMessageRewriter.getRefName(), deleteChangeMessageRewriter);
}
changeUpdates.put(update.getRefName(), update);
}
public void add(ChangeDraftUpdate draftUpdate) {
checkNotExecuted();
draftUpdates.put(draftUpdate.getRefName(), draftUpdate);
}
public void deleteChange(Change.Id id) {
checkNotExecuted();
changesToDelete.add(id);
}
/**
* Stage updates in the manager's internal list of commands.
*
* @throws IOException if a storage layer error occurs.
*/
private void stage() throws IOException {
try (Timer1.Context<NoteDbTable> timer = metrics.stageUpdateLatency.start(CHANGES)) {
if (isEmpty()) {
return;
}
initChangeRepo();
if (!draftUpdates.isEmpty() || !changesToDelete.isEmpty()) {
initAllUsersRepo();
}
addCommands();
}
}
@Nullable
public BatchRefUpdate execute() throws IOException {
return execute(false);
}
@Nullable
public BatchRefUpdate execute(boolean dryrun) throws IOException {
checkNotExecuted();
if (isEmpty()) {
executed = true;
return null;
}
try (Timer1.Context<NoteDbTable> timer = metrics.updateLatency.start(CHANGES)) {
stage();
// ChangeUpdates must execute before ChangeDraftUpdates.
//
// ChangeUpdate will automatically delete draft comments for any published
// comments, but the updates to the two repos don't happen atomically.
// Thus if the change meta update succeeds and the All-Users update fails,
// we may have stale draft comments. Doing it in this order allows stale
// comments to be filtered out by ChangeNotes, reflecting the fact that
// comments can only go from DRAFT to PUBLISHED, not vice versa.
BatchRefUpdate result = execute(changeRepo, dryrun, pushCert);
execute(allUsersRepo, dryrun, null);
if (!dryrun) {
// Only execute the asynchronous operation if we are not in dry-run mode: The dry run would
// have to run synchronous to be of any value at all. For the removal of draft comments from
// All-Users we don't care much of the operation succeeds, so we are skipping the dry run
// altogether.
updateAllUsersAsync.execute(refLogIdent, refLogMessage, pushCert);
}
executed = true;
return result;
} finally {
close();
}
}
private BatchRefUpdate execute(OpenRepo or, boolean dryrun, @Nullable PushCertificate pushCert)
throws IOException {
if (or == null || or.cmds.isEmpty()) {
return null;
}
if (!dryrun) {
or.flush();
} else {
// OpenRepo buffers objects separately; caller may assume that objects are available in the
// inserter it previously passed via setChangeRepo.
or.flushToFinalInserter();
}
BatchRefUpdate bru = or.repo.getRefDatabase().newBatchUpdate();
bru.setPushCertificate(pushCert);
if (refLogMessage != null) {
bru.setRefLogMessage(refLogMessage, false);
} else {
bru.setRefLogMessage(
firstNonNull(NoteDbUtil.guessRestApiHandler(), "Update NoteDb refs"), false);
}
bru.setRefLogIdent(refLogIdent != null ? refLogIdent : serverIdent.get());
bru.setAtomic(true);
or.cmds.addTo(bru);
bru.setAllowNonFastForwards(true);
if (!dryrun) {
RefUpdateUtil.executeChecked(bru, or.rw);
}
return bru;
}
private void addCommands() throws IOException {
changeRepo.addUpdates(changeUpdates, Optional.of(maxUpdates));
if (!draftUpdates.isEmpty()) {
boolean publishOnly = draftUpdates.values().stream().allMatch(ChangeDraftUpdate::canRunAsync);
if (publishOnly) {
updateAllUsersAsync.setDraftUpdates(draftUpdates);
} else {
allUsersRepo.addUpdates(draftUpdates);
}
}
if (!robotCommentUpdates.isEmpty()) {
changeRepo.addUpdates(robotCommentUpdates);
}
if (!rewriters.isEmpty()) {
addRewrites(rewriters, changeRepo);
}
for (Change.Id id : changesToDelete) {
doDelete(id);
}
}
private void doDelete(Change.Id id) throws IOException {
String metaRef = RefNames.changeMetaRef(id);
Optional<ObjectId> old = changeRepo.cmds.get(metaRef);
if (old.isPresent()) {
changeRepo.cmds.add(new ReceiveCommand(old.get(), ObjectId.zeroId(), metaRef));
}
// Just scan repo for ref names, but get "old" values from cmds.
for (Ref r :
allUsersRepo.repo.getRefDatabase().getRefsByPrefix(RefNames.refsDraftCommentsPrefix(id))) {
old = allUsersRepo.cmds.get(r.getName());
if (old.isPresent()) {
allUsersRepo.cmds.add(new ReceiveCommand(old.get(), ObjectId.zeroId(), r.getName()));
}
}
}
private void checkNotExecuted() {
checkState(!executed, "update has already been executed");
}
private static void addRewrites(ListMultimap<String, NoteDbRewriter> rewriters, OpenRepo openRepo)
throws IOException {
for (Map.Entry<String, Collection<NoteDbRewriter>> entry : rewriters.asMap().entrySet()) {
String refName = entry.getKey();
ObjectId oldTip = openRepo.cmds.get(refName).orElse(ObjectId.zeroId());
if (oldTip.equals(ObjectId.zeroId())) {
throw new StorageException(String.format("Ref %s is empty", refName));
}
ObjectId currTip = oldTip;
try {
for (NoteDbRewriter noteDbRewriter : entry.getValue()) {
ObjectId nextTip =
noteDbRewriter.rewriteCommitHistory(openRepo.rw, openRepo.tempIns, currTip);
if (nextTip != null) {
currTip = nextTip;
}
}
} catch (ConfigInvalidException e) {
throw new StorageException("Cannot rewrite commit history", e);
}
if (!oldTip.equals(currTip)) {
openRepo.cmds.add(new ReceiveCommand(oldTip, currTip, refName));
}
}
}
}
| java/com/google/gerrit/server/notedb/NoteDbUpdateManager.java | // Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.notedb;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.gerrit.server.notedb.NoteDbTable.CHANGES;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.entities.Change;
import com.google.gerrit.entities.Project;
import com.google.gerrit.entities.RefNames;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.git.RefUpdateUtil;
import com.google.gerrit.metrics.Timer1;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.update.ChainedReceiveCommands;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.PushCertificate;
import org.eclipse.jgit.transport.ReceiveCommand;
/**
* Object to manage a single sequence of updates to NoteDb.
*
* <p>Instances are one-time-use. Handles updating both the change repo and the All-Users repo for
* any affected changes, with proper ordering.
*
* <p>To see the state that would be applied prior to executing the full sequence of updates, use
* {@link #stage()}.
*/
public class NoteDbUpdateManager implements AutoCloseable {
public interface Factory {
NoteDbUpdateManager create(Project.NameKey projectName);
}
private final Provider<PersonIdent> serverIdent;
private final GitRepositoryManager repoManager;
private final AllUsersName allUsersName;
private final NoteDbMetrics metrics;
private final Project.NameKey projectName;
private final int maxUpdates;
private final ListMultimap<String, ChangeUpdate> changeUpdates;
private final ListMultimap<String, ChangeDraftUpdate> draftUpdates;
private final ListMultimap<String, RobotCommentUpdate> robotCommentUpdates;
private final ListMultimap<String, NoteDbRewriter> rewriters;
private final Set<Change.Id> toDelete;
private OpenRepo changeRepo;
private OpenRepo allUsersRepo;
private AllUsersAsyncUpdate updateAllUsersAsync;
private boolean executed;
private String refLogMessage;
private PersonIdent refLogIdent;
private PushCertificate pushCert;
@Inject
NoteDbUpdateManager(
@GerritServerConfig Config cfg,
@GerritPersonIdent Provider<PersonIdent> serverIdent,
GitRepositoryManager repoManager,
AllUsersName allUsersName,
NoteDbMetrics metrics,
AllUsersAsyncUpdate updateAllUsersAsync,
@Assisted Project.NameKey projectName) {
this.serverIdent = serverIdent;
this.repoManager = repoManager;
this.allUsersName = allUsersName;
this.metrics = metrics;
this.updateAllUsersAsync = updateAllUsersAsync;
this.projectName = projectName;
maxUpdates = cfg.getInt("change", null, "maxUpdates", 1000);
changeUpdates = MultimapBuilder.hashKeys().arrayListValues().build();
draftUpdates = MultimapBuilder.hashKeys().arrayListValues().build();
robotCommentUpdates = MultimapBuilder.hashKeys().arrayListValues().build();
rewriters = MultimapBuilder.hashKeys().arrayListValues().build();
toDelete = new HashSet<>();
}
@Override
public void close() {
try {
if (allUsersRepo != null) {
OpenRepo r = allUsersRepo;
allUsersRepo = null;
r.close();
}
} finally {
if (changeRepo != null) {
OpenRepo r = changeRepo;
changeRepo = null;
r.close();
}
}
}
public NoteDbUpdateManager setChangeRepo(
Repository repo, RevWalk rw, @Nullable ObjectInserter ins, ChainedReceiveCommands cmds) {
checkState(changeRepo == null, "change repo already initialized");
changeRepo = new OpenRepo(repo, rw, ins, cmds, false);
return this;
}
public NoteDbUpdateManager setRefLogMessage(String message) {
this.refLogMessage = message;
return this;
}
public NoteDbUpdateManager setRefLogIdent(PersonIdent ident) {
this.refLogIdent = ident;
return this;
}
/**
* Set a push certificate for the push that originally triggered this NoteDb update.
*
* <p>The pusher will not necessarily have specified any of the NoteDb refs explicitly, such as
* when processing a push to {@code refs/for/master}. That's fine; this is just passed to the
* underlying {@link BatchRefUpdate}, and the implementation decides what to do with it.
*
* <p>The cert should be associated with the main repo. There is currently no way of associating a
* push cert with the {@code All-Users} repo, since it is not currently possible to update draft
* changes via push.
*
* @param pushCert push certificate; may be null.
* @return this
*/
public NoteDbUpdateManager setPushCertificate(PushCertificate pushCert) {
this.pushCert = pushCert;
return this;
}
private void initChangeRepo() throws IOException {
if (changeRepo == null) {
changeRepo = OpenRepo.open(repoManager, projectName);
}
}
private void initAllUsersRepo() throws IOException {
if (allUsersRepo == null) {
allUsersRepo = OpenRepo.open(repoManager, allUsersName);
}
}
private boolean isEmpty() {
return changeUpdates.isEmpty()
&& draftUpdates.isEmpty()
&& robotCommentUpdates.isEmpty()
&& rewriters.isEmpty()
&& toDelete.isEmpty()
&& !hasCommands(changeRepo)
&& !hasCommands(allUsersRepo)
&& updateAllUsersAsync.isEmpty();
}
private static boolean hasCommands(@Nullable OpenRepo or) {
return or != null && !or.cmds.isEmpty();
}
/**
* Add an update to the list of updates to execute.
*
* <p>Updates should only be added to the manager after all mutations have been made, as this
* method may eagerly access the update.
*
* @param update the update to add.
*/
public void add(ChangeUpdate update) {
checkNotExecuted();
checkArgument(
update.getProjectName().equals(projectName),
"update for project %s cannot be added to manager for project %s",
update.getProjectName(),
projectName);
checkArgument(
!rewriters.containsKey(update.getRefName()),
"cannot update & rewrite ref %s in one BatchUpdate",
update.getRefName());
ChangeDraftUpdate du = update.getDraftUpdate();
if (du != null) {
draftUpdates.put(du.getRefName(), du);
}
RobotCommentUpdate rcu = update.getRobotCommentUpdate();
if (rcu != null) {
robotCommentUpdates.put(rcu.getRefName(), rcu);
}
DeleteCommentRewriter deleteCommentRewriter = update.getDeleteCommentRewriter();
if (deleteCommentRewriter != null) {
// Checks whether there is any ChangeUpdate or rewriter added earlier for the same ref.
checkArgument(
!changeUpdates.containsKey(deleteCommentRewriter.getRefName()),
"cannot update & rewrite ref %s in one BatchUpdate",
deleteCommentRewriter.getRefName());
checkArgument(
!rewriters.containsKey(deleteCommentRewriter.getRefName()),
"cannot rewrite the same ref %s in one BatchUpdate",
deleteCommentRewriter.getRefName());
rewriters.put(deleteCommentRewriter.getRefName(), deleteCommentRewriter);
}
DeleteChangeMessageRewriter deleteChangeMessageRewriter =
update.getDeleteChangeMessageRewriter();
if (deleteChangeMessageRewriter != null) {
// Checks whether there is any ChangeUpdate or rewriter added earlier for the same ref.
checkArgument(
!changeUpdates.containsKey(deleteChangeMessageRewriter.getRefName()),
"cannot update & rewrite ref %s in one BatchUpdate",
deleteChangeMessageRewriter.getRefName());
checkArgument(
!rewriters.containsKey(deleteChangeMessageRewriter.getRefName()),
"cannot rewrite the same ref %s in one BatchUpdate",
deleteChangeMessageRewriter.getRefName());
rewriters.put(deleteChangeMessageRewriter.getRefName(), deleteChangeMessageRewriter);
}
changeUpdates.put(update.getRefName(), update);
}
public void add(ChangeDraftUpdate draftUpdate) {
checkNotExecuted();
draftUpdates.put(draftUpdate.getRefName(), draftUpdate);
}
public void deleteChange(Change.Id id) {
checkNotExecuted();
toDelete.add(id);
}
/**
* Stage updates in the manager's internal list of commands.
*
* @throws IOException if a storage layer error occurs.
*/
private void stage() throws IOException {
try (Timer1.Context<NoteDbTable> timer = metrics.stageUpdateLatency.start(CHANGES)) {
if (isEmpty()) {
return;
}
initChangeRepo();
if (!draftUpdates.isEmpty() || !toDelete.isEmpty()) {
initAllUsersRepo();
}
addCommands();
}
}
@Nullable
public BatchRefUpdate execute() throws IOException {
return execute(false);
}
@Nullable
public BatchRefUpdate execute(boolean dryrun) throws IOException {
checkNotExecuted();
if (isEmpty()) {
executed = true;
return null;
}
try (Timer1.Context<NoteDbTable> timer = metrics.updateLatency.start(CHANGES)) {
stage();
// ChangeUpdates must execute before ChangeDraftUpdates.
//
// ChangeUpdate will automatically delete draft comments for any published
// comments, but the updates to the two repos don't happen atomically.
// Thus if the change meta update succeeds and the All-Users update fails,
// we may have stale draft comments. Doing it in this order allows stale
// comments to be filtered out by ChangeNotes, reflecting the fact that
// comments can only go from DRAFT to PUBLISHED, not vice versa.
BatchRefUpdate result = execute(changeRepo, dryrun, pushCert);
execute(allUsersRepo, dryrun, null);
if (!dryrun) {
// Only execute the asynchronous operation if we are not in dry-run mode: The dry run would
// have to run synchronous to be of any value at all. For the removal of draft comments from
// All-Users we don't care much of the operation succeeds, so we are skipping the dry run
// altogether.
updateAllUsersAsync.execute(refLogIdent, refLogMessage, pushCert);
}
executed = true;
return result;
} finally {
close();
}
}
private BatchRefUpdate execute(OpenRepo or, boolean dryrun, @Nullable PushCertificate pushCert)
throws IOException {
if (or == null || or.cmds.isEmpty()) {
return null;
}
if (!dryrun) {
or.flush();
} else {
// OpenRepo buffers objects separately; caller may assume that objects are available in the
// inserter it previously passed via setChangeRepo.
or.flushToFinalInserter();
}
BatchRefUpdate bru = or.repo.getRefDatabase().newBatchUpdate();
bru.setPushCertificate(pushCert);
if (refLogMessage != null) {
bru.setRefLogMessage(refLogMessage, false);
} else {
bru.setRefLogMessage(
firstNonNull(NoteDbUtil.guessRestApiHandler(), "Update NoteDb refs"), false);
}
bru.setRefLogIdent(refLogIdent != null ? refLogIdent : serverIdent.get());
bru.setAtomic(true);
or.cmds.addTo(bru);
bru.setAllowNonFastForwards(true);
if (!dryrun) {
RefUpdateUtil.executeChecked(bru, or.rw);
}
return bru;
}
private void addCommands() throws IOException {
changeRepo.addUpdates(changeUpdates, Optional.of(maxUpdates));
if (!draftUpdates.isEmpty()) {
boolean publishOnly = draftUpdates.values().stream().allMatch(ChangeDraftUpdate::canRunAsync);
if (publishOnly) {
updateAllUsersAsync.setDraftUpdates(draftUpdates);
} else {
allUsersRepo.addUpdates(draftUpdates);
}
}
if (!robotCommentUpdates.isEmpty()) {
changeRepo.addUpdates(robotCommentUpdates);
}
if (!rewriters.isEmpty()) {
addRewrites(rewriters, changeRepo);
}
for (Change.Id id : toDelete) {
doDelete(id);
}
}
private void doDelete(Change.Id id) throws IOException {
String metaRef = RefNames.changeMetaRef(id);
Optional<ObjectId> old = changeRepo.cmds.get(metaRef);
if (old.isPresent()) {
changeRepo.cmds.add(new ReceiveCommand(old.get(), ObjectId.zeroId(), metaRef));
}
// Just scan repo for ref names, but get "old" values from cmds.
for (Ref r :
allUsersRepo.repo.getRefDatabase().getRefsByPrefix(RefNames.refsDraftCommentsPrefix(id))) {
old = allUsersRepo.cmds.get(r.getName());
if (old.isPresent()) {
allUsersRepo.cmds.add(new ReceiveCommand(old.get(), ObjectId.zeroId(), r.getName()));
}
}
}
private void checkNotExecuted() {
checkState(!executed, "update has already been executed");
}
private static void addRewrites(ListMultimap<String, NoteDbRewriter> rewriters, OpenRepo openRepo)
throws IOException {
for (Map.Entry<String, Collection<NoteDbRewriter>> entry : rewriters.asMap().entrySet()) {
String refName = entry.getKey();
ObjectId oldTip = openRepo.cmds.get(refName).orElse(ObjectId.zeroId());
if (oldTip.equals(ObjectId.zeroId())) {
throw new StorageException(String.format("Ref %s is empty", refName));
}
ObjectId currTip = oldTip;
try {
for (NoteDbRewriter noteDbRewriter : entry.getValue()) {
ObjectId nextTip =
noteDbRewriter.rewriteCommitHistory(openRepo.rw, openRepo.tempIns, currTip);
if (nextTip != null) {
currTip = nextTip;
}
}
} catch (ConfigInvalidException e) {
throw new StorageException("Cannot rewrite commit history", e);
}
if (!oldTip.equals(currTip)) {
openRepo.cmds.add(new ReceiveCommand(oldTip, currTip, refName));
}
}
}
}
| NoteDbUpdateManager: toDelete->changesToDelete
This is required as a preparation for group deletion
Change-Id: I7f15502679e9d3c13ded15be0e203c9b5f7bac54
| java/com/google/gerrit/server/notedb/NoteDbUpdateManager.java | NoteDbUpdateManager: toDelete->changesToDelete | <ide><path>ava/com/google/gerrit/server/notedb/NoteDbUpdateManager.java
<ide> private final ListMultimap<String, ChangeDraftUpdate> draftUpdates;
<ide> private final ListMultimap<String, RobotCommentUpdate> robotCommentUpdates;
<ide> private final ListMultimap<String, NoteDbRewriter> rewriters;
<del> private final Set<Change.Id> toDelete;
<add> private final Set<Change.Id> changesToDelete;
<ide>
<ide> private OpenRepo changeRepo;
<ide> private OpenRepo allUsersRepo;
<ide> draftUpdates = MultimapBuilder.hashKeys().arrayListValues().build();
<ide> robotCommentUpdates = MultimapBuilder.hashKeys().arrayListValues().build();
<ide> rewriters = MultimapBuilder.hashKeys().arrayListValues().build();
<del> toDelete = new HashSet<>();
<add> changesToDelete = new HashSet<>();
<ide> }
<ide>
<ide> @Override
<ide> && draftUpdates.isEmpty()
<ide> && robotCommentUpdates.isEmpty()
<ide> && rewriters.isEmpty()
<del> && toDelete.isEmpty()
<add> && changesToDelete.isEmpty()
<ide> && !hasCommands(changeRepo)
<ide> && !hasCommands(allUsersRepo)
<ide> && updateAllUsersAsync.isEmpty();
<ide>
<ide> public void deleteChange(Change.Id id) {
<ide> checkNotExecuted();
<del> toDelete.add(id);
<add> changesToDelete.add(id);
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> initChangeRepo();
<del> if (!draftUpdates.isEmpty() || !toDelete.isEmpty()) {
<add> if (!draftUpdates.isEmpty() || !changesToDelete.isEmpty()) {
<ide> initAllUsersRepo();
<ide> }
<ide> addCommands();
<ide> addRewrites(rewriters, changeRepo);
<ide> }
<ide>
<del> for (Change.Id id : toDelete) {
<add> for (Change.Id id : changesToDelete) {
<ide> doDelete(id);
<ide> }
<ide> } |
|
Java | epl-1.0 | f3675b4a31aa3674d0a72e4329e63ce684110adb | 0 | ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio | /*
* Copyright (c) 2010 Stiftung Deutsches Elektronen-Synchrotron,
* Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY.
*
* THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS.
* WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND
* NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE
* IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR
* CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
* NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
* DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
* OR MODIFICATIONS.
* THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION,
* USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS
* PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY
* AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM
*
* $Id$
*/
package org.csstudio.platform;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import org.apache.log4j.Logger;
import org.csstudio.platform.logging.CentralLogger;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IPreferencesService;
/**
* Extend this class to implement your preferences.
*
* A preference must be defined as a constant in the subclass. This class helps you in retrieving typed values and default values.
*
* The constant defines the default value and implicitly the type (it is derived from the default value).
* The constant also defines the string which is used for accessing the value via the preferences api.
*
* @param <T> type of the Preference, must be given in the constant declaration
*
* Example:
* {@code}static final Preference<Integer> TIME = new Preference<Integer>("Time", 3600);
*
* Supported explicit types:<br/>
* <li> java.util.String </li>
* <li> java.util.Integer </li>
* <li> java.util.Long </li>
* <li> java.util.Float </li>
* <li> java.util.Double </li>
* <li> java.util.Boolean </li>
* <li> java.net.URL </li>
*
*
* @author jpenning
* @author $Author$
* @version $Revision$
* @since 10.06.2010
*/
public abstract class AbstractPreference<T> {
private static final Logger LOG =
CentralLogger.getInstance().getLogger(AbstractPreference.class);
interface PrefStrategy<T> {
@Nonnull
T getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final T defaultValue);
}
private static Map<Class<?>, PrefStrategy<?>> TYPE_MAP = new HashMap<Class<?>, PrefStrategy<?>>();
static {
TYPE_MAP.put(Integer.class, new PrefStrategy<Integer>() {
@Override
@Nonnull
public Integer getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Integer defaultValue) {
final IPreferencesService prefs = Platform.getPreferencesService();
return prefs.getInt(context, key, defaultValue, null);
}
});
TYPE_MAP.put(Long.class, new PrefStrategy<Long>() {
@Override
@Nonnull
public Long getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Long defaultValue) {
final IPreferencesService prefs = Platform.getPreferencesService();
return prefs.getLong(context, key, defaultValue, null);
}
});
TYPE_MAP.put(Float.class, new PrefStrategy<Float>() {
@Override
@Nonnull
public Float getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Float defaultValue) {
final IPreferencesService prefs = Platform.getPreferencesService();
return prefs.getFloat(context, key, defaultValue, null);
}
});
TYPE_MAP.put(Double.class, new PrefStrategy<Double>() {
@Override
@Nonnull
public Double getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Double defaultValue) {
final IPreferencesService prefs = Platform.getPreferencesService();
return prefs.getDouble(context, key, defaultValue, null);
}
});
TYPE_MAP.put(Boolean.class, new PrefStrategy<Boolean>() {
@Override
@Nonnull
public Boolean getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Boolean defaultValue) {
final IPreferencesService prefs = Platform.getPreferencesService();
return prefs.getBoolean(context, key, defaultValue, null);
}
});
TYPE_MAP.put(String.class, new PrefStrategy<String>() {
@Override
@Nonnull
public String getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final String defaultValue) {
final IPreferencesService prefs = Platform.getPreferencesService();
return prefs.getString(context, key, defaultValue, null);
}
});
TYPE_MAP.put(URL.class, new PrefStrategy<URL>() {
@Override
@Nonnull
public URL getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final URL defaultValue) {
final IPreferencesService prefs = Platform.getPreferencesService();
try {
return new URL(prefs.getString(context, key, defaultValue.toString(), null));
} catch (final MalformedURLException e) {
CentralLogger.getInstance().error(AbstractPreference.class,
"URL preference is not well formed.", e);
throw new IllegalArgumentException("URL preference not well-formed. " +
"That is not supposed to happen, since the defaultValue is by definition of type URL.");
}
}
});
}
private final String _keyAsString;
private final T _defaultValue;
private final Class<T> _type;
/**
* Constructor.
* @param keyAsString the string used to define the preference in initializers
* @param defaultValue the value used if none is defined in initializers. The type is derived from this value and must match T.
*/
@SuppressWarnings("unchecked")
protected AbstractPreference(@Nonnull final String keyAsString, @Nonnull final T defaultValue) {
assert keyAsString != null : "keyAsString must not be null";
assert defaultValue != null : "defaultValue must not be null";
_keyAsString = keyAsString;
_defaultValue = defaultValue;
_type = (Class<T>) defaultValue.getClass();
}
@Nonnull
public final String getKeyAsString() {
assert _keyAsString != null : "_keyAsString must not be null";
return _keyAsString;
}
/**
* @return the correctly typed value
*/
@SuppressWarnings("unchecked")
@Nonnull
public final T getValue() {
PrefStrategy<T> prefAction = (PrefStrategy<T>) TYPE_MAP.get(_type);
return prefAction.getResult(getPluginID(), getKeyAsString(), _defaultValue);
}
@Nonnull
public final String getDefaultAsString() {
assert _defaultValue != null : "_defaultValue must not be null";
return _defaultValue.toString();
}
@Nonnull
public final T getDefaultValue() {
assert _defaultValue != null : "_defaultValue must not be null";
return _defaultValue;
}
/**
* Collects all preferences that are defined in the derived class.
* Accessible via any preference field in this derived class (cannot be static unfortunately).
*
* @return a list of all preferences
*/
@Nonnull
public List<AbstractPreference<?>> getAllPreferences() {
final Class<? extends AbstractPreference<?>> clazz = getClassType();
final Field[] fields = clazz.getFields();
final List<AbstractPreference<?>> list = new ArrayList<AbstractPreference<?>>();
for (final Field field : fields) {
if (field.getType().equals(clazz)) {
try {
final Object pref = field.get(null); // for static fields param is ignored
list.add((AbstractPreference<?>) pref);
} catch (final IllegalAccessException e) {
LOG.error("One of the preferences constants in class " + clazz.getName() + " is not accessible.", e);
}
}
}
return list;
}
/**
* Returns the runtime (sub-)class of this object.
* @return the runtime (sub-)class of this object
*/
@Nonnull
protected abstract Class<? extends AbstractPreference<T>> getClassType();
/**
* @return the subclass has to define the plugin ID, this is used as the qualifier for preference retrieval.
*/
@Nonnull
protected abstract String getPluginID();
}
| core/plugins/org.csstudio.platform/src/org/csstudio/platform/AbstractPreference.java | /*
* Copyright (c) 2010 Stiftung Deutsches Elektronen-Synchrotron,
* Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY.
*
* THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS.
* WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND
* NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE
* IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR
* CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
* NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
* DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
* OR MODIFICATIONS.
* THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION,
* USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS
* PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY
* AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM
*
* $Id$
*/
package org.csstudio.platform;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.csstudio.platform.logging.CentralLogger;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IPreferencesService;
/**
* Extend this class to implement your preferences.
*
* A preference must be defined as a constant in the subclass. This class helps you in retrieving typed values and default values.
*
* The constant defines the default value and implicitly the type (it is derived from the default value).
* The constant also defines the string which is used for accessing the value via the preferences api.
*
* @param <T> type of the Preference, must be given in the constant declaration
*
* Example:
* {@code}static final Preference<Integer> TIME = new Preference<Integer>("Time", 3600);
*
* Supported explicit types:<br/>
* <li> java.util.String </li>
* <li> java.util.Integer </li>
* <li> java.util.Long </li>
* <li> java.util.Float </li>
* <li> java.util.Double </li>
* <li> java.util.Boolean </li>
* <li> java.net.URL </li>
*
*
* @author jpenning
* @author $Author$
* @version $Revision$
* @since 10.06.2010
*/
public abstract class AbstractPreference<T> {
private static final Logger LOG =
CentralLogger.getInstance().getLogger(AbstractPreference.class);
private final String _keyAsString;
private final T _defaultValue;
private final Class<?> _type;
/**
* Constructor.
* @param keyAsString the string used to define the preference in initializers
* @param defaultValue the value used if none is defined in initializers. The type is derived from this value and must match T.
*/
protected AbstractPreference(final String keyAsString, final T defaultValue) {
assert keyAsString != null : "keyAsString must not be null";
assert defaultValue != null : "defaultValue must not be null";
_keyAsString = keyAsString;
_defaultValue = defaultValue;
_type = defaultValue.getClass();
}
public final String getKeyAsString() {
assert _keyAsString != null : "_keyAsString must not be null";
return _keyAsString;
}
/**
* @return the correctly typed value
*/
@SuppressWarnings("unchecked")
public final T getValue() {
final IPreferencesService prefs = Platform.getPreferencesService();
Object result = null;
if (_type.equals(String.class)) {
result = prefs.getString(getPluginID(), getKeyAsString(), (String) _defaultValue, null);
} else if (_type.equals(Integer.class)) {
result = prefs.getInt(getPluginID(), getKeyAsString(), (Integer) _defaultValue, null);
} else if (_type.equals(Long.class)) {
result = prefs.getLong(getPluginID(), getKeyAsString(), (Long) _defaultValue, null);
} else if (_type.equals(Float.class)) {
result = prefs.getFloat(getPluginID(), getKeyAsString(), (Float) _defaultValue, null);
} else if (_type.equals(Double.class)) {
result = prefs.getDouble(getPluginID(), getKeyAsString(), (Double) _defaultValue, null);
} else if (_type.equals(Boolean.class)) {
result = prefs.getBoolean(getPluginID(), getKeyAsString(), (Boolean) _defaultValue, null);
} else if (_type.equals(URL.class)) {
try {
result = new URL(prefs.getString(getPluginID(), getKeyAsString(), _defaultValue.toString(), null));
} catch (final MalformedURLException e) {
LOG.error("URL preference is not well formed.", e);
}
}
assert result != null : "result must not be null";
return (T) result;
}
public final String getDefaultAsString() {
assert _defaultValue != null : "_defaultValue must not be null";
return _defaultValue.toString();
}
public final T getDefaultValue() {
assert _defaultValue != null : "_defaultValue must not be null";
return _defaultValue;
}
/**
* Collects all preferences that are defined in the derived class.
* Accessible via any preference field in this derived class (cannot be static unfortunately).
*
* @return a list of all preferences
*/
@SuppressWarnings("unchecked")
public List<AbstractPreference<?>> getAllPreferences() {
final Class<? extends AbstractPreference> clazz = getClassType();
final Field[] fields = clazz.getFields();
final List<AbstractPreference<?>> list = new ArrayList<AbstractPreference<?>>();
for (final Field field : fields) {
if (field.getType().equals(clazz)) {
try {
final Object pref = field.get(null); // for static fields param is ignored
list.add((AbstractPreference<?>) pref);
} catch (final IllegalAccessException e) {
LOG.error("One of the preferences constants in class " + clazz.getName() + " is not accessible.", e);
}
}
}
return list;
}
/**
* Returns the runtime (sub-)class of this object.
* @return the runtime (sub-)class of this object
*/
protected abstract Class<? extends AbstractPreference<T>> getClassType();
/**
* @return the subclass has to define the plugin ID, this is used as the qualifier for preference retrieval.
*/
protected abstract String getPluginID();
}
| o.c.platform: added type support map
| core/plugins/org.csstudio.platform/src/org/csstudio/platform/AbstractPreference.java | o.c.platform: added type support map | <ide><path>ore/plugins/org.csstudio.platform/src/org/csstudio/platform/AbstractPreference.java
<ide> import java.net.MalformedURLException;
<ide> import java.net.URL;
<ide> import java.util.ArrayList;
<add>import java.util.HashMap;
<ide> import java.util.List;
<add>import java.util.Map;
<add>
<add>import javax.annotation.Nonnull;
<ide>
<ide> import org.apache.log4j.Logger;
<ide> import org.csstudio.platform.logging.CentralLogger;
<ide> private static final Logger LOG =
<ide> CentralLogger.getInstance().getLogger(AbstractPreference.class);
<ide>
<add> interface PrefStrategy<T> {
<add> @Nonnull
<add> T getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final T defaultValue);
<add> }
<add> private static Map<Class<?>, PrefStrategy<?>> TYPE_MAP = new HashMap<Class<?>, PrefStrategy<?>>();
<add> static {
<add> TYPE_MAP.put(Integer.class, new PrefStrategy<Integer>() {
<add> @Override
<add> @Nonnull
<add> public Integer getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Integer defaultValue) {
<add> final IPreferencesService prefs = Platform.getPreferencesService();
<add> return prefs.getInt(context, key, defaultValue, null);
<add> }
<add> });
<add> TYPE_MAP.put(Long.class, new PrefStrategy<Long>() {
<add> @Override
<add> @Nonnull
<add> public Long getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Long defaultValue) {
<add> final IPreferencesService prefs = Platform.getPreferencesService();
<add> return prefs.getLong(context, key, defaultValue, null);
<add> }
<add> });
<add> TYPE_MAP.put(Float.class, new PrefStrategy<Float>() {
<add> @Override
<add> @Nonnull
<add> public Float getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Float defaultValue) {
<add> final IPreferencesService prefs = Platform.getPreferencesService();
<add> return prefs.getFloat(context, key, defaultValue, null);
<add> }
<add> });
<add> TYPE_MAP.put(Double.class, new PrefStrategy<Double>() {
<add> @Override
<add> @Nonnull
<add> public Double getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Double defaultValue) {
<add> final IPreferencesService prefs = Platform.getPreferencesService();
<add> return prefs.getDouble(context, key, defaultValue, null);
<add> }
<add> });
<add> TYPE_MAP.put(Boolean.class, new PrefStrategy<Boolean>() {
<add> @Override
<add> @Nonnull
<add> public Boolean getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final Boolean defaultValue) {
<add> final IPreferencesService prefs = Platform.getPreferencesService();
<add> return prefs.getBoolean(context, key, defaultValue, null);
<add> }
<add> });
<add> TYPE_MAP.put(String.class, new PrefStrategy<String>() {
<add> @Override
<add> @Nonnull
<add> public String getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final String defaultValue) {
<add> final IPreferencesService prefs = Platform.getPreferencesService();
<add> return prefs.getString(context, key, defaultValue, null);
<add> }
<add> });
<add> TYPE_MAP.put(URL.class, new PrefStrategy<URL>() {
<add> @Override
<add> @Nonnull
<add> public URL getResult(@Nonnull final String context, @Nonnull final String key, @Nonnull final URL defaultValue) {
<add> final IPreferencesService prefs = Platform.getPreferencesService();
<add> try {
<add> return new URL(prefs.getString(context, key, defaultValue.toString(), null));
<add> } catch (final MalformedURLException e) {
<add> CentralLogger.getInstance().error(AbstractPreference.class,
<add> "URL preference is not well formed.", e);
<add> throw new IllegalArgumentException("URL preference not well-formed. " +
<add> "That is not supposed to happen, since the defaultValue is by definition of type URL.");
<add> }
<add> }
<add> });
<add> }
<add>
<add>
<ide> private final String _keyAsString;
<ide> private final T _defaultValue;
<del> private final Class<?> _type;
<add> private final Class<T> _type;
<ide>
<ide> /**
<ide> * Constructor.
<ide> * @param keyAsString the string used to define the preference in initializers
<ide> * @param defaultValue the value used if none is defined in initializers. The type is derived from this value and must match T.
<ide> */
<del> protected AbstractPreference(final String keyAsString, final T defaultValue) {
<add> @SuppressWarnings("unchecked")
<add> protected AbstractPreference(@Nonnull final String keyAsString, @Nonnull final T defaultValue) {
<ide> assert keyAsString != null : "keyAsString must not be null";
<ide> assert defaultValue != null : "defaultValue must not be null";
<ide>
<ide> _keyAsString = keyAsString;
<ide> _defaultValue = defaultValue;
<del> _type = defaultValue.getClass();
<del> }
<del>
<add> _type = (Class<T>) defaultValue.getClass();
<add> }
<add>
<add> @Nonnull
<ide> public final String getKeyAsString() {
<ide> assert _keyAsString != null : "_keyAsString must not be null";
<ide>
<ide> return _keyAsString;
<ide> }
<ide>
<add>
<add>
<ide> /**
<ide> * @return the correctly typed value
<ide> */
<ide> @SuppressWarnings("unchecked")
<add> @Nonnull
<ide> public final T getValue() {
<del> final IPreferencesService prefs = Platform.getPreferencesService();
<del>
<del> Object result = null;
<del>
<del> if (_type.equals(String.class)) {
<del> result = prefs.getString(getPluginID(), getKeyAsString(), (String) _defaultValue, null);
<del> } else if (_type.equals(Integer.class)) {
<del> result = prefs.getInt(getPluginID(), getKeyAsString(), (Integer) _defaultValue, null);
<del> } else if (_type.equals(Long.class)) {
<del> result = prefs.getLong(getPluginID(), getKeyAsString(), (Long) _defaultValue, null);
<del> } else if (_type.equals(Float.class)) {
<del> result = prefs.getFloat(getPluginID(), getKeyAsString(), (Float) _defaultValue, null);
<del> } else if (_type.equals(Double.class)) {
<del> result = prefs.getDouble(getPluginID(), getKeyAsString(), (Double) _defaultValue, null);
<del> } else if (_type.equals(Boolean.class)) {
<del> result = prefs.getBoolean(getPluginID(), getKeyAsString(), (Boolean) _defaultValue, null);
<del> } else if (_type.equals(URL.class)) {
<del> try {
<del> result = new URL(prefs.getString(getPluginID(), getKeyAsString(), _defaultValue.toString(), null));
<del> } catch (final MalformedURLException e) {
<del> LOG.error("URL preference is not well formed.", e);
<del> }
<del> }
<del>
<del> assert result != null : "result must not be null";
<del> return (T) result;
<del> }
<del>
<add> PrefStrategy<T> prefAction = (PrefStrategy<T>) TYPE_MAP.get(_type);
<add> return prefAction.getResult(getPluginID(), getKeyAsString(), _defaultValue);
<add> }
<add>
<add> @Nonnull
<ide> public final String getDefaultAsString() {
<ide> assert _defaultValue != null : "_defaultValue must not be null";
<ide>
<ide> return _defaultValue.toString();
<ide> }
<ide>
<add> @Nonnull
<ide> public final T getDefaultValue() {
<ide> assert _defaultValue != null : "_defaultValue must not be null";
<ide>
<ide> *
<ide> * @return a list of all preferences
<ide> */
<del> @SuppressWarnings("unchecked")
<add> @Nonnull
<ide> public List<AbstractPreference<?>> getAllPreferences() {
<ide>
<del> final Class<? extends AbstractPreference> clazz = getClassType();
<add> final Class<? extends AbstractPreference<?>> clazz = getClassType();
<ide>
<ide> final Field[] fields = clazz.getFields();
<ide>
<ide> final List<AbstractPreference<?>> list = new ArrayList<AbstractPreference<?>>();
<del> for (final Field field : fields) {
<del> if (field.getType().equals(clazz)) {
<del> try {
<del> final Object pref = field.get(null); // for static fields param is ignored
<del> list.add((AbstractPreference<?>) pref);
<del> } catch (final IllegalAccessException e) {
<del> LOG.error("One of the preferences constants in class " + clazz.getName() + " is not accessible.", e);
<del> }
<add> for (final Field field : fields) {
<add> if (field.getType().equals(clazz)) {
<add> try {
<add> final Object pref = field.get(null); // for static fields param is ignored
<add> list.add((AbstractPreference<?>) pref);
<add> } catch (final IllegalAccessException e) {
<add> LOG.error("One of the preferences constants in class " + clazz.getName() + " is not accessible.", e);
<ide> }
<ide> }
<add> }
<ide> return list;
<ide> }
<ide>
<ide> * Returns the runtime (sub-)class of this object.
<ide> * @return the runtime (sub-)class of this object
<ide> */
<add> @Nonnull
<ide> protected abstract Class<? extends AbstractPreference<T>> getClassType();
<ide>
<ide> /**
<ide> * @return the subclass has to define the plugin ID, this is used as the qualifier for preference retrieval.
<ide> */
<add> @Nonnull
<ide> protected abstract String getPluginID();
<ide>
<ide> } |
|
Java | lgpl-2.1 | fdea28929d5fbcd1b530554f7f3044265c5128cc | 0 | andreasprlic/biojava,heuermh/biojava,pwrose/biojava,zachcp/biojava,fionakim/biojava,JolantaWojcik/biojavaOwn,emckee2006/biojava,heuermh/biojava,biojava/biojava,andreasprlic/biojava,fionakim/biojava,pwrose/biojava,zachcp/biojava,paolopavan/biojava,emckee2006/biojava,JolantaWojcik/biojavaOwn,pwrose/biojava,lafita/biojava,heuermh/biojava,andreasprlic/biojava,paolopavan/biojava,emckee2006/biojava,lafita/biojava,sbliven/biojava-sbliven,andreasprlic/biojava,zachcp/biojava,paolopavan/biojava,sbliven/biojava-sbliven,lafita/biojava,biojava/biojava,fionakim/biojava,sbliven/biojava-sbliven,biojava/biojava | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.biojava3.genome;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.logging.Logger;
import org.biojava3.core.sequence.AccessionID;
import org.biojava3.core.sequence.CDSSequence;
import org.biojava3.core.sequence.ChromosomeSequence;
import org.biojava3.core.sequence.DNASequence;
import org.biojava3.core.sequence.ExonSequence;
import org.biojava3.core.sequence.io.FastaReaderHelper;
import org.biojava3.core.sequence.io.FastaWriterHelper;
import org.biojava3.core.sequence.GeneSequence;
import org.biojava3.core.sequence.ProteinSequence;
import org.biojava3.core.sequence.Strand;
import org.biojava3.core.sequence.TranscriptSequence;
import org.biojava3.genome.parsers.gff.Feature;
import org.biojava3.genome.parsers.gff.FeatureI;
import org.biojava3.genome.parsers.gff.FeatureList;
import org.biojava3.genome.parsers.gff.GFF3Reader;
import org.biojava3.genome.parsers.gff.GeneIDGFF2Reader;
import org.biojava3.genome.parsers.gff.GeneMarkGTFReader;
/**
*
* @author Scooter Willis <willishf at gmail dot com>
*/
public class GeneFeatureHelper {
private static final Logger log = Logger.getLogger(GeneFeatureHelper.class.getName());
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromUpperCaseExonFastaFile(File fastaSequenceFile,File uppercaseFastaFile, boolean throwExceptionGeneNotFound) throws Exception{
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = new LinkedHashMap<String, ChromosomeSequence>();
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
for(String accession : dnaSequenceList.keySet()){
DNASequence contigSequence = dnaSequenceList.get(accession);
ChromosomeSequence chromsomeSequence = new ChromosomeSequence(contigSequence.getSequenceAsString());
chromsomeSequence.setAccession(contigSequence.getAccession());
chromosomeSequenceList.put(accession, chromsomeSequence);
}
LinkedHashMap<String, DNASequence> geneSequenceList = FastaReaderHelper.readFastaDNASequence(uppercaseFastaFile);
for(DNASequence dnaSequence : geneSequenceList.values()){
String geneSequence = dnaSequence.getSequenceAsString();
String lcGeneSequence = geneSequence.toLowerCase();
String reverseGeneSequence = dnaSequence.getReverseComplement().getSequenceAsString();
String lcReverseGeneSequence = reverseGeneSequence.toLowerCase();
Integer bioStart = null;
Integer bioEnd = null;
Strand strand = Strand.POSITIVE;
boolean geneFound = false;
String accession = "";
DNASequence contigDNASequence = null;
for(String id : dnaSequenceList.keySet()){
accession = id;
contigDNASequence = dnaSequenceList.get(id);
String contigSequence = contigDNASequence.getSequenceAsString().toLowerCase();
bioStart = contigSequence.indexOf(lcGeneSequence);
if(bioStart != -1){
bioStart = bioStart + 1;
bioEnd = bioStart + geneSequence.length() - 1;
geneFound = true;
break;
}else{
bioStart = contigSequence.indexOf(lcReverseGeneSequence);
if(bioStart != -1){
bioStart = bioStart + 1;
bioEnd = bioStart - geneSequence.length() - 1;
strand = Strand.NEGATIVE;
geneFound = true;
break;
}
}
}
if(geneFound){
System.out.println("Gene " + dnaSequence.getAccession().toString() + " found at " + contigDNASequence.getAccession().toString() + " " + bioStart + " " + bioEnd + " " + strand);
ChromosomeSequence chromosomeSequence = chromosomeSequenceList.get(accession);
ArrayList<Integer> exonBoundries = new ArrayList<Integer>();
//look for transitions from lowercase to upper case
for(int i = 0; i < geneSequence.length(); i++){
if(i == 0 && Character.isUpperCase(geneSequence.charAt(i))){
exonBoundries.add(i);
}else if(i == geneSequence.length() - 1) {
exonBoundries.add(i);
}else if(Character.isUpperCase(geneSequence.charAt(i)) && Character.isLowerCase(geneSequence.charAt(i - 1))){
exonBoundries.add(i);
}else if(Character.isUpperCase(geneSequence.charAt(i)) && Character.isLowerCase(geneSequence.charAt(i + 1))){
exonBoundries.add(i);
}
}
if(strand == Strand.NEGATIVE){
Collections.reverse(exonBoundries);
}
GeneSequence geneSeq = chromosomeSequence.addGene(dnaSequence.getAccession(), bioStart, bioEnd, strand);
geneSeq.setSource(uppercaseFastaFile.getName());
String transcriptName = dnaSequence.getAccession().getID() + "-transcript";
TranscriptSequence transcriptSequence = geneSeq.addTranscript(new AccessionID(transcriptName), bioStart, bioEnd);
int runningFrameLength = 0;
for(int i = 0; i < exonBoundries.size() - 1; i = i + 2){
int cdsBioStart = exonBoundries.get(i) + bioStart;
int cdsBioEnd = exonBoundries.get(i + 1) + bioStart;
runningFrameLength = runningFrameLength + Math.abs(cdsBioEnd - cdsBioStart) + 1;
String cdsName = transcriptName + "-cds-" + cdsBioStart + "-" + cdsBioEnd;
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSeq.addExon(cdsAccessionID, cdsBioStart, cdsBioEnd);
int remainder = runningFrameLength % 3;
int frame = 0;
if(remainder == 1){
frame = 2; // borrow 2 from next CDS region
}else if(remainder == 2){
frame = 1;
}
CDSSequence cdsSequence = transcriptSequence.addCDS(cdsAccessionID, cdsBioStart, cdsBioEnd, frame);
}
}else{
if(throwExceptionGeneNotFound){
throw new Exception(dnaSequence.getAccession().toString() + " not found");
}
System.out.println("Gene not found " + dnaSequence.getAccession().toString());
}
}
return chromosomeSequenceList;
}
/**
* Output a gff3 feature file that will give the length of each scaffold/chromosome in the fasta file.
* Used for gbrowse so it knows length.
* @param fastaSequenceFile
* @param gffFile
* @throws Exception
*/
static public void outputFastaSequenceLengthGFF3(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
String fileName = fastaSequenceFile.getName();
FileWriter fw = new FileWriter(gffFile);
fw.write("##gff-version 3\n");
for (DNASequence dnaSequence : dnaSequenceList.values()) {
String gff3line = dnaSequence.getAccession().getID() + "\t" + fileName + "\t" + "contig" + "\t" + "1" + "\t" + dnaSequence.getBioEnd() + "\t.\t.\t.\tName=" + dnaSequence.getAccession().getID() + "\n";
fw.write(gff3line);
}
fw.close();
}
/**
* Loads Fasta file and GFF2 feature file generated from the geneid prediction algorithm
*
* @param fastaSequenceFile
* @param gffFile
* @return
* @throws Exception
*/
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromGeneIDGFF2(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.getChromosomeSequenceFromDNASequence(dnaSequenceList);
FeatureList listGenes = GeneIDGFF2Reader.read(gffFile.getAbsolutePath());
addGeneIDGFF2GeneFeatures(chromosomeSequenceList, listGenes);
return chromosomeSequenceList;
}
/**
* Load GFF2 feature file generated from the geneid prediction algorithm and map features onto the chromosome sequences
*
* @param chromosomeSequenceList
* @param listGenes
* @throws Exception
*/
static public void addGeneIDGFF2GeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
Collection<String> geneIds = listGenes.attributeValues("gene_id");
for (String geneid : geneIds) {
FeatureList gene = listGenes.selectByAttribute("gene_id", geneid);
FeatureI geneFeature = gene.get(0);
ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
geneid = geneid.replaceAll("_", ".G");
AccessionID geneAccessionID = new AccessionID(geneid);
GeneSequence geneSequence = null;
Collection<String> transcriptids = gene.attributeValues("gene_id");
for (String transcriptid : transcriptids) {
// get all the individual features (exons, CDS regions, etc.) of this gene
FeatureList transcriptFeature = listGenes.selectByAttribute("gene_id", transcriptid);
transcriptid = transcriptid.replaceAll("_", ".G");
// String seqName = feature.seqname();
FeatureI startCodon = null;
FeatureI stopCodon = null;
Integer startCodonBegin = null;
Integer stopCodonEnd = null;
String startCodonName = "";
String stopCodonName = "";
// now select only the coding regions of this gene
FeatureList firstFeatures = transcriptFeature.selectByType("First");
FeatureList terminalFeatures = transcriptFeature.selectByType("Terminal");
FeatureList internalFeatures = transcriptFeature.selectByType("Internal");
FeatureList singleFeatures = transcriptFeature.selectByType("Single");
FeatureList cdsFeatures = new FeatureList();
cdsFeatures.add(firstFeatures);
cdsFeatures.add(terminalFeatures);
cdsFeatures.add(internalFeatures);
cdsFeatures.add(singleFeatures);
// sort them
cdsFeatures = cdsFeatures.sortByStart();
Strand strand = Strand.POSITIVE;
FeatureI feature = cdsFeatures.get(0);
if (feature.location().isNegative()) {
strand = strand.NEGATIVE;
}
if (startCodonBegin == null) {
FeatureI firstFeature = cdsFeatures.get(0);
if (strand == strand.NEGATIVE) {
startCodonBegin = firstFeature.location().bioEnd();
} else {
startCodonBegin = firstFeature.location().bioStart();
}
}
if (stopCodonEnd == null) {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
if (strand == strand.NEGATIVE) {
stopCodonEnd = lastFeature.location().bioStart();
} else {
stopCodonEnd = lastFeature.location().bioEnd();
}
}
//for gtf ordering can be strand based so first is last and last is first
if (startCodonBegin > stopCodonEnd) {
int temp = startCodonBegin;
startCodonBegin = stopCodonEnd;
stopCodonEnd = temp;
}
AccessionID transcriptAccessionID = new AccessionID(transcriptid);
if (geneSequence == null) {
geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
geneSequence.setSource(((Feature) feature).source());
} else {
//if multiple transcripts for one gene make sure the gene is defined as the min and max start/end
if (startCodonBegin < geneSequence.getBioBegin()) {
geneSequence.setBioBegin(startCodonBegin);
}
if (stopCodonEnd > geneSequence.getBioBegin()) {
geneSequence.setBioEnd(stopCodonEnd);
}
}
TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
if (startCodon != null) {
if (startCodonName == null || startCodonName.length() == 0) {
startCodonName = transcriptid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
}
transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
}
if (stopCodon != null) {
if (stopCodonName == null || stopCodonName.length() == 0) {
stopCodonName = transcriptid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
}
transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
}
for (FeatureI cdsFeature : cdsFeatures) {
Feature cds = (Feature) cdsFeature;
String cdsName = cds.getAttribute("transcript_name");
if (cdsName == null || cdsName.length() == 0) {
cdsName = transcriptid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
}
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
CDSSequence cdsSequence = transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());
cdsSequence.setSequenceScore(cds.score());
}
}
}
}
static public LinkedHashMap<String, ChromosomeSequence> getChromosomeSequenceFromDNASequence(LinkedHashMap<String, DNASequence> dnaSequenceList) {
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = new LinkedHashMap<String, ChromosomeSequence>();
for (String key : dnaSequenceList.keySet()) {
DNASequence dnaSequence = dnaSequenceList.get(key);
ChromosomeSequence chromosomeSequence = new ChromosomeSequence(dnaSequence.getSequenceAsString());
chromosomeSequence.setAccession(dnaSequence.getAccession());
chromosomeSequenceList.put(key, chromosomeSequence);
}
return chromosomeSequenceList;
}
/**
* Lots of variations in the ontology or descriptors that can be used in GFF3 which requires writing a custom parser to handle a GFF3 generated or used
* by a specific application. Probably could be abstracted out but for now easier to handle with custom code to deal with gff3 elements that are not
* included but can be extracted from other data elements.
* @param fastaSequenceFile
* @param gffFile
* @return
* @throws Exception
*/
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromGmodGFF3(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.getChromosomeSequenceFromDNASequence(dnaSequenceList);
FeatureList listGenes = GFF3Reader.read(gffFile.getAbsolutePath());
addGmodGFF3GeneFeatures(chromosomeSequenceList, listGenes);
return chromosomeSequenceList;
}
static public void addGmodGFF3GeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
FeatureList mRNAFeatures = listGenes.selectByType("mRNA");
for (FeatureI f : mRNAFeatures) {
Feature mRNAFeature = (Feature) f;
String geneid = mRNAFeature.getAttribute("ID");
String source = mRNAFeature.source();
FeatureList gene = listGenes.selectByAttribute("Parent", geneid);
FeatureI geneFeature = gene.get(0);
ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
AccessionID geneAccessionID = new AccessionID(geneid);
GeneSequence geneSequence = null;
FeatureList cdsFeatures = gene.selectByType("CDS");
FeatureI feature = cdsFeatures.get(0);
Strand strand = Strand.POSITIVE;
if (feature.location().isNegative()) {
strand = strand.NEGATIVE;
}
cdsFeatures = cdsFeatures.sortByStart();
String seqName = feature.seqname();
FeatureI startCodon = null;
FeatureI stopCodon = null;
Integer startCodonBegin = null;
Integer stopCodonEnd = null;
String startCodonName = "";
String stopCodonName = "";
FeatureList startCodonList = gene.selectByType("five_prime_UTR");
if (startCodonList != null && startCodonList.size() > 0) {
startCodon = startCodonList.get(0);
if (strand == Strand.NEGATIVE) {
startCodonBegin = startCodon.location().bioEnd();
} else {
startCodonBegin = startCodon.location().bioStart();
}
startCodonName = startCodon.getAttribute("ID");
}
FeatureList stopCodonList = gene.selectByType("three_prime_UTR");
if (stopCodonList != null && stopCodonList.size() > 0) {
stopCodon = stopCodonList.get(0);
if (strand == Strand.NEGATIVE) {
stopCodonEnd = stopCodon.location().bioStart();
} else {
stopCodonEnd = stopCodon.location().bioEnd();
}
stopCodonName = stopCodon.getAttribute("ID");
}
if (startCodonBegin == null) {
if (strand == Strand.NEGATIVE) {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioEnd();
} else {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioStart();
}
}
if (stopCodonEnd == null) {
if (strand == Strand.NEGATIVE) {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioStart();
} else {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioEnd();
}
}
//for gtf ordering can be strand based so first is last and last is first
if (startCodonBegin > stopCodonEnd) {
int temp = startCodonBegin;
startCodonBegin = stopCodonEnd;
stopCodonEnd = temp;
}
AccessionID transcriptAccessionID = new AccessionID(geneid);
if (geneSequence == null) {
geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
geneSequence.setSource(source);
} else {
if (startCodonBegin < geneSequence.getBioBegin()) {
geneSequence.setBioBegin(startCodonBegin);
}
if (stopCodonEnd > geneSequence.getBioBegin()) {
geneSequence.setBioEnd(stopCodonEnd);
}
}
TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
if (startCodon != null) {
if (startCodonName == null || startCodonName.length() == 0) {
startCodonName = geneid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
}
transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
}
if (stopCodon != null) {
if (stopCodonName == null || stopCodonName.length() == 0) {
stopCodonName = geneid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
}
transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
}
for (FeatureI cdsFeature : cdsFeatures) {
Feature cds = (Feature) cdsFeature;
String cdsName = cds.getAttribute("ID");
if (cdsName == null || cdsName.length() == 0) {
cdsName = geneid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
}
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());
}
}
}
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromGlimmerGFF3(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.getChromosomeSequenceFromDNASequence(dnaSequenceList);
FeatureList listGenes = GFF3Reader.read(gffFile.getAbsolutePath());
addGlimmerGFF3GeneFeatures(chromosomeSequenceList, listGenes);
return chromosomeSequenceList;
}
static public void addGlimmerGFF3GeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
FeatureList mRNAFeatures = listGenes.selectByType("mRNA");
for (FeatureI f : mRNAFeatures) {
Feature mRNAFeature = (Feature) f;
String geneid = mRNAFeature.getAttribute("ID");
String source = mRNAFeature.source();
FeatureList gene = listGenes.selectByAttribute("Parent", geneid);
FeatureI geneFeature = gene.get(0);
ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
AccessionID geneAccessionID = new AccessionID(geneid);
GeneSequence geneSequence = null;
FeatureList cdsFeatures = gene.selectByType("CDS");
FeatureI feature = cdsFeatures.get(0);
Strand strand = Strand.POSITIVE;
if (feature.location().isNegative()) {
strand = strand.NEGATIVE;
}
cdsFeatures = cdsFeatures.sortByStart();
String seqName = feature.seqname();
FeatureI startCodon = null;
FeatureI stopCodon = null;
Integer startCodonBegin = null;
Integer stopCodonEnd = null;
String startCodonName = "";
String stopCodonName = "";
FeatureList startCodonList = gene.selectByAttribute("Note", "initial-exon");
if (startCodonList != null && startCodonList.size() > 0) {
startCodon = startCodonList.get(0);
if (strand == Strand.NEGATIVE) {
startCodonBegin = startCodon.location().bioEnd();
} else {
startCodonBegin = startCodon.location().bioStart();
}
startCodonName = startCodon.getAttribute("ID");
}
FeatureList stopCodonList = gene.selectByAttribute("Note", "final-exon");
if (stopCodonList != null && stopCodonList.size() > 0) {
stopCodon = stopCodonList.get(0);
if (strand == Strand.NEGATIVE) {
stopCodonEnd = stopCodon.location().bioStart();
} else {
stopCodonEnd = stopCodon.location().bioEnd();
}
stopCodonName = stopCodon.getAttribute("ID");
}
if (startCodonBegin == null) {
if (strand == Strand.NEGATIVE) {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioEnd();
} else {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioStart();
}
}
if (stopCodonEnd == null) {
if (strand == Strand.NEGATIVE) {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioStart();
} else {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioEnd();
}
}
//for gtf ordering can be strand based so first is last and last is first
if (startCodonBegin > stopCodonEnd) {
int temp = startCodonBegin;
startCodonBegin = stopCodonEnd;
stopCodonEnd = temp;
}
AccessionID transcriptAccessionID = new AccessionID(geneid);
if (geneSequence == null) {
geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
geneSequence.setSource(source);
} else {
if (startCodonBegin < geneSequence.getBioBegin()) {
geneSequence.setBioBegin(startCodonBegin);
}
if (stopCodonEnd > geneSequence.getBioBegin()) {
geneSequence.setBioEnd(stopCodonEnd);
}
}
TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
if (startCodon != null) {
if (startCodonName == null || startCodonName.length() == 0) {
startCodonName = geneid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
}
transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
}
if (stopCodon != null) {
if (stopCodonName == null || stopCodonName.length() == 0) {
stopCodonName = geneid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
}
transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
}
for (FeatureI cdsFeature : cdsFeatures) {
Feature cds = (Feature) cdsFeature;
String cdsName = cds.getAttribute("ID");
if (cdsName == null || cdsName.length() == 0) {
cdsName = geneid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
}
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());
}
}
}
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromGeneMarkGTF(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.getChromosomeSequenceFromDNASequence(dnaSequenceList);
FeatureList listGenes = GeneMarkGTFReader.read(gffFile.getAbsolutePath());
addGeneMarkGTFGeneFeatures(chromosomeSequenceList, listGenes);
return chromosomeSequenceList;
}
static public void addGeneMarkGTFGeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
Collection<String> geneIds = listGenes.attributeValues("gene_id");
for (String geneid : geneIds) {
// if(geneid.equals("45_g")){
// int dummy =1;
// }
FeatureList gene = listGenes.selectByAttribute("gene_id", geneid);
FeatureI geneFeature = gene.get(0);
ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
AccessionID geneAccessionID = new AccessionID(geneid);
GeneSequence geneSequence = null;
Collection<String> transcriptids = gene.attributeValues("transcript_id");
for (String transcriptid : transcriptids) {
// get all the individual features (exons, CDS regions, etc.) of this gene
FeatureList transcriptFeature = listGenes.selectByAttribute("transcript_id", transcriptid);
// now select only the coding regions of this gene
FeatureList cdsFeatures = transcriptFeature.selectByType("CDS");
// sort them
cdsFeatures = cdsFeatures.sortByStart();
FeatureI feature = cdsFeatures.get(0);
Strand strand = Strand.POSITIVE;
if (feature.location().isNegative()) {
strand = strand.NEGATIVE;
}
String seqName = feature.seqname();
FeatureI startCodon = null;
FeatureI stopCodon = null;
Integer startCodonBegin = null;
Integer stopCodonEnd = null;
String startCodonName = "";
String stopCodonName = "";
FeatureList startCodonList = transcriptFeature.selectByType("start_codon");
if (startCodonList != null && startCodonList.size() > 0) {
startCodon = startCodonList.get(0);
if (strand == Strand.POSITIVE) {
startCodonBegin = startCodon.location().bioStart();
} else {
startCodonBegin = startCodon.location().bioEnd();
}
startCodonName = startCodon.getAttribute("transcript_name");
}
FeatureList stopCodonList = transcriptFeature.selectByType("stop_codon");
if (stopCodonList != null && stopCodonList.size() > 0) {
stopCodon = stopCodonList.get(0);
if (strand == Strand.POSITIVE) {
stopCodonEnd = stopCodon.location().bioEnd();
} else {
stopCodonEnd = stopCodon.location().bioStart();
}
stopCodonName = stopCodon.getAttribute("transcript_name");
}
if (startCodonBegin == null) {
if (strand == Strand.NEGATIVE) {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioEnd();
} else {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioStart();
}
}
if (stopCodonEnd == null) {
if (strand == Strand.NEGATIVE) {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioStart();
} else {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioEnd();
}
}
//for gtf ordering can be strand based so first is last and last is first
if (startCodonBegin > stopCodonEnd) {
int temp = startCodonBegin;
startCodonBegin = stopCodonEnd;
stopCodonEnd = temp;
}
AccessionID transcriptAccessionID = new AccessionID(transcriptid);
if (geneSequence == null) {
geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
geneSequence.setSource(((Feature) feature).source());
} else {
//if multiple transcripts for one gene make sure the gene is defined as the min and max start/end
if (startCodonBegin < geneSequence.getBioBegin()) {
geneSequence.setBioBegin(startCodonBegin);
}
if (stopCodonEnd > geneSequence.getBioBegin()) {
geneSequence.setBioEnd(stopCodonEnd);
}
}
TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
if (startCodon != null) {
if (startCodonName == null || startCodonName.length() == 0) {
startCodonName = transcriptid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
}
transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
}
if (stopCodon != null) {
if (stopCodonName == null || stopCodonName.length() == 0) {
stopCodonName = transcriptid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
}
transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
}
for (FeatureI cdsFeature : cdsFeatures) {
Feature cds = (Feature) cdsFeature;
// for genemark it appears frame of 2 =1 and frame of 1 = 2
// doesn't matter when you string cds regions together as one block
// but does make a difference when you try to make a protein sequence for each CDS region where
// you give up or borrow based on the frame value
// compared with gff like files and docs for geneid and glimmer where geneid and glimmer both do it the same
// way that appears to match the gff3 docs.
int frame = cds.frame();
if (frame == 1) {
frame = 2;
} else if (frame == 2) {
frame = 1;
} else {
frame = 0;
}
String cdsName = cds.getAttribute("transcript_name");
if (cdsName == null || cdsName.length() == 0) {
cdsName = transcriptid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
}
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), frame);
}
}
}
}
static public LinkedHashMap<String, ProteinSequence> getProteinSequences(Collection<ChromosomeSequence> chromosomeSequences) throws Exception {
LinkedHashMap<String, ProteinSequence> proteinSequenceHashMap = new LinkedHashMap<String, ProteinSequence>();
for (ChromosomeSequence dnaSequence : chromosomeSequences) {
for (GeneSequence geneSequence : dnaSequence.getGeneSequences().values()) {
for (TranscriptSequence transcriptSequence : geneSequence.getTranscripts().values()) {
DNASequence dnaCodingSequence = transcriptSequence.getDNACodingSequence();
System.out.println("CDS=" + dnaCodingSequence.getSequenceAsString());
try {
ProteinSequence proteinSequence = transcriptSequence.getProteinSequence();
System.out.println(proteinSequence.getAccession().getID() + " " + proteinSequence);
if (proteinSequenceHashMap.containsKey(proteinSequence.getAccession().getID())) {
throw new Exception("Duplicate protein sequence id=" + proteinSequence.getAccession().getID() + " found at Gene id=" + geneSequence.getAccession().getID());
} else {
proteinSequenceHashMap.put(proteinSequence.getAccession().getID(), proteinSequence);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return proteinSequenceHashMap;
}
static public LinkedHashMap<String, GeneSequence> getGeneSequences(Collection<ChromosomeSequence> chromosomeSequences) throws Exception {
LinkedHashMap<String, GeneSequence> geneSequenceHashMap = new LinkedHashMap<String, GeneSequence>();
for (ChromosomeSequence chromosomeSequence : chromosomeSequences) {
for (GeneSequence geneSequence : chromosomeSequence.getGeneSequences().values()) {
geneSequenceHashMap.put(geneSequence.getAccession().getID(), geneSequence);
}
}
return geneSequenceHashMap;
}
public static void main(String args[]) throws Exception {
if (false) {
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.loadFastaAddGeneFeaturesFromGeneMarkGTF(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/genemark_hmm.gtf"));
LinkedHashMap<String, ProteinSequence> proteinSequenceList = GeneFeatureHelper.getProteinSequences(chromosomeSequenceList.values());
}
if (false) {
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.loadFastaAddGeneFeaturesFromGlimmerGFF3(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), new File("/Users/Scooter/scripps/dyadic/GlimmerHMM/c1_glimmerhmm.gff"));
LinkedHashMap<String, ProteinSequence> proteinSequenceList = GeneFeatureHelper.getProteinSequences(chromosomeSequenceList.values());
// for (ProteinSequence proteinSequence : proteinSequenceList.values()) {
// System.out.println(proteinSequence.getAccession().getID() + " " + proteinSequence);
// }
FastaWriterHelper.writeProteinSequence(new File("/Users/Scooter/scripps/dyadic/GlimmerHMM/c1_predicted_glimmer.faa"), proteinSequenceList.values());
}
if (false) {
GeneFeatureHelper.outputFastaSequenceLengthGFF3(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/c1scaffolds.gff3"));
}
try {
if (true) {
LinkedHashMap<String, ChromosomeSequence> dnaSequenceHashMap = GeneFeatureHelper.loadFastaAddGeneFeaturesFromGlimmerGFF3(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds-16.fna"), new File("/Users/Scooter/scripps/dyadic/GlimmerHMM/c1_glimmerhmm-16.gff"));
LinkedHashMap<String, GeneSequence> geneSequenceHashMap = GeneFeatureHelper.getGeneSequences(dnaSequenceHashMap.values());
Collection<GeneSequence> geneSequences = geneSequenceHashMap.values();
FastaWriterHelper.writeGeneSequence(new File("/Users/Scooter/scripps/dyadic/outputGlimmer6/c1_glimmer_genes.fna"), geneSequences, true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| biojava3-genome/src/main/java/org/biojava3/genome/GeneFeatureHelper.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.biojava3.genome;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.logging.Logger;
import org.biojava3.core.sequence.AccessionID;
import org.biojava3.core.sequence.CDSSequence;
import org.biojava3.core.sequence.ChromosomeSequence;
import org.biojava3.core.sequence.DNASequence;
import org.biojava3.core.sequence.ExonSequence;
import org.biojava3.core.sequence.io.FastaReaderHelper;
import org.biojava3.core.sequence.io.FastaWriterHelper;
import org.biojava3.core.sequence.GeneSequence;
import org.biojava3.core.sequence.ProteinSequence;
import org.biojava3.core.sequence.Strand;
import org.biojava3.core.sequence.TranscriptSequence;
import org.biojava3.genome.parsers.gff.Feature;
import org.biojava3.genome.parsers.gff.FeatureI;
import org.biojava3.genome.parsers.gff.FeatureList;
import org.biojava3.genome.parsers.gff.GFF3Reader;
import org.biojava3.genome.parsers.gff.GeneIDGFF2Reader;
import org.biojava3.genome.parsers.gff.GeneMarkGTFReader;
/**
*
* @author Scooter Willis <willishf at gmail dot com>
*/
public class GeneFeatureHelper {
private static final Logger log = Logger.getLogger(GeneFeatureHelper.class.getName());
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromUpperCaseExonFastaFile(File fastaSequenceFile,File uppercaseFastaFile, boolean throwExceptionGeneNotFound) throws Exception{
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = new LinkedHashMap<String, ChromosomeSequence>();
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
for(String accession : dnaSequenceList.keySet()){
DNASequence contigSequence = dnaSequenceList.get(accession);
ChromosomeSequence chromsomeSequence = new ChromosomeSequence(contigSequence.getSequenceAsString());
chromsomeSequence.setAccession(contigSequence.getAccession());
chromosomeSequenceList.put(accession, chromsomeSequence);
}
LinkedHashMap<String, DNASequence> geneSequenceList = FastaReaderHelper.readFastaDNASequence(uppercaseFastaFile);
for(DNASequence dnaSequence : geneSequenceList.values()){
String geneSequence = dnaSequence.getSequenceAsString();
String lcGeneSequence = geneSequence.toLowerCase();
String reverseGeneSequence = dnaSequence.getReverse().getSequenceAsString();
String lcReverseGeneSequence = reverseGeneSequence.toLowerCase();
Integer bioStart = null;
Integer bioEnd = null;
Strand strand = Strand.POSITIVE;
boolean geneFound = false;
String accession = "";
for(String id : dnaSequenceList.keySet()){
accession = id;
DNASequence contigDNASequence = dnaSequenceList.get(id);
String contigSequence = contigDNASequence.getSequenceAsString().toLowerCase();
bioStart = contigSequence.indexOf(lcGeneSequence);
if(bioStart != -1){
bioStart = bioStart + 1;
bioEnd = bioStart + geneSequence.length() - 1;
geneFound = true;
break;
}else{
bioStart = contigSequence.indexOf(lcReverseGeneSequence);
if(bioStart != -1){
bioStart = bioStart + 1;
bioEnd = bioStart - geneSequence.length() - 1;
strand = Strand.NEGATIVE;
geneFound = true;
break;
}
}
}
if(geneFound){
System.out.println("Gene found at " + bioStart + " " + bioEnd);
ChromosomeSequence chromosomeSequence = chromosomeSequenceList.get(accession);
ArrayList<Integer> exonBoundries = new ArrayList<Integer>();
//look for transitions from lowercase to upper case
for(int i = 0; i < geneSequence.length(); i++){
if(i == 0 && Character.isUpperCase(geneSequence.charAt(i))){
exonBoundries.add(i);
}else if(i == geneSequence.length() - 1) {
exonBoundries.add(i);
}else if(Character.isUpperCase(geneSequence.charAt(i)) && Character.isLowerCase(geneSequence.charAt(i - 1))){
exonBoundries.add(i);
}else if(Character.isUpperCase(geneSequence.charAt(i)) && Character.isLowerCase(geneSequence.charAt(i + 1))){
exonBoundries.add(i);
}
}
if(strand == Strand.NEGATIVE){
Collections.reverse(exonBoundries);
}
GeneSequence geneSeq = chromosomeSequence.addGene(dnaSequence.getAccession(), bioStart, bioEnd, strand);
geneSeq.setSource(uppercaseFastaFile.getName());
String transcriptName = dnaSequence.getAccession().getID() + "-transcript";
TranscriptSequence transcriptSequence = geneSeq.addTranscript(new AccessionID(transcriptName), bioStart, bioEnd);
int runningFrameLength = 0;
for(int i = 0; i < exonBoundries.size() - 1; i = i + 2){
int cdsBioStart = exonBoundries.get(i) + bioStart;
int cdsBioEnd = exonBoundries.get(i + 1) + bioStart;
runningFrameLength = runningFrameLength + Math.abs(cdsBioEnd - cdsBioStart) + 1;
String cdsName = transcriptName + "-cds-" + cdsBioStart + "-" + cdsBioEnd;
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSeq.addExon(cdsAccessionID, cdsBioStart, cdsBioEnd);
int remainder = runningFrameLength % 3;
int frame = 0;
if(remainder == 1){
frame = 2; // borrow 2 from next CDS region
}else if(remainder == 2){
frame = 1;
}
CDSSequence cdsSequence = transcriptSequence.addCDS(cdsAccessionID, cdsBioStart, cdsBioEnd, frame);
}
}else{
if(throwExceptionGeneNotFound){
throw new Exception(dnaSequence.getAccession().toString() + " not found");
}
}
}
return chromosomeSequenceList;
}
/**
* Output a gff3 feature file that will give the length of each scaffold/chromosome in the fasta file.
* Used for gbrowse so it knows length.
* @param fastaSequenceFile
* @param gffFile
* @throws Exception
*/
static public void outputFastaSequenceLengthGFF3(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
String fileName = fastaSequenceFile.getName();
FileWriter fw = new FileWriter(gffFile);
fw.write("##gff-version 3\n");
for (DNASequence dnaSequence : dnaSequenceList.values()) {
String gff3line = dnaSequence.getAccession().getID() + "\t" + fileName + "\t" + "contig" + "\t" + "1" + "\t" + dnaSequence.getBioEnd() + "\t.\t.\t.\tName=" + dnaSequence.getAccession().getID() + "\n";
fw.write(gff3line);
}
fw.close();
}
/**
* Loads Fasta file and GFF2 feature file generated from the geneid prediction algorithm
*
* @param fastaSequenceFile
* @param gffFile
* @return
* @throws Exception
*/
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromGeneIDGFF2(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.getChromosomeSequenceFromDNASequence(dnaSequenceList);
FeatureList listGenes = GeneIDGFF2Reader.read(gffFile.getAbsolutePath());
addGeneIDGFF2GeneFeatures(chromosomeSequenceList, listGenes);
return chromosomeSequenceList;
}
/**
* Load GFF2 feature file generated from the geneid prediction algorithm and map features onto the chromosome sequences
*
* @param chromosomeSequenceList
* @param listGenes
* @throws Exception
*/
static public void addGeneIDGFF2GeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
Collection<String> geneIds = listGenes.attributeValues("gene_id");
for (String geneid : geneIds) {
FeatureList gene = listGenes.selectByAttribute("gene_id", geneid);
FeatureI geneFeature = gene.get(0);
ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
geneid = geneid.replaceAll("_", ".G");
AccessionID geneAccessionID = new AccessionID(geneid);
GeneSequence geneSequence = null;
Collection<String> transcriptids = gene.attributeValues("gene_id");
for (String transcriptid : transcriptids) {
// get all the individual features (exons, CDS regions, etc.) of this gene
FeatureList transcriptFeature = listGenes.selectByAttribute("gene_id", transcriptid);
transcriptid = transcriptid.replaceAll("_", ".G");
// String seqName = feature.seqname();
FeatureI startCodon = null;
FeatureI stopCodon = null;
Integer startCodonBegin = null;
Integer stopCodonEnd = null;
String startCodonName = "";
String stopCodonName = "";
// now select only the coding regions of this gene
FeatureList firstFeatures = transcriptFeature.selectByType("First");
FeatureList terminalFeatures = transcriptFeature.selectByType("Terminal");
FeatureList internalFeatures = transcriptFeature.selectByType("Internal");
FeatureList singleFeatures = transcriptFeature.selectByType("Single");
FeatureList cdsFeatures = new FeatureList();
cdsFeatures.add(firstFeatures);
cdsFeatures.add(terminalFeatures);
cdsFeatures.add(internalFeatures);
cdsFeatures.add(singleFeatures);
// sort them
cdsFeatures = cdsFeatures.sortByStart();
Strand strand = Strand.POSITIVE;
FeatureI feature = cdsFeatures.get(0);
if (feature.location().isNegative()) {
strand = strand.NEGATIVE;
}
if (startCodonBegin == null) {
FeatureI firstFeature = cdsFeatures.get(0);
if (strand == strand.NEGATIVE) {
startCodonBegin = firstFeature.location().bioEnd();
} else {
startCodonBegin = firstFeature.location().bioStart();
}
}
if (stopCodonEnd == null) {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
if (strand == strand.NEGATIVE) {
stopCodonEnd = lastFeature.location().bioStart();
} else {
stopCodonEnd = lastFeature.location().bioEnd();
}
}
//for gtf ordering can be strand based so first is last and last is first
if (startCodonBegin > stopCodonEnd) {
int temp = startCodonBegin;
startCodonBegin = stopCodonEnd;
stopCodonEnd = temp;
}
AccessionID transcriptAccessionID = new AccessionID(transcriptid);
if (geneSequence == null) {
geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
geneSequence.setSource(((Feature) feature).source());
} else {
//if multiple transcripts for one gene make sure the gene is defined as the min and max start/end
if (startCodonBegin < geneSequence.getBioBegin()) {
geneSequence.setBioBegin(startCodonBegin);
}
if (stopCodonEnd > geneSequence.getBioBegin()) {
geneSequence.setBioEnd(stopCodonEnd);
}
}
TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
if (startCodon != null) {
if (startCodonName == null || startCodonName.length() == 0) {
startCodonName = transcriptid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
}
transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
}
if (stopCodon != null) {
if (stopCodonName == null || stopCodonName.length() == 0) {
stopCodonName = transcriptid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
}
transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
}
for (FeatureI cdsFeature : cdsFeatures) {
Feature cds = (Feature) cdsFeature;
String cdsName = cds.getAttribute("transcript_name");
if (cdsName == null || cdsName.length() == 0) {
cdsName = transcriptid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
}
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
CDSSequence cdsSequence = transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());
cdsSequence.setSequenceScore(cds.score());
}
}
}
}
static public LinkedHashMap<String, ChromosomeSequence> getChromosomeSequenceFromDNASequence(LinkedHashMap<String, DNASequence> dnaSequenceList) {
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = new LinkedHashMap<String, ChromosomeSequence>();
for (String key : dnaSequenceList.keySet()) {
DNASequence dnaSequence = dnaSequenceList.get(key);
ChromosomeSequence chromosomeSequence = new ChromosomeSequence(dnaSequence.getSequenceAsString());
chromosomeSequence.setAccession(dnaSequence.getAccession());
chromosomeSequenceList.put(key, chromosomeSequence);
}
return chromosomeSequenceList;
}
/**
* Lots of variations in the ontology or descriptors that can be used in GFF3 which requires writing a custom parser to handle a GFF3 generated or used
* by a specific application. Probably could be abstracted out but for now easier to handle with custom code to deal with gff3 elements that are not
* included but can be extracted from other data elements.
* @param fastaSequenceFile
* @param gffFile
* @return
* @throws Exception
*/
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromGmodGFF3(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.getChromosomeSequenceFromDNASequence(dnaSequenceList);
FeatureList listGenes = GFF3Reader.read(gffFile.getAbsolutePath());
addGmodGFF3GeneFeatures(chromosomeSequenceList, listGenes);
return chromosomeSequenceList;
}
static public void addGmodGFF3GeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
FeatureList mRNAFeatures = listGenes.selectByType("mRNA");
for (FeatureI f : mRNAFeatures) {
Feature mRNAFeature = (Feature) f;
String geneid = mRNAFeature.getAttribute("ID");
String source = mRNAFeature.source();
FeatureList gene = listGenes.selectByAttribute("Parent", geneid);
FeatureI geneFeature = gene.get(0);
ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
AccessionID geneAccessionID = new AccessionID(geneid);
GeneSequence geneSequence = null;
FeatureList cdsFeatures = gene.selectByType("CDS");
FeatureI feature = cdsFeatures.get(0);
Strand strand = Strand.POSITIVE;
if (feature.location().isNegative()) {
strand = strand.NEGATIVE;
}
cdsFeatures = cdsFeatures.sortByStart();
String seqName = feature.seqname();
FeatureI startCodon = null;
FeatureI stopCodon = null;
Integer startCodonBegin = null;
Integer stopCodonEnd = null;
String startCodonName = "";
String stopCodonName = "";
FeatureList startCodonList = gene.selectByType("five_prime_UTR");
if (startCodonList != null && startCodonList.size() > 0) {
startCodon = startCodonList.get(0);
if (strand == Strand.NEGATIVE) {
startCodonBegin = startCodon.location().bioEnd();
} else {
startCodonBegin = startCodon.location().bioStart();
}
startCodonName = startCodon.getAttribute("ID");
}
FeatureList stopCodonList = gene.selectByType("three_prime_UTR");
if (stopCodonList != null && stopCodonList.size() > 0) {
stopCodon = stopCodonList.get(0);
if (strand == Strand.NEGATIVE) {
stopCodonEnd = stopCodon.location().bioStart();
} else {
stopCodonEnd = stopCodon.location().bioEnd();
}
stopCodonName = stopCodon.getAttribute("ID");
}
if (startCodonBegin == null) {
if (strand == Strand.NEGATIVE) {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioEnd();
} else {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioStart();
}
}
if (stopCodonEnd == null) {
if (strand == Strand.NEGATIVE) {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioStart();
} else {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioEnd();
}
}
//for gtf ordering can be strand based so first is last and last is first
if (startCodonBegin > stopCodonEnd) {
int temp = startCodonBegin;
startCodonBegin = stopCodonEnd;
stopCodonEnd = temp;
}
AccessionID transcriptAccessionID = new AccessionID(geneid);
if (geneSequence == null) {
geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
geneSequence.setSource(source);
} else {
if (startCodonBegin < geneSequence.getBioBegin()) {
geneSequence.setBioBegin(startCodonBegin);
}
if (stopCodonEnd > geneSequence.getBioBegin()) {
geneSequence.setBioEnd(stopCodonEnd);
}
}
TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
if (startCodon != null) {
if (startCodonName == null || startCodonName.length() == 0) {
startCodonName = geneid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
}
transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
}
if (stopCodon != null) {
if (stopCodonName == null || stopCodonName.length() == 0) {
stopCodonName = geneid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
}
transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
}
for (FeatureI cdsFeature : cdsFeatures) {
Feature cds = (Feature) cdsFeature;
String cdsName = cds.getAttribute("ID");
if (cdsName == null || cdsName.length() == 0) {
cdsName = geneid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
}
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());
}
}
}
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromGlimmerGFF3(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.getChromosomeSequenceFromDNASequence(dnaSequenceList);
FeatureList listGenes = GFF3Reader.read(gffFile.getAbsolutePath());
addGlimmerGFF3GeneFeatures(chromosomeSequenceList, listGenes);
return chromosomeSequenceList;
}
static public void addGlimmerGFF3GeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
FeatureList mRNAFeatures = listGenes.selectByType("mRNA");
for (FeatureI f : mRNAFeatures) {
Feature mRNAFeature = (Feature) f;
String geneid = mRNAFeature.getAttribute("ID");
String source = mRNAFeature.source();
FeatureList gene = listGenes.selectByAttribute("Parent", geneid);
FeatureI geneFeature = gene.get(0);
ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
AccessionID geneAccessionID = new AccessionID(geneid);
GeneSequence geneSequence = null;
FeatureList cdsFeatures = gene.selectByType("CDS");
FeatureI feature = cdsFeatures.get(0);
Strand strand = Strand.POSITIVE;
if (feature.location().isNegative()) {
strand = strand.NEGATIVE;
}
cdsFeatures = cdsFeatures.sortByStart();
String seqName = feature.seqname();
FeatureI startCodon = null;
FeatureI stopCodon = null;
Integer startCodonBegin = null;
Integer stopCodonEnd = null;
String startCodonName = "";
String stopCodonName = "";
FeatureList startCodonList = gene.selectByAttribute("Note", "initial-exon");
if (startCodonList != null && startCodonList.size() > 0) {
startCodon = startCodonList.get(0);
if (strand == Strand.NEGATIVE) {
startCodonBegin = startCodon.location().bioEnd();
} else {
startCodonBegin = startCodon.location().bioStart();
}
startCodonName = startCodon.getAttribute("ID");
}
FeatureList stopCodonList = gene.selectByAttribute("Note", "final-exon");
if (stopCodonList != null && stopCodonList.size() > 0) {
stopCodon = stopCodonList.get(0);
if (strand == Strand.NEGATIVE) {
stopCodonEnd = stopCodon.location().bioStart();
} else {
stopCodonEnd = stopCodon.location().bioEnd();
}
stopCodonName = stopCodon.getAttribute("ID");
}
if (startCodonBegin == null) {
if (strand == Strand.NEGATIVE) {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioEnd();
} else {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioStart();
}
}
if (stopCodonEnd == null) {
if (strand == Strand.NEGATIVE) {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioStart();
} else {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioEnd();
}
}
//for gtf ordering can be strand based so first is last and last is first
if (startCodonBegin > stopCodonEnd) {
int temp = startCodonBegin;
startCodonBegin = stopCodonEnd;
stopCodonEnd = temp;
}
AccessionID transcriptAccessionID = new AccessionID(geneid);
if (geneSequence == null) {
geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
geneSequence.setSource(source);
} else {
if (startCodonBegin < geneSequence.getBioBegin()) {
geneSequence.setBioBegin(startCodonBegin);
}
if (stopCodonEnd > geneSequence.getBioBegin()) {
geneSequence.setBioEnd(stopCodonEnd);
}
}
TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
if (startCodon != null) {
if (startCodonName == null || startCodonName.length() == 0) {
startCodonName = geneid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
}
transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
}
if (stopCodon != null) {
if (stopCodonName == null || stopCodonName.length() == 0) {
stopCodonName = geneid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
}
transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
}
for (FeatureI cdsFeature : cdsFeatures) {
Feature cds = (Feature) cdsFeature;
String cdsName = cds.getAttribute("ID");
if (cdsName == null || cdsName.length() == 0) {
cdsName = geneid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
}
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), cds.frame());
}
}
}
static public LinkedHashMap<String, ChromosomeSequence> loadFastaAddGeneFeaturesFromGeneMarkGTF(File fastaSequenceFile, File gffFile) throws Exception {
LinkedHashMap<String, DNASequence> dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile);
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.getChromosomeSequenceFromDNASequence(dnaSequenceList);
FeatureList listGenes = GeneMarkGTFReader.read(gffFile.getAbsolutePath());
addGeneMarkGTFGeneFeatures(chromosomeSequenceList, listGenes);
return chromosomeSequenceList;
}
static public void addGeneMarkGTFGeneFeatures(LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList, FeatureList listGenes) throws Exception {
Collection<String> geneIds = listGenes.attributeValues("gene_id");
for (String geneid : geneIds) {
// if(geneid.equals("45_g")){
// int dummy =1;
// }
FeatureList gene = listGenes.selectByAttribute("gene_id", geneid);
FeatureI geneFeature = gene.get(0);
ChromosomeSequence seq = chromosomeSequenceList.get(geneFeature.seqname());
AccessionID geneAccessionID = new AccessionID(geneid);
GeneSequence geneSequence = null;
Collection<String> transcriptids = gene.attributeValues("transcript_id");
for (String transcriptid : transcriptids) {
// get all the individual features (exons, CDS regions, etc.) of this gene
FeatureList transcriptFeature = listGenes.selectByAttribute("transcript_id", transcriptid);
// now select only the coding regions of this gene
FeatureList cdsFeatures = transcriptFeature.selectByType("CDS");
// sort them
cdsFeatures = cdsFeatures.sortByStart();
FeatureI feature = cdsFeatures.get(0);
Strand strand = Strand.POSITIVE;
if (feature.location().isNegative()) {
strand = strand.NEGATIVE;
}
String seqName = feature.seqname();
FeatureI startCodon = null;
FeatureI stopCodon = null;
Integer startCodonBegin = null;
Integer stopCodonEnd = null;
String startCodonName = "";
String stopCodonName = "";
FeatureList startCodonList = transcriptFeature.selectByType("start_codon");
if (startCodonList != null && startCodonList.size() > 0) {
startCodon = startCodonList.get(0);
if (strand == Strand.POSITIVE) {
startCodonBegin = startCodon.location().bioStart();
} else {
startCodonBegin = startCodon.location().bioEnd();
}
startCodonName = startCodon.getAttribute("transcript_name");
}
FeatureList stopCodonList = transcriptFeature.selectByType("stop_codon");
if (stopCodonList != null && stopCodonList.size() > 0) {
stopCodon = stopCodonList.get(0);
if (strand == Strand.POSITIVE) {
stopCodonEnd = stopCodon.location().bioEnd();
} else {
stopCodonEnd = stopCodon.location().bioStart();
}
stopCodonName = stopCodon.getAttribute("transcript_name");
}
if (startCodonBegin == null) {
if (strand == Strand.NEGATIVE) {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioEnd();
} else {
FeatureI firstFeature = cdsFeatures.get(0);
startCodonBegin = firstFeature.location().bioStart();
}
}
if (stopCodonEnd == null) {
if (strand == Strand.NEGATIVE) {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioStart();
} else {
FeatureI lastFeature = cdsFeatures.get(cdsFeatures.size() - 1);
stopCodonEnd = lastFeature.location().bioEnd();
}
}
//for gtf ordering can be strand based so first is last and last is first
if (startCodonBegin > stopCodonEnd) {
int temp = startCodonBegin;
startCodonBegin = stopCodonEnd;
stopCodonEnd = temp;
}
AccessionID transcriptAccessionID = new AccessionID(transcriptid);
if (geneSequence == null) {
geneSequence = seq.addGene(geneAccessionID, startCodonBegin, stopCodonEnd, strand);
geneSequence.setSource(((Feature) feature).source());
} else {
//if multiple transcripts for one gene make sure the gene is defined as the min and max start/end
if (startCodonBegin < geneSequence.getBioBegin()) {
geneSequence.setBioBegin(startCodonBegin);
}
if (stopCodonEnd > geneSequence.getBioBegin()) {
geneSequence.setBioEnd(stopCodonEnd);
}
}
TranscriptSequence transcriptSequence = geneSequence.addTranscript(transcriptAccessionID, startCodonBegin, stopCodonEnd);
if (startCodon != null) {
if (startCodonName == null || startCodonName.length() == 0) {
startCodonName = transcriptid + "-start_codon-" + startCodon.location().bioStart() + "-" + startCodon.location().bioEnd();
}
transcriptSequence.addStartCodonSequence(new AccessionID(startCodonName), startCodon.location().bioStart(), startCodon.location().bioEnd());
}
if (stopCodon != null) {
if (stopCodonName == null || stopCodonName.length() == 0) {
stopCodonName = transcriptid + "-stop_codon-" + stopCodon.location().bioStart() + "-" + stopCodon.location().bioEnd();
}
transcriptSequence.addStopCodonSequence(new AccessionID(stopCodonName), stopCodon.location().bioStart(), stopCodon.location().bioEnd());
}
for (FeatureI cdsFeature : cdsFeatures) {
Feature cds = (Feature) cdsFeature;
// for genemark it appears frame of 2 =1 and frame of 1 = 2
// doesn't matter when you string cds regions together as one block
// but does make a difference when you try to make a protein sequence for each CDS region where
// you give up or borrow based on the frame value
// compared with gff like files and docs for geneid and glimmer where geneid and glimmer both do it the same
// way that appears to match the gff3 docs.
int frame = cds.frame();
if (frame == 1) {
frame = 2;
} else if (frame == 2) {
frame = 1;
} else {
frame = 0;
}
String cdsName = cds.getAttribute("transcript_name");
if (cdsName == null || cdsName.length() == 0) {
cdsName = transcriptid + "-cds-" + cds.location().bioStart() + "-" + cds.location().bioEnd();
}
AccessionID cdsAccessionID = new AccessionID(cdsName);
ExonSequence exonSequence = geneSequence.addExon(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd());
transcriptSequence.addCDS(cdsAccessionID, cdsFeature.location().bioStart(), cdsFeature.location().bioEnd(), frame);
}
}
}
}
static public LinkedHashMap<String, ProteinSequence> getProteinSequences(Collection<ChromosomeSequence> chromosomeSequences) throws Exception {
LinkedHashMap<String, ProteinSequence> proteinSequenceHashMap = new LinkedHashMap<String, ProteinSequence>();
for (ChromosomeSequence dnaSequence : chromosomeSequences) {
for (GeneSequence geneSequence : dnaSequence.getGeneSequences().values()) {
for (TranscriptSequence transcriptSequence : geneSequence.getTranscripts().values()) {
DNASequence dnaCodingSequence = transcriptSequence.getDNACodingSequence();
System.out.println("CDS=" + dnaCodingSequence.getSequenceAsString());
try {
ProteinSequence proteinSequence = transcriptSequence.getProteinSequence();
System.out.println(proteinSequence.getAccession().getID() + " " + proteinSequence);
if (proteinSequenceHashMap.containsKey(proteinSequence.getAccession().getID())) {
throw new Exception("Duplicate protein sequence id=" + proteinSequence.getAccession().getID() + " found at Gene id=" + geneSequence.getAccession().getID());
} else {
proteinSequenceHashMap.put(proteinSequence.getAccession().getID(), proteinSequence);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return proteinSequenceHashMap;
}
static public LinkedHashMap<String, GeneSequence> getGeneSequences(Collection<ChromosomeSequence> chromosomeSequences) throws Exception {
LinkedHashMap<String, GeneSequence> geneSequenceHashMap = new LinkedHashMap<String, GeneSequence>();
for (ChromosomeSequence chromosomeSequence : chromosomeSequences) {
for (GeneSequence geneSequence : chromosomeSequence.getGeneSequences().values()) {
geneSequenceHashMap.put(geneSequence.getAccession().getID(), geneSequence);
}
}
return geneSequenceHashMap;
}
public static void main(String args[]) throws Exception {
if (false) {
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.loadFastaAddGeneFeaturesFromGeneMarkGTF(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/genemark_hmm.gtf"));
LinkedHashMap<String, ProteinSequence> proteinSequenceList = GeneFeatureHelper.getProteinSequences(chromosomeSequenceList.values());
}
if (false) {
LinkedHashMap<String, ChromosomeSequence> chromosomeSequenceList = GeneFeatureHelper.loadFastaAddGeneFeaturesFromGlimmerGFF3(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), new File("/Users/Scooter/scripps/dyadic/GlimmerHMM/c1_glimmerhmm.gff"));
LinkedHashMap<String, ProteinSequence> proteinSequenceList = GeneFeatureHelper.getProteinSequences(chromosomeSequenceList.values());
// for (ProteinSequence proteinSequence : proteinSequenceList.values()) {
// System.out.println(proteinSequence.getAccession().getID() + " " + proteinSequence);
// }
FastaWriterHelper.writeProteinSequence(new File("/Users/Scooter/scripps/dyadic/GlimmerHMM/c1_predicted_glimmer.faa"), proteinSequenceList.values());
}
if (false) {
GeneFeatureHelper.outputFastaSequenceLengthGFF3(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/c1scaffolds.gff3"));
}
try {
if (true) {
LinkedHashMap<String, ChromosomeSequence> dnaSequenceHashMap = GeneFeatureHelper.loadFastaAddGeneFeaturesFromGlimmerGFF3(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds-16.fna"), new File("/Users/Scooter/scripps/dyadic/GlimmerHMM/c1_glimmerhmm-16.gff"));
LinkedHashMap<String, GeneSequence> geneSequenceHashMap = GeneFeatureHelper.getGeneSequences(dnaSequenceHashMap.values());
Collection<GeneSequence> geneSequences = geneSequenceHashMap.values();
FastaWriterHelper.writeGeneSequence(new File("/Users/Scooter/scripps/dyadic/outputGlimmer6/c1_glimmer_genes.fna"), geneSequences, true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Forcing check-in
git-svn-id: a754228c0d23e99fefe44e35d84d6184990ceaa2@8326 7c6358e6-4a41-0410-a743-a5b2a554c398
| biojava3-genome/src/main/java/org/biojava3/genome/GeneFeatureHelper.java | Forcing check-in | <ide><path>iojava3-genome/src/main/java/org/biojava3/genome/GeneFeatureHelper.java
<ide> for(DNASequence dnaSequence : geneSequenceList.values()){
<ide> String geneSequence = dnaSequence.getSequenceAsString();
<ide> String lcGeneSequence = geneSequence.toLowerCase();
<del> String reverseGeneSequence = dnaSequence.getReverse().getSequenceAsString();
<add> String reverseGeneSequence = dnaSequence.getReverseComplement().getSequenceAsString();
<ide> String lcReverseGeneSequence = reverseGeneSequence.toLowerCase();
<ide> Integer bioStart = null;
<ide> Integer bioEnd = null;
<ide> Strand strand = Strand.POSITIVE;
<ide> boolean geneFound = false;
<ide> String accession = "";
<add> DNASequence contigDNASequence = null;
<ide> for(String id : dnaSequenceList.keySet()){
<ide> accession = id;
<del> DNASequence contigDNASequence = dnaSequenceList.get(id);
<add> contigDNASequence = dnaSequenceList.get(id);
<ide> String contigSequence = contigDNASequence.getSequenceAsString().toLowerCase();
<ide> bioStart = contigSequence.indexOf(lcGeneSequence);
<ide> if(bioStart != -1){
<ide> }
<ide>
<ide> if(geneFound){
<del> System.out.println("Gene found at " + bioStart + " " + bioEnd);
<add> System.out.println("Gene " + dnaSequence.getAccession().toString() + " found at " + contigDNASequence.getAccession().toString() + " " + bioStart + " " + bioEnd + " " + strand);
<ide> ChromosomeSequence chromosomeSequence = chromosomeSequenceList.get(accession);
<ide>
<ide> ArrayList<Integer> exonBoundries = new ArrayList<Integer>();
<ide> if(throwExceptionGeneNotFound){
<ide> throw new Exception(dnaSequence.getAccession().toString() + " not found");
<ide> }
<add> System.out.println("Gene not found " + dnaSequence.getAccession().toString());
<ide> }
<ide>
<ide> } |
|
Java | mit | 5936b5b09e8aef0364972953e5d9d5a1610d07bf | 0 | PLOS/wombat,PLOS/wombat,PLOS/wombat,PLOS/wombat | package org.ambraproject.wombat.controller;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Ordering;
import com.google.gson.Gson;
import org.ambraproject.wombat.config.site.RequestMappingContextDictionary;
import org.ambraproject.wombat.config.site.Site;
import org.ambraproject.wombat.config.site.SiteParam;
import org.ambraproject.wombat.config.site.SiteSet;
import org.ambraproject.wombat.config.site.url.Link;
import org.ambraproject.wombat.model.ArticleComment;
import org.ambraproject.wombat.model.ArticleCommentFlag;
import org.ambraproject.wombat.model.ScholarlyWorkId;
import org.ambraproject.wombat.service.ApiAddress;
import org.ambraproject.wombat.service.ArticleService;
import org.ambraproject.wombat.service.ArticleTransformService;
import org.ambraproject.wombat.service.CaptchaService;
import org.ambraproject.wombat.service.CitationDownloadService;
import org.ambraproject.wombat.service.CommentService;
import org.ambraproject.wombat.service.CommentValidationService;
import org.ambraproject.wombat.service.EmailMessage;
import org.ambraproject.wombat.service.EntityNotFoundException;
import org.ambraproject.wombat.service.FreemarkerMailService;
import org.ambraproject.wombat.service.RenderContext;
import org.ambraproject.wombat.service.XmlService;
import org.ambraproject.wombat.service.remote.ArticleApi;
import org.ambraproject.wombat.service.remote.CachedRemoteService;
import org.ambraproject.wombat.service.remote.JsonService;
import org.ambraproject.wombat.service.remote.ServiceRequestException;
import org.ambraproject.wombat.service.remote.UserApi;
import org.ambraproject.wombat.util.CacheParams;
import org.ambraproject.wombat.util.DoiSchemeStripper;
import org.ambraproject.wombat.util.HttpMessageUtil;
import org.ambraproject.wombat.util.TextUtil;
import org.ambraproject.wombat.util.UriUtil;
import org.apache.commons.io.output.WriterOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.routines.EmailValidator;
import org.apache.commons.validator.routines.UrlValidator;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.SortedMap;
import java.util.stream.Collectors;
/**
* Controller for rendering an article.
*/
@Controller
public class ArticleController extends WombatController {
private static final Logger log = LoggerFactory.getLogger(ArticleController.class);
/**
* Initial size (in bytes) of buffer that holds transformed article HTML before passing it to the model.
*/
private static final int XFORM_BUFFER_SIZE = 0x8000;
private static final int MAX_TO_EMAILS = 5;
private static final String COMMENT_NAMESPACE = "comments";
@Autowired
private Charset charset;
@Autowired
private SiteSet siteSet;
@Autowired
private UserApi userApi;
@Autowired
private ArticleApi articleApi;
@Autowired
private ArticleService articleService;
@Autowired
private ArticleTransformService articleTransformService;
@Autowired
private CachedRemoteService<Reader> cachedRemoteReader;
@Autowired
private CitationDownloadService citationDownloadService;
@Autowired
private JsonService jsonService;
@Autowired
private CaptchaService captchaService;
@Autowired
private FreeMarkerConfig freeMarkerConfig;
@Autowired
private FreemarkerMailService freemarkerMailService;
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private CommentValidationService commentValidationService;
@Autowired
private XmlService xmlService;
@Autowired
private CommentService commentService;
@Autowired
private RequestMappingContextDictionary requestMappingContextDictionary;
// TODO: this method currently makes 5 backend RPCs, all sequentially. Explore reducing this
// number, or doing them in parallel, if this is a performance bottleneck.
@RequestMapping(name = "article", value = "/article")
public String renderArticle(HttpServletRequest request,
Model model,
@SiteParam Site site,
@RequestParam("id") String articleId,
@RequestParam("rev") int revision,
// TODO: Replace articleId with workId everywhere
ScholarlyWorkId workId)
throws IOException {
Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
// validateArticleVisibility(site, articleMetaData);
requireNonemptyParameter(articleId);
RenderContext renderContext = new RenderContext(site, new ScholarlyWorkId(articleId, OptionalInt.of(revision)));
String articleHtml = getArticleHtml(renderContext);
model.addAttribute("article", articleMetadata);
model.addAttribute("articleText", articleHtml);
model.addAttribute("amendments", fillAmendments(site, articleMetadata));
return site + "/ftl/article/article";
}
/**
* Serves a request for a list of all the root-level comments associated with an article.
*
* @param model data to pass to the view
* @param site current site
* @param articleId specifies the article
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleComments", value = "/article/comments")
public String renderArticleComments(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
try {
model.addAttribute("articleComments", commentService.getArticleComments(articleId));
} catch (UserApi.UserApiException e) {
log.error(e.getMessage(), e);
model.addAttribute("userApiError", e);
}
return site + "/ftl/article/comment/comments";
}
@RequestMapping(name = "articleCommentForm", value = "/article/comments/new")
public String renderNewCommentForm(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId)
throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
model.addAttribute("captchaHtml", captchaService.getCaptchaHtml(site, Optional.of("clean")));
return site + "/ftl/article/comment/newComment";
}
/**
* Types of related articles that get special display handling.
*/
private static enum AmendmentType {
CORRECTION("correction-forward"),
EOC("expressed-concern"),
RETRACTION("retraction");
/**
* A value of the "type" field of an object in an article's "relatedArticles" list.
*/
private final String relationshipType;
private AmendmentType(String relationshipType) {
this.relationshipType = relationshipType;
}
// For use as a key in maps destined for the FreeMarker model
private String getLabel() {
return name().toLowerCase();
}
private static final int COUNT = values().length;
private static final ImmutableMap<String, AmendmentType> BY_RELATIONSHIP_TYPE = Maps.uniqueIndex(
EnumSet.allOf(AmendmentType.class),
new Function<AmendmentType, String>() {
@Override
public String apply(AmendmentType input) {
return input.relationshipType;
}
}
);
}
private Map<String, Collection<Object>> getContainingArticleLists(String doi, Site site) throws IOException {
List<Map<?, ?>> articleListObjects = articleApi.requestObject(
ApiAddress.builder("articles").addToken(doi).addParameter("lists").build(),
List.class);
Multimap<String, Object> result = LinkedListMultimap.create(articleListObjects.size());
for (Map<?, ?> articleListObject : articleListObjects) {
String listType = Preconditions.checkNotNull((String) articleListObject.get("type"));
result.put(listType, articleListObject);
}
return result.asMap();
}
/**
* Iterate over article categories and extract and sort unique category terms (i.e., the final category term in a
* given category path)
*
* @param articleMetadata
* @return a sorted list of category terms
*/
private List<String> getCategoryTerms(Map<?, ?> articleMetadata) {
List<Map<String, ?>> categories = (List<Map<String, ?>>) articleMetadata.get("categories");
if (categories == null || categories.isEmpty()) {
return ImmutableList.of();
}
// create a map of terms/weights (effectively removes duplicate terms through the mapping)
Map<String, Double> termsMap = new HashMap<>();
for (Map<String, ?> category : categories) {
String[] categoryTerms = ((String) category.get("path")).split("/");
String categoryTerm = categoryTerms[categoryTerms.length - 1];
termsMap.put(categoryTerm, (Double) category.get("weight"));
}
// use Guava for sorting, first on weight (descending), then on category term
Comparator valueComparator = Ordering.natural().reverse().onResultOf(Functions.forMap(termsMap)).compound(Ordering.natural());
SortedMap<String, Double> sortedTermsMap = ImmutableSortedMap.copyOf(termsMap, valueComparator);
return new ArrayList<>(sortedTermsMap.keySet());
}
/**
* Check related articles for ones that amend this article. Set them up for special display, and retrieve additional
* data about those articles from the service tier.
*
* @param articleMetadata the article metadata
* @return a map from amendment type labels to related article objects
*/
private Map<String, List<Object>> fillAmendments(Site site, Map<?, ?> articleMetadata) throws IOException {
List<Map<String, ?>> relatedArticles = (List<Map<String, ?>>) articleMetadata.get("relatedArticles");
if (relatedArticles == null || relatedArticles.isEmpty()) {
return ImmutableMap.of();
}
ListMultimap<String, Object> amendments = LinkedListMultimap.create(AmendmentType.COUNT);
for (Map<String, ?> relatedArticle : relatedArticles) {
String relationshipType = (String) relatedArticle.get("type");
AmendmentType amendmentType = AmendmentType.BY_RELATIONSHIP_TYPE.get(relationshipType);
if (amendmentType != null) {
amendments.put(amendmentType.getLabel(), relatedArticle);
}
}
if (amendments.keySet().size() > 1) {
applyAmendmentPrecedence(amendments);
}
for (Object amendmentObj : amendments.values()) {
Map<String, Object> amendment = (Map<String, Object>) amendmentObj;
String amendmentId = (String) amendment.get("doi");
Map<String, ?> amendmentMetadata = (Map<String, ?>) requestArticleMetadata(amendmentId);
amendment.putAll(amendmentMetadata);
// Display the body only on non-correction amendments. Would be better if there were configurable per theme.
String amendmentType = (String) amendment.get("type");
if (!amendmentType.equals(AmendmentType.CORRECTION.relationshipType)) {
RenderContext renderContext = new RenderContext(site, new ScholarlyWorkId(amendmentId));
String body = getAmendmentBody(renderContext);
amendment.put("body", body);
}
}
return Multimaps.asMap(amendments);
}
/**
* Add links to cross-published journals to the model.
* <p>
* Each journal in which the article was published (according to the supplied article metadata) will be represented in
* the model, other than the journal belonging to the site being browsed. If that journal is the only one, nothing is
* added to the model. The journal of original publication (according to the article metadata's eISSN) is added under
* the named {@code "originalPub"}, and other journals are added as a collection named {@code "crossPub"}.
*
* @param request the contextual request (used to build cross-site links)
* @param model the page model into which to insert the link values
* @param site the site of the current page request
* @param articleMetadata metadata for an article being rendered
* @throws IOException
*/
private void addCrossPublishedJournals(HttpServletRequest request, Model model, Site site, Map<?, ?> articleMetadata)
throws IOException {
final Map<?, ?> publishedJournals = (Map<?, ?>) articleMetadata.get("journals");
final String eissn = (String) articleMetadata.get("eIssn");
Collection<Map<String, Object>> crossPublishedJournals;
Map<String, Object> originalJournal = null;
if (publishedJournals.size() <= 1) {
// The article was published in only one journal.
// Assume it is the one being browsed (validateArticleVisibility would have caught it otherwise).
crossPublishedJournals = ImmutableList.of();
} else {
crossPublishedJournals = Lists.newArrayListWithCapacity(publishedJournals.size() - 1);
String localJournal = site.getJournalKey();
for (Map.Entry<?, ?> journalEntry : publishedJournals.entrySet()) {
String journalKey = (String) journalEntry.getKey();
if (journalKey.equals(localJournal)) {
// This is the journal being browsed right now, so don't add a link
continue;
}
// Make a mutable copy to clobber
Map<String, Object> crossPublishedJournalMetadata = new HashMap<>((Map<? extends String, ?>) journalEntry.getValue());
// Find the site object (if possible) for the other journal
String crossPublishedJournalKey = (String) crossPublishedJournalMetadata.get("journalKey");
Site crossPublishedSite = site.getTheme().resolveForeignJournalKey(siteSet, crossPublishedJournalKey);
// Set up an href link to the other site's root page.
// Do not link to handlerName="homePage" because we don't know if the other site has disabled it.
String homepageLink = Link.toForeignSite(site, crossPublishedSite).toPath("").get(request);
crossPublishedJournalMetadata.put("href", homepageLink);
// Look up whether the other site wants its journal title italicized
// (This isn't a big deal because it's only one value, but if similar display details pile up
// in the future, it would be better to abstract them out than to handle them all individually here.)
boolean italicizeTitle = (boolean) crossPublishedSite.getTheme().getConfigMap("journal").get("italicizeTitle");
crossPublishedJournalMetadata.put("italicizeTitle", italicizeTitle);
if (eissn.equals(crossPublishedJournalMetadata.get("eIssn"))) {
originalJournal = crossPublishedJournalMetadata;
} else {
crossPublishedJournals.add(crossPublishedJournalMetadata);
}
}
}
model.addAttribute("crossPub", crossPublishedJournals);
model.addAttribute("originalPub", originalJournal);
}
/**
* Apply the display logic for different amendment types taking precedence over each other.
* <p>
* Retractions take precedence over all else (i.e., don't show them if there is a retraction) and EOCs take precedence
* over corrections. This logic could conceivably vary between sites (e.g., some journals might want to show all
* amendments side-by-side), so this is a good candidate for making it controllable through config. But for now,
* assume that the rules are always the same.
*
* @param amendments related article objects, keyed by {@link AmendmentType#getLabel()}.
*/
private static void applyAmendmentPrecedence(ListMultimap<String, Object> amendments) {
if (amendments.containsKey(AmendmentType.RETRACTION.getLabel())) {
amendments.removeAll(AmendmentType.EOC.getLabel());
amendments.removeAll(AmendmentType.CORRECTION.getLabel());
} else if (amendments.containsKey(AmendmentType.EOC.getLabel())) {
amendments.removeAll(AmendmentType.CORRECTION.getLabel());
}
}
/**
* Serves a request for an expanded view of a single comment and any replies.
*
* @param model data to pass to the view
* @param site current site
* @param commentId specifies the comment
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleCommentTree", value = "/article/comment")
public String renderArticleCommentTree(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String commentId) throws IOException {
requireNonemptyParameter(commentId);
Map<String, Object> comment;
try {
comment = commentService.getComment(commentId);
} catch (CommentService.CommentNotFoundException e) {
throw new NotFoundException(e);
} catch (UserApi.UserApiException e) {
log.error(e.getMessage(), e);
model.addAttribute("userApiError", e);
// Get a copy of the comment that is not populated with userApi data.
// This articleApi call is redundant to one that commentService.getComment would have made before throwing.
// TODO: Prevent extra articleApi call
comment = articleApi.requestObject(ApiAddress.builder("comments").addToken(commentId).build(), Map.class);
}
Map<?, ?> parentArticleStub = (Map<?, ?>) comment.get("parentArticle");
String articleId = (String) parentArticleStub.get("doi");
Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetadata);
model.addAttribute("comment", comment);
model.addAttribute("captchaHtml", captchaService.getCaptchaHtml(site, Optional.of("clean")));
return site + "/ftl/article/comment/comment";
}
private static HttpUriRequest createJsonPostRequest(URI target, Object body) {
String json = new Gson().toJson(body);
HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
RequestBuilder reqBuilder = RequestBuilder.create("POST").setUri(target).setEntity(entity);
return reqBuilder.build();
}
/**
* @param parentArticleDoi null if a reply to another comment
* @param parentCommentUri null if a direct reply to an article
*/
@RequestMapping(name = "postComment", method = RequestMethod.POST, value = "/article/comments/new")
@ResponseBody
public Object receiveNewComment(HttpServletRequest request,
@SiteParam Site site,
@RequestParam("commentTitle") String commentTitle,
@RequestParam("comment") String commentBody,
@RequestParam("isCompetingInterest") boolean hasCompetingInterest,
@RequestParam(value = "ciStatement", required = false) String ciStatement,
@RequestParam(value = "target", required = false) String parentArticleDoi,
@RequestParam(value = "inReplyTo", required = false) String parentCommentUri,
@RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
@RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
throws IOException {
Map<String, Object> validationErrors = commentValidationService.validateComment(site,
commentTitle, commentBody, hasCompetingInterest, ciStatement);
if (validationErrors.isEmpty()) {
// Submit Captcha for validation only if there are no other errors.
// Otherwise, the user's valid Captcha response would be wasted when they resubmit the comment.
if (!captchaService.validateCaptcha(site, request.getRemoteAddr(), captchaChallenge, captchaResponse)) {
validationErrors.put("captchaValidationFailure", true);
}
}
if (!validationErrors.isEmpty()) {
return ImmutableMap.of("validationErrors", validationErrors);
}
URI forwardedUrl = UriUtil.concatenate(articleApi.getServerUrl(), COMMENT_NAMESPACE);
String authId = request.getRemoteUser();
ArticleComment comment = new ArticleComment(parentArticleDoi, userApi.getUserIdFromAuthId(authId),
parentCommentUri, commentTitle, commentBody, ciStatement);
HttpUriRequest commentPostRequest = createJsonPostRequest(forwardedUrl, comment);
try (CloseableHttpResponse response = articleApi.getResponse(commentPostRequest)) {
String createdCommentUri = HttpMessageUtil.readResponse(response);
return ImmutableMap.of("createdCommentUri", createdCommentUri);
}
}
@RequestMapping(name = "postCommentFlag", method = RequestMethod.POST, value = "/article/comments/flag")
@ResponseBody
public Object receiveCommentFlag(HttpServletRequest request, @SiteParam Site site,
@RequestParam("reasonCode") String reasonCode,
@RequestParam("comment") String flagCommentBody,
@RequestParam("target") String targetComment)
throws IOException {
Map<String, Object> validationErrors = commentValidationService.validateFlag(flagCommentBody);
if (!validationErrors.isEmpty()) {
return ImmutableMap.of("validationErrors", validationErrors);
}
URI forwardedUrl = UriUtil.concatenate(articleApi.getServerUrl(),
String.format("%s/%s?flag", COMMENT_NAMESPACE, targetComment));
String authId = request.getRemoteUser();
ArticleCommentFlag flag = new ArticleCommentFlag(userApi.getUserIdFromAuthId(authId), flagCommentBody, reasonCode);
HttpUriRequest commentPostRequest = createJsonPostRequest(forwardedUrl, flag);
try (CloseableHttpResponse response = articleApi.getResponse(commentPostRequest)) {
return ImmutableMap.of(); // the "201 CREATED" status is all the AJAX client needs
}
}
/**
* Serves a request for the "about the authors" page for an article.
*
* @param model data to pass to the view
* @param site current site
* @param articleId specifies the article
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleAuthors", value = "/article/authors")
public String renderArticleAuthors(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
return site + "/ftl/article/authors";
}
/**
* Serves the article metrics tab content for an article.
*
* @param model data to pass to the view
* @param site current site
* @param articleId specifies the article
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleMetrics", value = "/article/metrics")
public String renderArticleMetrics(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
return site + "/ftl/article/metrics";
}
@RequestMapping(name = "citationDownloadPage", value = "/article/citation")
public String renderCitationDownloadPage(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId)
throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
return site + "/ftl/article/citationDownload";
}
@RequestMapping(name = "downloadRisCitation", value = "/article/citation/ris")
public ResponseEntity<String> serveRisCitationDownload(@SiteParam Site site, @RequestParam("id") String articleId)
throws IOException {
return serveCitationDownload(site, articleId, "ris", "application/x-research-info-systems",
citationDownloadService::buildRisCitation);
}
@RequestMapping(name = "downloadBibtexCitation", value = "/article/citation/bibtex")
public ResponseEntity<String> serveBibtexCitationDownload(@SiteParam Site site, @RequestParam("id") String articleId)
throws IOException {
return serveCitationDownload(site, articleId, "bib", "application/x-bibtex",
citationDownloadService::buildBibtexCitation);
}
private ResponseEntity<String> serveCitationDownload(Site site, String articleId,
String fileExtension, String contentType,
Function<Map<String, ?>, String> serviceFunction)
throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
validateArticleVisibility(site, articleMetadata);
String citationBody = serviceFunction.apply((Map<String, ?>) articleMetadata);
String contentDispositionValue = String.format("attachment; filename=\"%s.%s\"",
URLEncoder.encode(DoiSchemeStripper.strip((String) articleMetadata.get("doi")), Charsets.UTF_8.toString()),
fileExtension);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, contentType);
headers.add(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue);
return new ResponseEntity<>(citationBody, headers, HttpStatus.OK);
}
/**
* Serves the related content tab content for an article.
*
* @param model data to pass to the view
* @param site current site
* @param articleId specifies the article
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleRelatedContent", value = "/article/related")
public String renderArticleRelatedContent(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetadata);
String recaptchaPublicKey = site.getTheme().getConfigMap("captcha").get("publicKey").toString();
model.addAttribute("recaptchaPublicKey", recaptchaPublicKey);
return site + "/ftl/article/relatedContent";
}
/**
* Serves as a POST endpoint to submit media curation requests
*
* @param model data passed in from the view
* @param site current site
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "submitMediaCurationRequest", value = "/article/submitMediaCurationRequest", method = RequestMethod.POST)
public
@ResponseBody
String submitMediaCurationRequest(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("doi") String doi,
@RequestParam("link") String link,
@RequestParam("comment") String comment,
@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
@RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
throws IOException {
requireNonemptyParameter(doi);
if (!validateMediaCurationInput(model, link, name, email, captchaChallenge,
captchaResponse, site, request)) {
model.addAttribute("formError", "Invalid values have been submitted.");
//return model for error reporting
return jsonService.serialize(model);
}
String linkComment = name + ", " + email + "\n" + comment;
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("doi", doi.replaceFirst("info:doi/", "")));
params.add(new BasicNameValuePair("link", link));
params.add(new BasicNameValuePair("comment", linkComment));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
String mediaCurationUrl = site.getTheme().getConfigMap("mediaCuration").get("mediaCurationUrl").toString();
if (mediaCurationUrl != null) {
HttpPost httpPost = new HttpPost(mediaCurationUrl);
httpPost.setEntity(entity);
StatusLine statusLine = null;
try (CloseableHttpResponse response = cachedRemoteReader.getResponse(httpPost)) {
statusLine = response.getStatusLine();
} catch (ServiceRequestException e) {
//This exception is thrown when the submitted link is already present for the article.
if (e.getStatusCode() == HttpStatus.BAD_REQUEST.value()
&& e.getResponseBody().equals("The link already exists")) {
model.addAttribute("formError", "This link has already been submitted. Please submit a different link");
model.addAttribute("isValid", false);
} else {
throw new RuntimeException(e);
}
} finally {
httpPost.releaseConnection();
}
if (statusLine != null && statusLine.getStatusCode() != HttpStatus.CREATED.value()) {
throw new RuntimeException("bad response from media curation server: " + statusLine);
}
}
return jsonService.serialize(model);
}
/**
* Validate the input from the form
*
* @param model data passed in from the view
* @param link link pointing to media content relating to the article
* @param name name of the user submitting the media curation request
* @param email email of the user submitting the media curation request
* @param site current site
* @return true if everything is ok
*/
private boolean validateMediaCurationInput(Model model, String link, String name,
String email, String captchaChallenge, String captchaResponse, Site site,
HttpServletRequest request) throws IOException {
boolean isValid = true;
UrlValidator urlValidator = new UrlValidator();
if (StringUtils.isBlank(link)) {
model.addAttribute("linkError", "This field is required.");
isValid = false;
} else if (!urlValidator.isValid(link)) {
model.addAttribute("linkError", "Invalid Media link URL");
isValid = false;
}
if (StringUtils.isBlank(name)) {
model.addAttribute("nameError", "This field is required.");
isValid = false;
}
if (StringUtils.isBlank(email)) {
model.addAttribute("emailError", "This field is required.");
isValid = false;
} else if (!EmailValidator.getInstance().isValid(email)) {
model.addAttribute("emailError", "Invalid e-mail address");
isValid = false;
}
if (!captchaService.validateCaptcha(site, request.getRemoteAddr(), captchaChallenge, captchaResponse)) {
model.addAttribute("captchaError", "Verification is incorrect. Please try again.");
isValid = false;
}
model.addAttribute("isValid", isValid);
return isValid;
}
/*
* Returns a list of figures and tables of a given article; main usage is the figshare tile on the Metrics
* tab
*
* @param site current site
* @param articleId DOI identifying the article
* @return a list of figures and tables of a given article
* @throws IOException
*/
@RequestMapping(name = "articleFigsAndTables", value = "/article/assets/figsAndTables")
public ResponseEntity<List> listArticleFiguresAndTables(@SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
validateArticleVisibility(site, articleMetadata);
List<ImmutableMap<String, String>> articleFigsAndTables = articleService.getArticleFiguresAndTables(articleMetadata);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<>(articleFigsAndTables, headers, HttpStatus.OK);
}
@RequestMapping(name = "email", value = "/article/email")
public String renderEmailThisArticle(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetadata);
model.addAttribute("maxEmails", MAX_TO_EMAILS);
model.addAttribute("captchaHTML", captchaService.getCaptchaHtml(site, Optional.empty()));
return site + "/ftl/article/email";
}
/**
* @param model data passed in from the view
* @param site current site
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "emailPost", value = "/article/email", method = RequestMethod.POST)
public String emailArticle(HttpServletRequest request, HttpServletResponse response, Model model,
@SiteParam Site site,
@RequestParam("id") String articleId,
@RequestParam("articleUri") String articleUri,
@RequestParam("emailToAddresses") String emailToAddresses,
@RequestParam("emailFrom") String emailFrom,
@RequestParam("senderName") String senderName,
@RequestParam("note") String note,
@RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
@RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
throws IOException, MessagingException {
requireNonemptyParameter(articleId);
requireNonemptyParameter(articleUri);
model.addAttribute("emailToAddresses", emailToAddresses);
model.addAttribute("emailFrom", emailFrom);
model.addAttribute("senderName", senderName);
model.addAttribute("note", note);
model.addAttribute("articleUri", articleUri);
List<InternetAddress> toAddresses = Splitter.on(CharMatcher.anyOf("\n\r")).omitEmptyStrings()
.splitToList(emailToAddresses).stream()
.map(email -> EmailMessage.createAddress(null /*name*/, email))
.collect(Collectors.toList());
Set<String> errors = validateEmailArticleInput(toAddresses, emailFrom, senderName,
captchaChallenge, captchaResponse, site, request);
if (applyValidation(response, model, errors)) {
return renderEmailThisArticle(request, model, site, articleId);
}
Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
String title = articleMetadata.get("title").toString();
model.addAttribute("title", title);
model.addAttribute("description", articleMetadata.get("description"));
model.addAttribute("journalName", site.getJournalName());
Multipart content = freemarkerMailService.createContent(site, "emailThisArticle", model);
EmailMessage message = EmailMessage.builder()
.addToEmailAddresses(toAddresses)
.setSenderAddress(EmailMessage.createAddress(senderName, emailFrom))
.setSubject("An Article from " + site.getJournalName() + ": " + title)
.setContent(content)
.setEncoding(freeMarkerConfig.getConfiguration().getDefaultEncoding())
.build();
message.send(javaMailSender);
response.setStatus(HttpStatus.CREATED.value());
return site + "/ftl/article/emailSuccess";
}
private Set<String> validateEmailArticleInput(List<InternetAddress> emailToAddresses,
String emailFrom, String senderName, String captchaChallenge, String captchaResponse,
Site site, HttpServletRequest request) throws IOException {
Set<String> errors = new HashSet<>();
if (StringUtils.isBlank(emailFrom)) {
errors.add("emailFromMissing");
} else if (!EmailValidator.getInstance().isValid(emailFrom)) {
errors.add("emailFromInvalid");
}
if (emailToAddresses.isEmpty()) {
errors.add("emailToAddressesMissing");
} else if (emailToAddresses.size() > MAX_TO_EMAILS) {
errors.add("tooManyEmailToAddresses");
} else if (emailToAddresses.stream()
.noneMatch(email -> EmailValidator.getInstance().isValid(email.toString()))) {
errors.add("emailToAddressesInvalid");
}
if (StringUtils.isBlank(senderName)) {
errors.add("senderNameMissing");
}
if (!captchaService.validateCaptcha(site, request.getRemoteAddr(), captchaChallenge, captchaResponse)) {
errors.add("captchaError");
}
return errors;
}
/**
* Loads article metadata from the SOA layer.
*
* @param articleId DOI identifying the article
* @return Map of JSON representing the article
* @throws IOException
*/
private Map<?, ?> requestArticleMetadata(String articleId) throws IOException {
Map<?, ?> articleMetadata;
try {
articleMetadata = articleService.requestArticleMetadata(articleId, false);
} catch (EntityNotFoundException enfe) {
throw new ArticleNotFoundException(articleId);
}
return articleMetadata;
}
/**
* Appends additional info about article authors to the model.
*
* @param model model to be passed to the view
* @param doi identifies the article
* @return the list of authors appended to the model
* @throws IOException
*/
private void requestAuthors(Model model, String doi) throws IOException {
Map<?, ?> allAuthorsData = articleApi.requestObject(
ApiAddress.builder("articles").addToken(doi).addParameter("authors").build(),
Map.class);
List<?> authors = (List<?>) allAuthorsData.get("authors");
model.addAttribute("authors", authors);
// Putting this here was a judgement call. One could make the argument that this logic belongs
// in Rhino, but it's so simple I elected to keep it here for now.
List<String> equalContributors = new ArrayList<>();
ListMultimap<String, String> authorAffiliationsMap = LinkedListMultimap.create();
for (Object o : authors) {
Map<String, Object> author = (Map<String, Object>) o;
String fullName = (String) author.get("fullName");
List<String> affiliations = (List<String>) author.get("affiliations");
for (String affiliation : affiliations) {
authorAffiliationsMap.put(affiliation, fullName);
}
Object obj = author.get("equalContrib");
if (obj != null && (boolean) obj) {
equalContributors.add(fullName);
}
// remove the footnote marker from the current address
List<String> currentAddresses = (List<String>) author.get("currentAddresses");
for (ListIterator<String> iterator = currentAddresses.listIterator(); iterator.hasNext(); ) {
String currentAddress = iterator.next();
iterator.set(TextUtil.removeFootnoteMarker(currentAddress));
}
}
//Create comma-separated list of authors per affiliation
LinkedHashMap<String, String> authorListAffiliationMap = new LinkedHashMap<>();
for (Map.Entry<String, Collection<String>> affiliation : authorAffiliationsMap.asMap().entrySet()) {
authorListAffiliationMap.put(affiliation.getKey(), Joiner.on(", ").join(affiliation.getValue()));
}
model.addAttribute("authorListAffiliationMap", authorListAffiliationMap);
model.addAttribute("authorContributions", allAuthorsData.get("authorContributions"));
model.addAttribute("competingInterests", allAuthorsData.get("competingInterests"));
model.addAttribute("correspondingAuthors", allAuthorsData.get("correspondingAuthorList"));
model.addAttribute("equalContributors", equalContributors);
}
/**
* Build the path to request the article XML asset for an article.
*
* @return the service path to the correspond article XML asset file
*/
private static ApiAddress getArticleXmlAssetPath(RenderContext renderContext) {
ScholarlyWorkId id = renderContext.getArticleId().get();
OptionalInt revisionNumber = id.getRevisionNumber();
ApiAddress.Builder address = ApiAddress.builder("articles").addToken(id.getDoi()).addParameter("xml");
if (revisionNumber.isPresent()) {
address = address.addParameter("revision", revisionNumber.getAsInt());
}
return address.build();
}
/**
* Retrieve and transform the body of an amendment article from its XML file. The returned value is cached.
*
* @return the body of the amendment article, transformed into HTML for display in a notice on the amended article
*/
private String getAmendmentBody(final RenderContext renderContext) throws IOException {
String cacheKey = "amendmentBody:" + Preconditions.checkNotNull(renderContext.getArticleId());
ApiAddress xmlAssetPath = getArticleXmlAssetPath(renderContext);
return articleApi.requestCachedStream(CacheParams.create(cacheKey), xmlAssetPath, stream -> {
// Extract the "/article/body" element from the amendment XML, not to be confused with the HTML <body> element.
String bodyXml = xmlService.extractElement(stream, "body");
try {
return articleTransformService.transformExcerpt(renderContext, bodyXml, null);
} catch (TransformerException e) {
throw new RuntimeException(e);
}
});
}
/**
* Retrieves article XML from the SOA server, transforms it into HTML, and returns it. Result will be stored in
* memcache.
*
* @return String of the article HTML
* @throws IOException
*/
private String getArticleHtml(final RenderContext renderContext) throws IOException {
String cacheKey = String.format("html:%s:%s",
Preconditions.checkNotNull(renderContext.getSite()), renderContext.getArticleId());
ApiAddress xmlAssetPath = getArticleXmlAssetPath(renderContext);
return articleApi.requestCachedStream(CacheParams.create(cacheKey), xmlAssetPath, stream -> {
StringWriter articleHtml = new StringWriter(XFORM_BUFFER_SIZE);
try (OutputStream outputStream = new WriterOutputStream(articleHtml, charset)) {
articleTransformService.transform(renderContext, stream, outputStream);
} catch (TransformerException e) {
throw new RuntimeException(e);
}
return articleHtml.toString();
});
}
private Map<?, ?> addCommonModelAttributes(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException {
Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
addCrossPublishedJournals(request, model, site, articleMetadata);
model.addAttribute("article", articleMetadata);
model.addAttribute("containingLists", getContainingArticleLists(articleId, site));
model.addAttribute("categoryTerms", getCategoryTerms(articleMetadata));
requestAuthors(model, articleId);
return articleMetadata;
}
}
| src/main/java/org/ambraproject/wombat/controller/ArticleController.java | package org.ambraproject.wombat.controller;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Ordering;
import com.google.gson.Gson;
import org.ambraproject.wombat.config.site.RequestMappingContextDictionary;
import org.ambraproject.wombat.config.site.Site;
import org.ambraproject.wombat.config.site.SiteParam;
import org.ambraproject.wombat.config.site.SiteSet;
import org.ambraproject.wombat.config.site.url.Link;
import org.ambraproject.wombat.model.ArticleComment;
import org.ambraproject.wombat.model.ArticleCommentFlag;
import org.ambraproject.wombat.model.ScholarlyWorkId;
import org.ambraproject.wombat.service.ApiAddress;
import org.ambraproject.wombat.service.ArticleService;
import org.ambraproject.wombat.service.ArticleTransformService;
import org.ambraproject.wombat.service.CaptchaService;
import org.ambraproject.wombat.service.CitationDownloadService;
import org.ambraproject.wombat.service.CommentService;
import org.ambraproject.wombat.service.CommentValidationService;
import org.ambraproject.wombat.service.EmailMessage;
import org.ambraproject.wombat.service.EntityNotFoundException;
import org.ambraproject.wombat.service.FreemarkerMailService;
import org.ambraproject.wombat.service.RenderContext;
import org.ambraproject.wombat.service.XmlService;
import org.ambraproject.wombat.service.remote.CachedRemoteService;
import org.ambraproject.wombat.service.remote.JsonService;
import org.ambraproject.wombat.service.remote.ServiceRequestException;
import org.ambraproject.wombat.service.remote.ArticleApi;
import org.ambraproject.wombat.service.remote.UserApi;
import org.ambraproject.wombat.util.CacheParams;
import org.ambraproject.wombat.util.DoiSchemeStripper;
import org.ambraproject.wombat.util.HttpMessageUtil;
import org.ambraproject.wombat.util.TextUtil;
import org.ambraproject.wombat.util.UriUtil;
import org.apache.commons.io.output.WriterOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.routines.EmailValidator;
import org.apache.commons.validator.routines.UrlValidator;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.SortedMap;
import java.util.stream.Collectors;
/**
* Controller for rendering an article.
*/
@Controller
public class ArticleController extends WombatController {
private static final Logger log = LoggerFactory.getLogger(ArticleController.class);
/**
* Initial size (in bytes) of buffer that holds transformed article HTML before passing it to the model.
*/
private static final int XFORM_BUFFER_SIZE = 0x8000;
private static final int MAX_TO_EMAILS = 5;
private static final String COMMENT_NAMESPACE = "comments";
@Autowired
private Charset charset;
@Autowired
private SiteSet siteSet;
@Autowired
private UserApi userApi;
@Autowired
private ArticleApi articleApi;
@Autowired
private ArticleService articleService;
@Autowired
private ArticleTransformService articleTransformService;
@Autowired
private CachedRemoteService<Reader> cachedRemoteReader;
@Autowired
private CitationDownloadService citationDownloadService;
@Autowired
private JsonService jsonService;
@Autowired
private CaptchaService captchaService;
@Autowired
private FreeMarkerConfig freeMarkerConfig;
@Autowired
private FreemarkerMailService freemarkerMailService;
@Autowired
private JavaMailSender javaMailSender;
@Autowired
private CommentValidationService commentValidationService;
@Autowired
private XmlService xmlService;
@Autowired
private CommentService commentService;
@Autowired
private RequestMappingContextDictionary requestMappingContextDictionary;
// TODO: this method currently makes 5 backend RPCs, all sequentially. Explore reducing this
// number, or doing them in parallel, if this is a performance bottleneck.
@RequestMapping(name = "article", value = "/article")
public String renderArticle(HttpServletRequest request,
Model model,
@SiteParam Site site,
@RequestParam("id") String articleId,
@RequestParam("rev") int revision,
// TODO: Replace articleId with workId everywhere
ScholarlyWorkId workId)
throws IOException {
Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
// validateArticleVisibility(site, articleMetaData);
requireNonemptyParameter(articleId);
RenderContext renderContext = new RenderContext(site, new ScholarlyWorkId(articleId, OptionalInt.of(revision)));
String articleHtml = getArticleHtml(renderContext);
model.addAttribute("article", articleMetadata);
model.addAttribute("articleText", articleHtml);
model.addAttribute("amendments", fillAmendments(site, articleMetadata));
return site + "/ftl/article/article";
}
/**
* Serves a request for a list of all the root-level comments associated with an article.
*
* @param model data to pass to the view
* @param site current site
* @param articleId specifies the article
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleComments", value = "/article/comments")
public String renderArticleComments(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
try {
model.addAttribute("articleComments", commentService.getArticleComments(articleId));
} catch (UserApi.UserApiException e) {
log.error(e.getMessage(), e);
model.addAttribute("userApiError", e);
}
return site + "/ftl/article/comment/comments";
}
@RequestMapping(name = "articleCommentForm", value = "/article/comments/new")
public String renderNewCommentForm(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId)
throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
model.addAttribute("captchaHtml", captchaService.getCaptchaHtml(site, Optional.of("clean")));
return site + "/ftl/article/comment/newComment";
}
/**
* Types of related articles that get special display handling.
*/
private static enum AmendmentType {
CORRECTION("correction-forward"),
EOC("expressed-concern"),
RETRACTION("retraction");
/**
* A value of the "type" field of an object in an article's "relatedArticles" list.
*/
private final String relationshipType;
private AmendmentType(String relationshipType) {
this.relationshipType = relationshipType;
}
// For use as a key in maps destined for the FreeMarker model
private String getLabel() {
return name().toLowerCase();
}
private static final int COUNT = values().length;
private static final ImmutableMap<String, AmendmentType> BY_RELATIONSHIP_TYPE = Maps.uniqueIndex(
EnumSet.allOf(AmendmentType.class),
new Function<AmendmentType, String>() {
@Override
public String apply(AmendmentType input) {
return input.relationshipType;
}
}
);
}
private Map<String, Collection<Object>> getContainingArticleLists(String doi, Site site) throws IOException {
List<Map<?, ?>> articleListObjects = articleApi.requestObject(
ApiAddress.builder("articles").addToken(doi).addParameter("lists").build(),
List.class);
Multimap<String, Object> result = LinkedListMultimap.create(articleListObjects.size());
for (Map<?, ?> articleListObject : articleListObjects) {
String listType = Preconditions.checkNotNull((String) articleListObject.get("type"));
result.put(listType, articleListObject);
}
return result.asMap();
}
/**
* Iterate over article categories and extract and sort unique category terms (i.e., the final category term in a
* given category path)
*
* @param articleMetadata
* @return a sorted list of category terms
*/
private List<String> getCategoryTerms(Map<?, ?> articleMetadata) {
List<Map<String, ?>> categories = (List<Map<String, ?>>) articleMetadata.get("categories");
if (categories == null || categories.isEmpty()) {
return ImmutableList.of();
}
// create a map of terms/weights (effectively removes duplicate terms through the mapping)
Map<String, Double> termsMap = new HashMap<>();
for (Map<String, ?> category : categories) {
String[] categoryTerms = ((String) category.get("path")).split("/");
String categoryTerm = categoryTerms[categoryTerms.length - 1];
termsMap.put(categoryTerm, (Double) category.get("weight"));
}
// use Guava for sorting, first on weight (descending), then on category term
Comparator valueComparator = Ordering.natural().reverse().onResultOf(Functions.forMap(termsMap)).compound(Ordering.natural());
SortedMap<String, Double> sortedTermsMap = ImmutableSortedMap.copyOf(termsMap, valueComparator);
return new ArrayList<>(sortedTermsMap.keySet());
}
/**
* Check related articles for ones that amend this article. Set them up for special display, and retrieve additional
* data about those articles from the service tier.
*
* @param articleMetadata the article metadata
* @return a map from amendment type labels to related article objects
*/
private Map<String, List<Object>> fillAmendments(Site site, Map<?, ?> articleMetadata) throws IOException {
List<Map<String, ?>> relatedArticles = (List<Map<String, ?>>) articleMetadata.get("relatedArticles");
if (relatedArticles == null || relatedArticles.isEmpty()) {
return ImmutableMap.of();
}
ListMultimap<String, Object> amendments = LinkedListMultimap.create(AmendmentType.COUNT);
for (Map<String, ?> relatedArticle : relatedArticles) {
String relationshipType = (String) relatedArticle.get("type");
AmendmentType amendmentType = AmendmentType.BY_RELATIONSHIP_TYPE.get(relationshipType);
if (amendmentType != null) {
amendments.put(amendmentType.getLabel(), relatedArticle);
}
}
if (amendments.keySet().size() > 1) {
applyAmendmentPrecedence(amendments);
}
for (Object amendmentObj : amendments.values()) {
Map<String, Object> amendment = (Map<String, Object>) amendmentObj;
String amendmentId = (String) amendment.get("doi");
Map<String, ?> amendmentMetadata = (Map<String, ?>) requestArticleMetadata(amendmentId);
amendment.putAll(amendmentMetadata);
// Display the body only on non-correction amendments. Would be better if there were configurable per theme.
String amendmentType = (String) amendment.get("type");
if (!amendmentType.equals(AmendmentType.CORRECTION.relationshipType)) {
RenderContext renderContext = new RenderContext(site, new ScholarlyWorkId(amendmentId));
String body = getAmendmentBody(renderContext);
amendment.put("body", body);
}
}
return Multimaps.asMap(amendments);
}
/**
* Add links to cross-published journals to the model.
* <p>
* Each journal in which the article was published (according to the supplied article metadata) will be represented in
* the model, other than the journal belonging to the site being browsed. If that journal is the only one, nothing is
* added to the model. The journal of original publication (according to the article metadata's eISSN) is added under
* the named {@code "originalPub"}, and other journals are added as a collection named {@code "crossPub"}.
*
* @param request the contextual request (used to build cross-site links)
* @param model the page model into which to insert the link values
* @param site the site of the current page request
* @param articleMetadata metadata for an article being rendered
* @throws IOException
*/
private void addCrossPublishedJournals(HttpServletRequest request, Model model, Site site, Map<?, ?> articleMetadata)
throws IOException {
final Map<?, ?> publishedJournals = (Map<?, ?>) articleMetadata.get("journals");
final String eissn = (String) articleMetadata.get("eIssn");
Collection<Map<String, Object>> crossPublishedJournals;
Map<String, Object> originalJournal = null;
if (publishedJournals.size() <= 1) {
// The article was published in only one journal.
// Assume it is the one being browsed (validateArticleVisibility would have caught it otherwise).
crossPublishedJournals = ImmutableList.of();
} else {
crossPublishedJournals = Lists.newArrayListWithCapacity(publishedJournals.size() - 1);
String localJournal = site.getJournalKey();
for (Map.Entry<?, ?> journalEntry : publishedJournals.entrySet()) {
String journalKey = (String) journalEntry.getKey();
if (journalKey.equals(localJournal)) {
// This is the journal being browsed right now, so don't add a link
continue;
}
// Make a mutable copy to clobber
Map<String, Object> crossPublishedJournalMetadata = new HashMap<>((Map<? extends String, ?>) journalEntry.getValue());
// Find the site object (if possible) for the other journal
String crossPublishedJournalKey = (String) crossPublishedJournalMetadata.get("journalKey");
Site crossPublishedSite = site.getTheme().resolveForeignJournalKey(siteSet, crossPublishedJournalKey);
// Set up an href link to the other site's root page.
// Do not link to handlerName="homePage" because we don't know if the other site has disabled it.
String homepageLink = Link.toForeignSite(site, crossPublishedSite).toPath("").get(request);
crossPublishedJournalMetadata.put("href", homepageLink);
// Look up whether the other site wants its journal title italicized
// (This isn't a big deal because it's only one value, but if similar display details pile up
// in the future, it would be better to abstract them out than to handle them all individually here.)
boolean italicizeTitle = (boolean) crossPublishedSite.getTheme().getConfigMap("journal").get("italicizeTitle");
crossPublishedJournalMetadata.put("italicizeTitle", italicizeTitle);
if (eissn.equals(crossPublishedJournalMetadata.get("eIssn"))) {
originalJournal = crossPublishedJournalMetadata;
} else {
crossPublishedJournals.add(crossPublishedJournalMetadata);
}
}
}
model.addAttribute("crossPub", crossPublishedJournals);
model.addAttribute("originalPub", originalJournal);
}
/**
* Apply the display logic for different amendment types taking precedence over each other.
* <p>
* Retractions take precedence over all else (i.e., don't show them if there is a retraction) and EOCs take precedence
* over corrections. This logic could conceivably vary between sites (e.g., some journals might want to show all
* amendments side-by-side), so this is a good candidate for making it controllable through config. But for now,
* assume that the rules are always the same.
*
* @param amendments related article objects, keyed by {@link AmendmentType#getLabel()}.
*/
private static void applyAmendmentPrecedence(ListMultimap<String, Object> amendments) {
if (amendments.containsKey(AmendmentType.RETRACTION.getLabel())) {
amendments.removeAll(AmendmentType.EOC.getLabel());
amendments.removeAll(AmendmentType.CORRECTION.getLabel());
} else if (amendments.containsKey(AmendmentType.EOC.getLabel())) {
amendments.removeAll(AmendmentType.CORRECTION.getLabel());
}
}
/**
* Serves a request for an expanded view of a single comment and any replies.
*
* @param model data to pass to the view
* @param site current site
* @param commentId specifies the comment
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleCommentTree", value = "/article/comment")
public String renderArticleCommentTree(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String commentId) throws IOException {
requireNonemptyParameter(commentId);
Map<String, Object> comment;
try {
comment = commentService.getComment(commentId);
} catch (CommentService.CommentNotFoundException e) {
throw new NotFoundException(e);
} catch (UserApi.UserApiException e) {
log.error(e.getMessage(), e);
model.addAttribute("userApiError", e);
// Get a copy of the comment that is not populated with userApi data.
// This articleApi call is redundant to one that commentService.getComment would have made before throwing.
// TODO: Prevent extra articleApi call
comment = articleApi.requestObject(ApiAddress.builder("comments").addToken(commentId).build(), Map.class);
}
Map<?, ?> parentArticleStub = (Map<?, ?>) comment.get("parentArticle");
String articleId = (String) parentArticleStub.get("doi");
Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetadata);
model.addAttribute("comment", comment);
model.addAttribute("captchaHtml", captchaService.getCaptchaHtml(site, Optional.of("clean")));
return site + "/ftl/article/comment/comment";
}
private static HttpUriRequest createJsonPostRequest(URI target, Object body) {
String json = new Gson().toJson(body);
HttpEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
RequestBuilder reqBuilder = RequestBuilder.create("POST").setUri(target).setEntity(entity);
return reqBuilder.build();
}
/**
* @param parentArticleDoi null if a reply to another comment
* @param parentCommentUri null if a direct reply to an article
*/
@RequestMapping(name = "postComment", method = RequestMethod.POST, value = "/article/comments/new")
@ResponseBody
public Object receiveNewComment(HttpServletRequest request,
@SiteParam Site site,
@RequestParam("commentTitle") String commentTitle,
@RequestParam("comment") String commentBody,
@RequestParam("isCompetingInterest") boolean hasCompetingInterest,
@RequestParam(value = "ciStatement", required = false) String ciStatement,
@RequestParam(value = "target", required = false) String parentArticleDoi,
@RequestParam(value = "inReplyTo", required = false) String parentCommentUri,
@RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
@RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
throws IOException {
Map<String, Object> validationErrors = commentValidationService.validateComment(site,
commentTitle, commentBody, hasCompetingInterest, ciStatement);
if (validationErrors.isEmpty()) {
// Submit Captcha for validation only if there are no other errors.
// Otherwise, the user's valid Captcha response would be wasted when they resubmit the comment.
if (!captchaService.validateCaptcha(site, request.getRemoteAddr(), captchaChallenge, captchaResponse)) {
validationErrors.put("captchaValidationFailure", true);
}
}
if (!validationErrors.isEmpty()) {
return ImmutableMap.of("validationErrors", validationErrors);
}
URI forwardedUrl = UriUtil.concatenate(articleApi.getServerUrl(), COMMENT_NAMESPACE);
String authId = request.getRemoteUser();
ArticleComment comment = new ArticleComment(parentArticleDoi, userApi.getUserIdFromAuthId(authId),
parentCommentUri, commentTitle, commentBody, ciStatement);
HttpUriRequest commentPostRequest = createJsonPostRequest(forwardedUrl, comment);
try (CloseableHttpResponse response = articleApi.getResponse(commentPostRequest)) {
String createdCommentUri = HttpMessageUtil.readResponse(response);
return ImmutableMap.of("createdCommentUri", createdCommentUri);
}
}
@RequestMapping(name = "postCommentFlag", method = RequestMethod.POST, value = "/article/comments/flag")
@ResponseBody
public Object receiveCommentFlag(HttpServletRequest request, @SiteParam Site site,
@RequestParam("reasonCode") String reasonCode,
@RequestParam("comment") String flagCommentBody,
@RequestParam("target") String targetComment)
throws IOException {
Map<String, Object> validationErrors = commentValidationService.validateFlag(flagCommentBody);
if (!validationErrors.isEmpty()) {
return ImmutableMap.of("validationErrors", validationErrors);
}
URI forwardedUrl = UriUtil.concatenate(articleApi.getServerUrl(),
String.format("%s/%s?flag", COMMENT_NAMESPACE, targetComment));
String authId = request.getRemoteUser();
ArticleCommentFlag flag = new ArticleCommentFlag(userApi.getUserIdFromAuthId(authId), flagCommentBody, reasonCode);
HttpUriRequest commentPostRequest = createJsonPostRequest(forwardedUrl, flag);
try (CloseableHttpResponse response = articleApi.getResponse(commentPostRequest)) {
return ImmutableMap.of(); // the "201 CREATED" status is all the AJAX client needs
}
}
/**
* Serves a request for the "about the authors" page for an article.
*
* @param model data to pass to the view
* @param site current site
* @param articleId specifies the article
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleAuthors", value = "/article/authors")
public String renderArticleAuthors( HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
return site + "/ftl/article/authors";
}
/**
* Serves the article metrics tab content for an article.
*
* @param model data to pass to the view
* @param site current site
* @param articleId specifies the article
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleMetrics", value = "/article/metrics")
public String renderArticleMetrics(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
return site + "/ftl/article/metrics";
}
@RequestMapping(name = "citationDownloadPage", value = "/article/citation")
public String renderCitationDownloadPage(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId)
throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetaData);
return site + "/ftl/article/citationDownload";
}
@RequestMapping(name = "downloadRisCitation", value = "/article/citation/ris")
public ResponseEntity<String> serveRisCitationDownload(@SiteParam Site site, @RequestParam("id") String articleId)
throws IOException {
return serveCitationDownload(site, articleId, "ris", "application/x-research-info-systems",
citationDownloadService::buildRisCitation);
}
@RequestMapping(name = "downloadBibtexCitation", value = "/article/citation/bibtex")
public ResponseEntity<String> serveBibtexCitationDownload(@SiteParam Site site, @RequestParam("id") String articleId)
throws IOException {
return serveCitationDownload(site, articleId, "bib", "application/x-bibtex",
citationDownloadService::buildBibtexCitation);
}
private ResponseEntity<String> serveCitationDownload(Site site, String articleId,
String fileExtension, String contentType,
Function<Map<String, ?>, String> serviceFunction)
throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
validateArticleVisibility(site, articleMetadata);
String citationBody = serviceFunction.apply((Map<String, ?>) articleMetadata);
String contentDispositionValue = String.format("attachment; filename=\"%s.%s\"",
URLEncoder.encode(DoiSchemeStripper.strip((String) articleMetadata.get("doi")), Charsets.UTF_8.toString()),
fileExtension);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, contentType);
headers.add(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue);
return new ResponseEntity<>(citationBody, headers, HttpStatus.OK);
}
/**
* Serves the related content tab content for an article.
*
* @param model data to pass to the view
* @param site current site
* @param articleId specifies the article
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "articleRelatedContent", value = "/article/related")
public String renderArticleRelatedContent(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetadata);
String recaptchaPublicKey = site.getTheme().getConfigMap("captcha").get("publicKey").toString();
model.addAttribute("recaptchaPublicKey", recaptchaPublicKey);
return site + "/ftl/article/relatedContent";
}
/**
* Serves as a POST endpoint to submit media curation requests
*
* @param model data passed in from the view
* @param site current site
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "submitMediaCurationRequest", value = "/article/submitMediaCurationRequest", method = RequestMethod.POST)
public @ResponseBody String submitMediaCurationRequest(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("doi") String doi,
@RequestParam("link") String link,
@RequestParam("comment") String comment,
@RequestParam("name") String name,
@RequestParam("email") String email,
@RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
@RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
throws IOException {
requireNonemptyParameter(doi);
if (!validateMediaCurationInput(model, link, name, email, captchaChallenge,
captchaResponse, site, request)) {
model.addAttribute("formError", "Invalid values have been submitted.");
//return model for error reporting
return jsonService.serialize(model);
}
String linkComment = name + ", " + email + "\n" + comment;
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("doi", doi.replaceFirst("info:doi/", "")));
params.add(new BasicNameValuePair("link", link));
params.add(new BasicNameValuePair("comment", linkComment));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
String mediaCurationUrl = site.getTheme().getConfigMap("mediaCuration").get("mediaCurationUrl").toString();
if (mediaCurationUrl != null) {
HttpPost httpPost = new HttpPost(mediaCurationUrl);
httpPost.setEntity(entity);
StatusLine statusLine = null;
try (CloseableHttpResponse response = cachedRemoteReader.getResponse(httpPost)) {
statusLine = response.getStatusLine();
} catch (ServiceRequestException e) {
//This exception is thrown when the submitted link is already present for the article.
if (e.getStatusCode() == HttpStatus.BAD_REQUEST.value()
&& e.getResponseBody().equals("The link already exists")) {
model.addAttribute("formError", "This link has already been submitted. Please submit a different link");
model.addAttribute("isValid", false);
} else {
throw new RuntimeException(e);
}
} finally {
httpPost.releaseConnection();
}
if (statusLine != null && statusLine.getStatusCode() != HttpStatus.CREATED.value()) {
throw new RuntimeException("bad response from media curation server: " + statusLine);
}
}
return jsonService.serialize(model);
}
/**
* Validate the input from the form
* @param model data passed in from the view
* @param link link pointing to media content relating to the article
* @param name name of the user submitting the media curation request
* @param email email of the user submitting the media curation request
* @param site current site
* @return true if everything is ok
*/
private boolean validateMediaCurationInput(Model model, String link, String name,
String email, String captchaChallenge, String captchaResponse, Site site,
HttpServletRequest request) throws IOException {
boolean isValid = true;
UrlValidator urlValidator = new UrlValidator();
if (StringUtils.isBlank(link)) {
model.addAttribute("linkError", "This field is required.");
isValid = false;
} else if (!urlValidator.isValid(link)) {
model.addAttribute("linkError", "Invalid Media link URL");
isValid = false;
}
if (StringUtils.isBlank(name)) {
model.addAttribute("nameError", "This field is required.");
isValid = false;
}
if (StringUtils.isBlank(email)) {
model.addAttribute("emailError", "This field is required.");
isValid = false;
} else if (!EmailValidator.getInstance().isValid(email)) {
model.addAttribute("emailError", "Invalid e-mail address");
isValid = false;
}
if (!captchaService.validateCaptcha(site, request.getRemoteAddr(), captchaChallenge, captchaResponse)) {
model.addAttribute("captchaError", "Verification is incorrect. Please try again.");
isValid = false;
}
model.addAttribute("isValid", isValid);
return isValid;
}
/*
* Returns a list of figures and tables of a given article; main usage is the figshare tile on the Metrics
* tab
*
* @param site current site
* @param articleId DOI identifying the article
* @return a list of figures and tables of a given article
* @throws IOException
*/
@RequestMapping(name = "articleFigsAndTables", value = "/article/assets/figsAndTables")
public ResponseEntity<List> listArticleFiguresAndTables(@SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
validateArticleVisibility(site, articleMetadata);
List<ImmutableMap<String, String>> articleFigsAndTables = articleService.getArticleFiguresAndTables(articleMetadata);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return new ResponseEntity<>(articleFigsAndTables, headers, HttpStatus.OK);
}
@RequestMapping(name = "email", value = "/article/email")
public String renderEmailThisArticle(HttpServletRequest request, Model model, @SiteParam Site site,
@RequestParam("id") String articleId) throws IOException {
requireNonemptyParameter(articleId);
Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
validateArticleVisibility(site, articleMetadata);
model.addAttribute("maxEmails", MAX_TO_EMAILS);
model.addAttribute("captchaHTML", captchaService.getCaptchaHtml(site, Optional.empty()));
return site + "/ftl/article/email";
}
/**
* @param model data passed in from the view
* @param site current site
* @return path to the template
* @throws IOException
*/
@RequestMapping(name = "emailPost", value = "/article/email", method = RequestMethod.POST)
public String emailArticle(HttpServletRequest request, HttpServletResponse response, Model model,
@SiteParam Site site,
@RequestParam("id") String articleId,
@RequestParam("articleUri") String articleUri,
@RequestParam("emailToAddresses") String emailToAddresses,
@RequestParam("emailFrom") String emailFrom,
@RequestParam("senderName") String senderName,
@RequestParam("note") String note,
@RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
@RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
throws IOException, MessagingException {
requireNonemptyParameter(articleId);
requireNonemptyParameter(articleUri);
model.addAttribute("emailToAddresses", emailToAddresses);
model.addAttribute("emailFrom", emailFrom);
model.addAttribute("senderName", senderName);
model.addAttribute("note", note);
model.addAttribute("articleUri", articleUri);
List<InternetAddress> toAddresses = Splitter.on(CharMatcher.anyOf("\n\r")).omitEmptyStrings()
.splitToList(emailToAddresses).stream()
.map(email -> EmailMessage.createAddress(null /*name*/, email))
.collect(Collectors.toList());
Set<String> errors = validateEmailArticleInput(toAddresses, emailFrom, senderName,
captchaChallenge, captchaResponse, site, request);
if (applyValidation(response, model, errors)) {
return renderEmailThisArticle(request, model, site, articleId);
}
Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
String title = articleMetadata.get("title").toString();
model.addAttribute("title", title);
model.addAttribute("description", articleMetadata.get("description"));
model.addAttribute("journalName", site.getJournalName());
Multipart content = freemarkerMailService.createContent(site, "emailThisArticle", model);
EmailMessage message = EmailMessage.builder()
.addToEmailAddresses(toAddresses)
.setSenderAddress(EmailMessage.createAddress(senderName, emailFrom))
.setSubject("An Article from " + site.getJournalName() + ": " + title)
.setContent(content)
.setEncoding(freeMarkerConfig.getConfiguration().getDefaultEncoding())
.build();
message.send(javaMailSender);
response.setStatus(HttpStatus.CREATED.value());
return site + "/ftl/article/emailSuccess";
}
private Set<String> validateEmailArticleInput(List<InternetAddress> emailToAddresses,
String emailFrom, String senderName, String captchaChallenge, String captchaResponse,
Site site, HttpServletRequest request) throws IOException {
Set<String> errors = new HashSet<>();
if (StringUtils.isBlank(emailFrom)) {
errors.add("emailFromMissing");
} else if (!EmailValidator.getInstance().isValid(emailFrom)) {
errors.add("emailFromInvalid");
}
if (emailToAddresses.isEmpty()) {
errors.add("emailToAddressesMissing");
} else if (emailToAddresses.size() > MAX_TO_EMAILS) {
errors.add("tooManyEmailToAddresses");
} else if (emailToAddresses.stream()
.noneMatch(email -> EmailValidator.getInstance().isValid(email.toString()))) {
errors.add("emailToAddressesInvalid");
}
if (StringUtils.isBlank(senderName)) {
errors.add("senderNameMissing");
}
if (!captchaService.validateCaptcha(site, request.getRemoteAddr(), captchaChallenge, captchaResponse)) {
errors.add("captchaError");
}
return errors;
}
/**
* Loads article metadata from the SOA layer.
*
* @param articleId DOI identifying the article
* @return Map of JSON representing the article
* @throws IOException
*/
private Map<?, ?> requestArticleMetadata(String articleId) throws IOException {
Map<?, ?> articleMetadata;
try {
articleMetadata = articleService.requestArticleMetadata(articleId, false);
} catch (EntityNotFoundException enfe) {
throw new ArticleNotFoundException(articleId);
}
return articleMetadata;
}
/**
* Appends additional info about article authors to the model.
*
* @param model model to be passed to the view
* @param doi identifies the article
* @return the list of authors appended to the model
* @throws IOException
*/
private void requestAuthors(Model model, String doi) throws IOException {
Map<?, ?> allAuthorsData = articleApi.requestObject(
ApiAddress.builder("articles").addToken(doi).addParameter("authors").build(),
Map.class);
List<?> authors = (List<?>) allAuthorsData.get("authors");
model.addAttribute("authors", authors);
// Putting this here was a judgement call. One could make the argument that this logic belongs
// in Rhino, but it's so simple I elected to keep it here for now.
List<String> equalContributors = new ArrayList<>();
ListMultimap<String, String> authorAffiliationsMap = LinkedListMultimap.create();
for (Object o : authors) {
Map<String, Object> author = (Map<String, Object>) o;
String fullName = (String) author.get("fullName");
List<String> affiliations = (List<String>) author.get("affiliations");
for (String affiliation : affiliations) {
authorAffiliationsMap.put(affiliation, fullName);
}
Object obj = author.get("equalContrib");
if (obj != null && (boolean) obj) {
equalContributors.add(fullName);
}
// remove the footnote marker from the current address
List<String> currentAddresses = (List<String>) author.get("currentAddresses");
for (ListIterator<String> iterator = currentAddresses.listIterator(); iterator.hasNext(); ) {
String currentAddress = iterator.next();
iterator.set(TextUtil.removeFootnoteMarker(currentAddress));
}
}
//Create comma-separated list of authors per affiliation
LinkedHashMap<String, String> authorListAffiliationMap = new LinkedHashMap<>();
for (Map.Entry<String, Collection<String>> affiliation : authorAffiliationsMap.asMap().entrySet()) {
authorListAffiliationMap.put(affiliation.getKey(), Joiner.on(", ").join(affiliation.getValue()));
}
model.addAttribute("authorListAffiliationMap", authorListAffiliationMap);
model.addAttribute("authorContributions", allAuthorsData.get("authorContributions"));
model.addAttribute("competingInterests", allAuthorsData.get("competingInterests"));
model.addAttribute("correspondingAuthors", allAuthorsData.get("correspondingAuthorList"));
model.addAttribute("equalContributors", equalContributors);
}
/**
* Build the path to request the article XML asset for an article.
*
* @return the service path to the correspond article XML asset file
*/
private static ApiAddress getArticleXmlAssetPath(RenderContext renderContext) {
ScholarlyWorkId id = renderContext.getArticleId().get();
OptionalInt revisionNumber = id.getRevisionNumber();
ApiAddress.Builder address = ApiAddress.builder("articles").addToken(id.getDoi()).addParameter("xml");
if (revisionNumber.isPresent()) {
address = address.addParameter("revision", revisionNumber.getAsInt());
}
return address.build();
}
/**
* Retrieve and transform the body of an amendment article from its XML file. The returned value is cached.
*
* @return the body of the amendment article, transformed into HTML for display in a notice on the amended article
*/
private String getAmendmentBody(final RenderContext renderContext) throws IOException {
String cacheKey = "amendmentBody:" + Preconditions.checkNotNull(renderContext.getArticleId());
ApiAddress xmlAssetPath = getArticleXmlAssetPath(renderContext);
return articleApi.requestCachedStream(CacheParams.create(cacheKey), xmlAssetPath, stream -> {
// Extract the "/article/body" element from the amendment XML, not to be confused with the HTML <body> element.
String bodyXml = xmlService.extractElement(stream, "body");
try {
return articleTransformService.transformExcerpt(renderContext, bodyXml, null);
} catch (TransformerException e) {
throw new RuntimeException(e);
}
});
}
/**
* Retrieves article XML from the SOA server, transforms it into HTML, and returns it. Result will be stored in
* memcache.
*
* @return String of the article HTML
* @throws IOException
*/
private String getArticleHtml(final RenderContext renderContext) throws IOException {
String cacheKey = String.format("html:%s:%s",
Preconditions.checkNotNull(renderContext.getSite()), renderContext.getArticleId());
ApiAddress xmlAssetPath = getArticleXmlAssetPath(renderContext);
return articleApi.requestCachedStream(CacheParams.create(cacheKey), xmlAssetPath, stream -> {
StringWriter articleHtml = new StringWriter(XFORM_BUFFER_SIZE);
try (OutputStream outputStream = new WriterOutputStream(articleHtml, charset)) {
articleTransformService.transform(renderContext, stream, outputStream);
} catch (TransformerException e) {
throw new RuntimeException(e);
}
return articleHtml.toString();
});
}
private Map<?, ?> addCommonModelAttributes(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException {
Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
addCrossPublishedJournals(request, model, site, articleMetadata);
model.addAttribute("article", articleMetadata);
model.addAttribute("containingLists", getContainingArticleLists(articleId, site));
model.addAttribute("categoryTerms", getCategoryTerms(articleMetadata));
requestAuthors(model, articleId);
return articleMetadata;
}
}
| Auto-format
| src/main/java/org/ambraproject/wombat/controller/ArticleController.java | Auto-format | <ide><path>rc/main/java/org/ambraproject/wombat/controller/ArticleController.java
<ide> import org.ambraproject.wombat.service.FreemarkerMailService;
<ide> import org.ambraproject.wombat.service.RenderContext;
<ide> import org.ambraproject.wombat.service.XmlService;
<add>import org.ambraproject.wombat.service.remote.ArticleApi;
<ide> import org.ambraproject.wombat.service.remote.CachedRemoteService;
<ide> import org.ambraproject.wombat.service.remote.JsonService;
<ide> import org.ambraproject.wombat.service.remote.ServiceRequestException;
<del>import org.ambraproject.wombat.service.remote.ArticleApi;
<ide> import org.ambraproject.wombat.service.remote.UserApi;
<ide> import org.ambraproject.wombat.util.CacheParams;
<ide> import org.ambraproject.wombat.util.DoiSchemeStripper;
<ide> * @throws IOException
<ide> */
<ide> @RequestMapping(name = "articleAuthors", value = "/article/authors")
<del> public String renderArticleAuthors( HttpServletRequest request, Model model, @SiteParam Site site,
<add> public String renderArticleAuthors(HttpServletRequest request, Model model, @SiteParam Site site,
<ide> @RequestParam("id") String articleId) throws IOException {
<del> Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
<del> validateArticleVisibility(site, articleMetaData);
<del> return site + "/ftl/article/authors";
<del> }
<del>
<del> /**
<add> Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
<add> validateArticleVisibility(site, articleMetaData);
<add> return site + "/ftl/article/authors";
<add> }
<add>
<add> /**
<ide> * Serves the article metrics tab content for an article.
<ide> *
<ide> * @param model data to pass to the view
<ide> @RequestMapping(name = "articleMetrics", value = "/article/metrics")
<ide> public String renderArticleMetrics(HttpServletRequest request, Model model, @SiteParam Site site,
<ide> @RequestParam("id") String articleId) throws IOException {
<del> Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
<del> validateArticleVisibility(site, articleMetaData);
<add> Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
<add> validateArticleVisibility(site, articleMetaData);
<ide> return site + "/ftl/article/metrics";
<ide> }
<ide>
<ide> @RequestParam("id") String articleId)
<ide> throws IOException {
<ide> requireNonemptyParameter(articleId);
<del> Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
<del> validateArticleVisibility(site, articleMetaData);
<del> return site + "/ftl/article/citationDownload";
<add> Map<?, ?> articleMetaData = addCommonModelAttributes(request, model, site, articleId);
<add> validateArticleVisibility(site, articleMetaData);
<add> return site + "/ftl/article/citationDownload";
<ide> }
<ide>
<ide> @RequestMapping(name = "downloadRisCitation", value = "/article/citation/ris")
<ide> validateArticleVisibility(site, articleMetadata);
<ide> String citationBody = serviceFunction.apply((Map<String, ?>) articleMetadata);
<ide> String contentDispositionValue = String.format("attachment; filename=\"%s.%s\"",
<del> URLEncoder.encode(DoiSchemeStripper.strip((String) articleMetadata.get("doi")), Charsets.UTF_8.toString()),
<del> fileExtension);
<add> URLEncoder.encode(DoiSchemeStripper.strip((String) articleMetadata.get("doi")), Charsets.UTF_8.toString()),
<add> fileExtension);
<ide>
<ide> HttpHeaders headers = new HttpHeaders();
<ide> headers.add(HttpHeaders.CONTENT_TYPE, contentType);
<ide> */
<ide> @RequestMapping(name = "articleRelatedContent", value = "/article/related")
<ide> public String renderArticleRelatedContent(HttpServletRequest request, Model model, @SiteParam Site site,
<del> @RequestParam("id") String articleId) throws IOException {
<add> @RequestParam("id") String articleId) throws IOException {
<ide> requireNonemptyParameter(articleId);
<ide> Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
<ide> validateArticleVisibility(site, articleMetadata);
<ide> /**
<ide> * Serves as a POST endpoint to submit media curation requests
<ide> *
<del> * @param model data passed in from the view
<del> * @param site current site
<add> * @param model data passed in from the view
<add> * @param site current site
<ide> * @return path to the template
<ide> * @throws IOException
<ide> */
<ide> @RequestMapping(name = "submitMediaCurationRequest", value = "/article/submitMediaCurationRequest", method = RequestMethod.POST)
<del> public @ResponseBody String submitMediaCurationRequest(HttpServletRequest request, Model model, @SiteParam Site site,
<del> @RequestParam("doi") String doi,
<del> @RequestParam("link") String link,
<del> @RequestParam("comment") String comment,
<del> @RequestParam("name") String name,
<del> @RequestParam("email") String email,
<del> @RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
<del> @RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
<add> public
<add> @ResponseBody
<add> String submitMediaCurationRequest(HttpServletRequest request, Model model, @SiteParam Site site,
<add> @RequestParam("doi") String doi,
<add> @RequestParam("link") String link,
<add> @RequestParam("comment") String comment,
<add> @RequestParam("name") String name,
<add> @RequestParam("email") String email,
<add> @RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
<add> @RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
<ide> throws IOException {
<ide> requireNonemptyParameter(doi);
<ide>
<ide>
<ide> /**
<ide> * Validate the input from the form
<add> *
<ide> * @param model data passed in from the view
<del> * @param link link pointing to media content relating to the article
<del> * @param name name of the user submitting the media curation request
<add> * @param link link pointing to media content relating to the article
<add> * @param name name of the user submitting the media curation request
<ide> * @param email email of the user submitting the media curation request
<del> * @param site current site
<add> * @param site current site
<ide> * @return true if everything is ok
<ide> */
<ide> private boolean validateMediaCurationInput(Model model, String link, String name,
<del> String email, String captchaChallenge, String captchaResponse, Site site,
<del> HttpServletRequest request) throws IOException {
<add> String email, String captchaChallenge, String captchaResponse, Site site,
<add> HttpServletRequest request) throws IOException {
<ide>
<ide> boolean isValid = true;
<ide>
<ide> model.addAttribute("isValid", isValid);
<ide> return isValid;
<ide> }
<add>
<ide> /*
<ide> * Returns a list of figures and tables of a given article; main usage is the figshare tile on the Metrics
<ide> * tab
<ide> */
<ide> @RequestMapping(name = "articleFigsAndTables", value = "/article/assets/figsAndTables")
<ide> public ResponseEntity<List> listArticleFiguresAndTables(@SiteParam Site site,
<del> @RequestParam("id") String articleId) throws IOException {
<add> @RequestParam("id") String articleId) throws IOException {
<ide> requireNonemptyParameter(articleId);
<ide> Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
<ide> validateArticleVisibility(site, articleMetadata);
<ide>
<ide> @RequestMapping(name = "email", value = "/article/email")
<ide> public String renderEmailThisArticle(HttpServletRequest request, Model model, @SiteParam Site site,
<del> @RequestParam("id") String articleId) throws IOException {
<add> @RequestParam("id") String articleId) throws IOException {
<ide> requireNonemptyParameter(articleId);
<ide> Map<?, ?> articleMetadata = addCommonModelAttributes(request, model, site, articleId);
<ide> validateArticleVisibility(site, articleMetadata);
<ide> }
<ide>
<ide> /**
<del> * @param model data passed in from the view
<del> * @param site current site
<add> * @param model data passed in from the view
<add> * @param site current site
<ide> * @return path to the template
<ide> * @throws IOException
<ide> */
<ide> @RequestMapping(name = "emailPost", value = "/article/email", method = RequestMethod.POST)
<ide> public String emailArticle(HttpServletRequest request, HttpServletResponse response, Model model,
<del> @SiteParam Site site,
<del> @RequestParam("id") String articleId,
<del> @RequestParam("articleUri") String articleUri,
<del> @RequestParam("emailToAddresses") String emailToAddresses,
<del> @RequestParam("emailFrom") String emailFrom,
<del> @RequestParam("senderName") String senderName,
<del> @RequestParam("note") String note,
<del> @RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
<del> @RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
<add> @SiteParam Site site,
<add> @RequestParam("id") String articleId,
<add> @RequestParam("articleUri") String articleUri,
<add> @RequestParam("emailToAddresses") String emailToAddresses,
<add> @RequestParam("emailFrom") String emailFrom,
<add> @RequestParam("senderName") String senderName,
<add> @RequestParam("note") String note,
<add> @RequestParam(RECAPTCHA_CHALLENGE_FIELD) String captchaChallenge,
<add> @RequestParam(RECAPTCHA_RESPONSE_FIELD) String captchaResponse)
<ide> throws IOException, MessagingException {
<ide> requireNonemptyParameter(articleId);
<ide> requireNonemptyParameter(articleUri);
<ide> }
<ide>
<ide> private Set<String> validateEmailArticleInput(List<InternetAddress> emailToAddresses,
<del> String emailFrom, String senderName, String captchaChallenge, String captchaResponse,
<del> Site site, HttpServletRequest request) throws IOException {
<add> String emailFrom, String senderName, String captchaChallenge, String captchaResponse,
<add> Site site, HttpServletRequest request) throws IOException {
<ide>
<ide> Set<String> errors = new HashSet<>();
<ide> if (StringUtils.isBlank(emailFrom)) {
<ide> if (emailToAddresses.isEmpty()) {
<ide> errors.add("emailToAddressesMissing");
<ide> } else if (emailToAddresses.size() > MAX_TO_EMAILS) {
<del> errors.add("tooManyEmailToAddresses");
<add> errors.add("tooManyEmailToAddresses");
<ide> } else if (emailToAddresses.stream()
<ide> .noneMatch(email -> EmailValidator.getInstance().isValid(email.toString()))) {
<ide> errors.add("emailToAddressesInvalid");
<ide> });
<ide> }
<ide>
<del> private Map<?, ?> addCommonModelAttributes(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException {
<del> Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
<del> addCrossPublishedJournals(request, model, site, articleMetadata);
<del> model.addAttribute("article", articleMetadata);
<del> model.addAttribute("containingLists", getContainingArticleLists(articleId, site));
<del> model.addAttribute("categoryTerms", getCategoryTerms(articleMetadata));
<del> requestAuthors(model, articleId);
<del> return articleMetadata;
<del> }
<add> private Map<?, ?> addCommonModelAttributes(HttpServletRequest request, Model model, @SiteParam Site site, @RequestParam("id") String articleId) throws IOException {
<add> Map<?, ?> articleMetadata = requestArticleMetadata(articleId);
<add> addCrossPublishedJournals(request, model, site, articleMetadata);
<add> model.addAttribute("article", articleMetadata);
<add> model.addAttribute("containingLists", getContainingArticleLists(articleId, site));
<add> model.addAttribute("categoryTerms", getCategoryTerms(articleMetadata));
<add> requestAuthors(model, articleId);
<add> return articleMetadata;
<add> }
<ide>
<ide> } |
|
JavaScript | mit | 1235bd8b1667991e5789ea6dc9c208c426ad510a | 0 | trailofbits/tubertc,trailofbits/tubertc,trailofbits/tubertc | /**
* @file This handles the following:
* + Parsing of the query string for a roomName (if it exists)
* + Checking localStorage to determine the following information:
* - Is a userName key set with a valid value? If so, autopopulate the username field with this
* value.
* - Is a capabilities key set with valid values? If so, alter the navBar buttons to reflect the
* capabilities values. Valid capabilities:
* = cameraIsEnabled : bool
* = micIsEnabled : bool
* = dashModeEnabled : bool
* - Example:
* {
* "userName" : <string>,
* "cameraIsEnabled" : <bool>,
* "micIsEnabled" : <bool>,
* "dashModeEnabled" : <bool>
* }
* + Bind the Join button with a handler that performs the following actions:
* - Verifies that userName and roomName are valid values, if not, use visual indication
* and focus to direct user to the problematic field
* + Update localStorage fields with the new values.
*
* @requires module:js/error
* @requires module:js/navbar
* @requires module:js/dialog
* @requires module:js/vtc
* @requires Chance.js
*/
'use strict';
/**
* Generates a random room name.
*
* @returns {String} A random room name.
* @public
*/
var generateRoomName = function() {
return chance.word() + '-' + chance.hash().substring(0, 8);
};
/**
* Converts a room name to an RTC room name.
*
* @param {String} roomName - The room name.
* @returns {String} A room name suitable for RTC.
* @public
*/
var toRtcRoomName = function(roomName) {
return roomName
.replace(/[^\w\s]/gi, '')
.replace(/ /gi, '_');
};
// Provides a namespace to parse the room name from the querystring
var Query = {
/**
* Gets a room name.
* DO NOT TRUST OUTPUT FROM THIS FUNCTION
*
* @returns {String} The room name.
* @public
*/
getRoomName: function() {
var queryStart = '?room=';
var queryRaw = document.location.search;
if (queryRaw.length <= queryStart.length) {
return null;
}
if (queryRaw.indexOf(queryStart) !== 0) {
ErrorMetric.log('Query.getRoomName => Invalid querystring: ' + queryRaw);
return null;
}
return unescape(queryRaw.substring(6));
}
};
var StorageCookie = {
// The Object structure for our StorageCookie should look like the dictionary below:
// {
// "userName" : <string>,
// "cameraIsEnabled" : <bool>,
// "micIsEnabled" : <bool>,
// "dashModeEnabled" : <bool>
// }
/**
* Validates the StorageCookie.
*
* @param {Object} dict - StorageCookie configuration object.
* @returns {Boolean} True if valid, false otherwise.
* @private
*/
_validate: function(dict) {
return (typeof dict.userName === 'string' &&
typeof dict.cameraIsEnabled === 'boolean' &&
typeof dict.micIsEnabled === 'boolean' &&
typeof dict.dashModeEnabled === 'boolean');
},
/**
* Sets the StorageCookie.
*
* @param {Object} config - StorageCookie configuration object.
* @returns {Boolean} True if successful, false otherwise.
* @public
*/
set: function(config) {
if (this._validate(config)) {
localStorage.tubertc = JSON.stringify(config);
return true;
} else {
ErrorMetric.log('StorageCookie.set => invalid Object structure');
ErrorMetric.log(' => ' + JSON.stringify(config));
return false;
}
},
/**
* Sets a value on the storage cookie. This function assumes the
* existence of `localStorage.tubertc`. If it doesn't exist, it will
* fail. Otherwise, it will find the "key" in `localStorage.tubertc`
* and update it to the new value.
*
* @param {String} key - Key part of the key-value pair.
* @param {*} value - This value can be of any type and
* is returned whenever key is referenced.
* @returns {Boolean} True if successful, false otherwise.
* @public
*/
setValue: function(key, value) {
var config = this.get();
if (config === null) {
ErrorMetric.log('StorageCookie.setValue => StorageCookie.get had invalid return value');
return false;
} else {
if (config[key] !== undefined) {
ErrorMetric.log('StorageCookie.setValue => invalid key "' + key + '"');
return false;
} else {
config[key] = value;
return this.set(config);
}
}
},
/**
* Gets the StorageCookie.
* DO NOT TRUST THE RETURNED OBJECT: The userName field needs to be sanitized.
*
* @returns {Object} The StorageCookie dict if successful, `null` otherwise.
* @public
*/
get: function() {
var rawConfig = localStorage.tubertc;
if (rawConfig !== undefined) {
// TODO: are we certain we can trust JSON.parse to parse localStorage?
try {
var config = JSON.parse(rawConfig);
if (this._validate(config)) {
return config;
} else {
ErrorMetric.log('StorageCookie.get => localStorage.tubertc Object is invalid');
ErrorMetric.log(' => ' + JSON.stringify(config));
return null;
}
} catch (e) {
ErrorMetric.log('StorageCookie.get => exception while trying to validate localStorage.tubertc');
ErrorMetric.log(' => ' + e);
return null;
}
} else {
ErrorMetric.log('StorageCookie.get => localStorage.tubertc does not exist');
return null;
}
},
/**
* Gets the value associated with the key.
* DO NOT TRUST userName: it needs to be sanitized before use!
*
* @param {String} key - The key to look up.
* @returns {*} The value associated with the key, or `null`
* if either the key is invalid or `StorageCookie.get()` fails.
* @public
*/
getValue: function(key) {
var config = this.get();
if (config !== null) {
if (config[key] === undefined) {
ErrorMetric.log('StorageCookie.getKey => invalid key "' + key + '"');
return null;
} else {
return config[key];
}
} else {
ErrorMetric.log('StorageCookie.getKey => StorageCookie.get had invalid return value');
return null;
}
}
};
// jQuery selectors
var _joinBtn = $('#joinBtn');
var _loginMsg = $('#loginMsg');
var _loginAlert = $('#loginAlert');
var _userNameEntry = $('#userNameEntry');
var _roomNameEntry = $('#roomNameEntry');
var Login = {
_completionFn: null,
/**
* Check to see if the visitor is browsing a non-TLS instance of tuber
* with Chrome 47 and above.
*
* @returns {true|false} The return status value. This is the status of the
* check.
* @private
*/
_checkIfNonTlsAndChromeAbove47: function() {
var userAgent = navigator.userAgent;
if (window.location.protocol !== 'https:' &&
(window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1')) {
var browserString = null;
var browserVersion = null;
var browserVersionString = null;
var browserStartIdx = userAgent.indexOf('Chrome/');
if (browserStartIdx === -1) {
browserStartIdx = userAgent.indexOf('Chromium/');
}
if (browserStartIdx === -1) {
// Could not find Chrome or Chromium in user agent...
// At this point, we should assume that it might be newer than 47
return true;
}
var browserEndIdx = userAgent.indexOf(' ', browserStartIdx);
if (browserEndIdx === -1) {
browserString = userAgent.substring(browserStartIdx);
} else {
browserString = userAgent.substring(browserStartIdx, browserEndIdx);
}
browserVersionString = browserString.split('/')[1];
if (browserVersionString.indexOf('.') !== -1) {
browserVersion = parseInt(browserVersionString.split('.')[0], 10);
} else {
browserVersion = parseInt(browserVersionString, 10);
}
// Chrome/Chromium 47 introduces a policy requiring SSL for getUserMedia requests to
// work correctly.
if (browserVersion >= 47) {
return true;
}
}
return false;
},
/**
* Checks to ensure that the current browser has
* the support needed to successfully use tubertc.
*
* @returns {String|null} The return status value. It has three possible
* states, which mean the following:
* 'full' - All APIs are supported and browser is well tested
* 'ssl' - All APIs are supported but the current tuber instance is
* non-TLS and the viewing browser is Chrome 47+
* 'untested' - All APIs are supported but browser is not as well tested
* null - Some required APIs are not supported
* @private
*/
_browserCompatCheck: function() {
var userAgent = navigator.userAgent;
if (!('Notification' in window)) {
ErrorMetric.log('_browserCompatCheck => browser does not support Notifications');
ErrorMetric.log(' => userAgent: ' + userAgent);
return null;
}
if (!('localStorage' in window)) {
ErrorMetric.log('_browserCompatCheck => browser does not support LocalStorage');
ErrorMetric.log(' => userAgent: ' + userAgent);
return null;
}
if (!VTCCore.isBrowserSupported()) {
ErrorMetric.log('_browserCompatCheck => browser does not support WebRTC');
ErrorMetric.log(' => userAgent: ' + userAgent);
return null;
}
// @todo FIXME: We only have tested Chrome, need to refactor this once more browsers are tested
if ('chrome' in window) {
if (Login._checkIfNonTlsAndChromeAbove47()) {
return 'ssl';
}
return 'full';
} else {
return 'untested';
}
},
/**
* Validates the user and room names.
*
* @returns {Boolean} True if user name and
* room name are valid, false otherwise.
* @private
*/
_validate: function() {
var userName = $.trim(_userNameEntry.val());
var roomName = $.trim(_roomNameEntry.val());
if (userName.length === 0) {
_loginAlert
.html('Please provide a <b>user name</b>.')
.stop(true, false)
.slideDown();
_userNameEntry.focus();
return false;
}
if (roomName.length === 0) {
_loginAlert
.html('Please provide a <b>room name</b>.')
.stop(true, false)
.slideDown();
_roomNameEntry.focus();
return false;
}
return true;
},
/**
* Sets up the handlers for the initial "page" form.
*
* @param {Object} config - Configuration object of the form:
* {
* cameraBtn : <StatefulButton>,
* micBtn : <StatefulButton>,
* dashBtn : <StatefulButton>
* }
*
* @returns {Object} The current Login instance for chaining purposes.
* @public
*/
initialize: function(config) {
var _this = this;
if (typeof config.cameraBtn !== 'object' ||
typeof config.micBtn !== 'object' ||
typeof config.dashBtn !== 'object') {
ErrorMetric.log('Log.initialize => config parameter is not valid');
ErrorMetric.log(' => config.cameraBtn is ' + config.cameraBtn);
ErrorMetric.log(' => config.micBtn is ' + config.micBtn);
ErrorMetric.log(' => config.dashBtn is ' + config.dashBtn);
// Break chaining to indicate error
return null;
}
var compatStatus = this._browserCompatCheck();
if (compatStatus === null) {
_userNameEntry.prop('disabled', true);
_roomNameEntry.prop('disabled', true);
_joinBtn.prop('disabled', true);
// @todo FIXME: proofread and make this better
_loginAlert
.html(
'Your browser <b>does not</b> support some of the required APIs.<br>' +
'tubertc will not work on your current system.<br><br>' +
'We recommend using <a href="http://www.google.com/chrome/">Google Chrome</a>.'
)
.slideDown();
// Disable buttons since the app is disabled anyways.
config.cameraBtn.disableButton();
config.micBtn.disableButton();
config.dashBtn.disableButton();
ErrorMetric.log('Login.initialize => ' + navigator.userAgent + ' is not supported');
// Break chaining to indicate error
return null;
} else if (compatStatus === 'untested') {
// @todo FIXME: proofread and make this better
_loginAlert
.html(
'Your browser configuration has not been extensively tested. ' +
'There may be user interface artifacts or missing functionality.<br><br>' +
'We recommend using <a href="http://www.google.com/chrome/">Google Chrome</a>.'
)
.slideDown();
ErrorMetric.log('Login.initialize => ' + navigator.userAgent + ' is untested');
} else if (compatStatus === 'ssl') {
// @todo FIXME: proofread and make this better
_loginAlert
.html(
'Starting with Chrome 47 and higher, WebRTC will cease to function on non-TLS sites.'
)
.slideDown();
ErrorMetric.log('Login.initialize => ' + navigator.userAgent + ' requires SSL for getUserMedia ' +
'to work');
}
var userName = StorageCookie.getValue('userName');
var roomName = Query.getRoomName();
if (userName !== null) {
// @todo Verify that this doesn't introduce XSS
_userNameEntry.val(userName);
}
if (roomName !== null) {
_roomNameEntry
.val(roomName)
.prop('disabled', true);
} else {
// No roomName was specified, to make it friendly to the user, generate one.
// We don't set roomName because we want to make this field modifiable.
_roomNameEntry
.val(generateRoomName());
}
var scCameraEnabled = StorageCookie.getValue('cameraIsEnabled');
var scMicEnabled = StorageCookie.getValue('micIsEnabled');
var scDashMode = StorageCookie.getValue('dashModeEnabled');
var _setInitialBtnState = function(initValue, btn) {
if (initValue !== null && initValue !== btn.isSelected()) {
btn.toggle();
}
};
// Set button's initial state (from localStorage)
_setInitialBtnState(scCameraEnabled, config.cameraBtn);
_setInitialBtnState(scMicEnabled, config.micBtn);
_setInitialBtnState(scDashMode, config.dashBtn);
// Obtain the list of video sources, if none exist, disable the camera button
easyrtc.getVideoSourceList(function(list) {
if (list.length === 0) {
_setInitialBtnState(false, config.cameraBtn);
config.cameraBtn.disableButton();
// @todo FIXME: maybe add a different sort of notification, like a tooltip?
_loginMsg
.html('Disabling camera functionality because a camera could not be found.')
.slideDown();
}
});
_userNameEntry.keypress(function(e) {
// Detect when ENTER button is pressed
if (e.which === 13) {
if (roomName !== null) {
// Room is already populated from query string, simulate a click event
_joinBtn.click();
} else {
// Room is not populated, switch focus to roomNameEntry
_roomNameEntry.focus();
}
}
});
_roomNameEntry.keypress(function(e) {
// Detect when ENTER button is pressed
if (e.which === 13) {
_joinBtn.click();
}
});
_joinBtn.click(function() {
if (_this._validate()) {
_loginAlert
.stop(true, false)
.slideUp();
var params = {
userName: _userNameEntry.val(),
roomName: _roomNameEntry.val(),
rtcName: toRtcRoomName(_roomNameEntry.val()),
cameraIsEnabled: config.cameraBtn.isSelected(),
hasCamera: config.cameraBtn.isEnabled(),
micIsEnabled: config.micBtn.isSelected(),
hasMic: config.micBtn.isEnabled(),
dashIsEnabled: config.dashBtn.isSelected()
};
var trtcConfig = {
userName: params.userName,
cameraIsEnabled: params.cameraIsEnabled,
micIsEnabled: params.micIsEnabled,
dashModeEnabled: params.dashIsEnabled
};
StorageCookie.set(trtcConfig);
if (_this._completionFn !== null) {
$('#loginContent').fadeOut(function() {
_this._completionFn(params);
});
} else {
ErrorMetric.log('joinBtn.click => _completionFn not set');
// @todo FIXME: this case should not happen since we immediately call
// done() to set the completion handler
Dialog.show('An Error Has Occurred', 'tubertc has broke!');
}
} else {
ErrorMetric.log('joinBtn.click => failed to validate');
}
});
return this;
},
/**
* Completion handler, called when the "Join Room" button is clicked and all the input is validated.
* At this point, both the userName and roomName are considered UNTRUSTED and should be sanitized
* using Handlebars.
*
* @param {Function} completionFn - Completion callback of the form:
* function({
* userName : <String>,
* roomName : <String>,
* rtcName : <String>,
* cameraIsEnabled : <boolean>,
* hasCamera : <boolean>,
* micIsEnabled : <boolean>,
* hasMic : <boolean>,
* dashModeEnabled : <boolean>
* })
* @returns {Object} The current Login instance for chaining purposes.
* @public
*/
done: function(completionFn) {
this._completionFn = completionFn;
return this;
}
};
| public/js/login.js | /**
* @file This handles the following:
* + Parsing of the query string for a roomName (if it exists)
* + Checking localStorage to determine the following information:
* - Is a userName key set with a valid value? If so, autopopulate the username field with this
* value.
* - Is a capabilities key set with valid values? If so, alter the navBar buttons to reflect the
* capabilities values. Valid capabilities:
* = cameraIsEnabled : bool
* = micIsEnabled : bool
* = dashModeEnabled : bool
* - Example:
* {
* "userName" : <string>,
* "cameraIsEnabled" : <bool>,
* "micIsEnabled" : <bool>,
* "dashModeEnabled" : <bool>
* }
* + Bind the Join button with a handler that performs the following actions:
* - Verifies that userName and roomName are valid values, if not, use visual indication
* and focus to direct user to the problematic field
* + Update localStorage fields with the new values.
*
* @requires module:js/error
* @requires module:js/navbar
* @requires module:js/dialog
* @requires module:js/vtc
* @requires Chance.js
*/
'use strict';
/**
* Generates a random room name.
*
* @returns {String} A random room name.
* @public
*/
var generateRoomName = function() {
return chance.word() + '-' + chance.hash().substring(0, 8);
};
/**
* Converts a room name to an RTC room name.
*
* @param {String} roomName - The room name.
* @returns {String} A room name suitable for RTC.
* @public
*/
var toRtcRoomName = function(roomName) {
return roomName
.replace(/[^\w\s]/gi, '')
.replace(/ /gi, '_');
};
// Provides a namespace to parse the room name from the querystring
var Query = {
/**
* Gets a room name.
* DO NOT TRUST OUTPUT FROM THIS FUNCTION
*
* @returns {String} The room name.
* @public
*/
getRoomName: function() {
var queryStart = '?room=';
var queryRaw = document.location.search;
if (queryRaw.length <= queryStart.length) {
return null;
}
if (queryRaw.indexOf(queryStart) !== 0) {
ErrorMetric.log('Query.getRoomName => Invalid querystring: ' + queryRaw);
return null;
}
return unescape(queryRaw.substring(6));
}
};
var StorageCookie = {
// The Object structure for our StorageCookie should look like the dictionary below:
// {
// "userName" : <string>,
// "cameraIsEnabled" : <bool>,
// "micIsEnabled" : <bool>,
// "dashModeEnabled" : <bool>
// }
/**
* Validates the StorageCookie.
*
* @param {Object} dict - StorageCookie configuration object.
* @returns {Boolean} True if valid, false otherwise.
* @private
*/
_validate: function(dict) {
return (typeof dict.userName === 'string' &&
typeof dict.cameraIsEnabled === 'boolean' &&
typeof dict.micIsEnabled === 'boolean' &&
typeof dict.dashModeEnabled === 'boolean');
},
/**
* Sets the StorageCookie.
*
* @param {Object} config - StorageCookie configuration object.
* @returns {Boolean} True if successful, false otherwise.
* @public
*/
set: function(config) {
if (this._validate(config)) {
localStorage.tubertc = JSON.stringify(config);
return true;
} else {
ErrorMetric.log('StorageCookie.set => invalid Object structure');
ErrorMetric.log(' => ' + JSON.stringify(config));
return false;
}
},
/**
* Sets a value on the storage cookie. This function assumes the
* existence of `localStorage.tubertc`. If it doesn't exist, it will
* fail. Otherwise, it will find the "key" in `localStorage.tubertc`
* and update it to the new value.
*
* @param {String} key - Key part of the key-value pair.
* @param {*} value - This value can be of any type and
* is returned whenever key is referenced.
* @returns {Boolean} True if successful, false otherwise.
* @public
*/
setValue: function(key, value) {
var config = this.get();
if (config === null) {
ErrorMetric.log('StorageCookie.setValue => StorageCookie.get had invalid return value');
return false;
} else {
if (config[key] !== undefined) {
ErrorMetric.log('StorageCookie.setValue => invalid key "' + key + '"');
return false;
} else {
config[key] = value;
return this.set(config);
}
}
},
/**
* Gets the StorageCookie.
* DO NOT TRUST THE RETURNED OBJECT: The userName field needs to be sanitized.
*
* @returns {Object} The StorageCookie dict if successful, `null` otherwise.
* @public
*/
get: function() {
var rawConfig = localStorage.tubertc;
if (rawConfig !== undefined) {
// TODO: are we certain we can trust JSON.parse to parse localStorage?
try {
var config = JSON.parse(rawConfig);
if (this._validate(config)) {
return config;
} else {
ErrorMetric.log('StorageCookie.get => localStorage.tubertc Object is invalid');
ErrorMetric.log(' => ' + JSON.stringify(config));
return null;
}
} catch (e) {
ErrorMetric.log('StorageCookie.get => exception while trying to validate localStorage.tubertc');
ErrorMetric.log(' => ' + e);
return null;
}
} else {
ErrorMetric.log('StorageCookie.get => localStorage.tubertc does not exist');
return null;
}
},
/**
* Gets the value associated with the key.
* DO NOT TRUST userName: it needs to be sanitized before use!
*
* @param {String} key - The key to look up.
* @returns {*} The value associated with the key, or `null`
* if either the key is invalid or `StorageCookie.get()` fails.
* @public
*/
getValue: function(key) {
var config = this.get();
if (config !== null) {
if (config[key] === undefined) {
ErrorMetric.log('StorageCookie.getKey => invalid key "' + key + '"');
return null;
} else {
return config[key];
}
} else {
ErrorMetric.log('StorageCookie.getKey => StorageCookie.get had invalid return value');
return null;
}
}
};
// jQuery selectors
var _joinBtn = $('#joinBtn');
var _loginMsg = $('#loginMsg');
var _loginAlert = $('#loginAlert');
var _userNameEntry = $('#userNameEntry');
var _roomNameEntry = $('#roomNameEntry');
var Login = {
_completionFn: null,
/**
* Check to see if the visitor is browsing a non-TLS instance of tuber
* with Chrome 47 and above.
*
* @returns {true|false} The return status value. This is the status of the
* check.
* @private
*/
_checkIfNonTlsAndChromeAbove47: function() {
var userAgent = navigator.userAgent;
if (window.location.protocol !== 'https:' &&
(window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1')) {
var browserString = null;
var browserVersion = null;
var browserVersionString = null;
var browserStartIdx = userAgent.indexOf('Chrome/');
if (browserStartIdx === -1) {
browserStartIdx = userAgent.indexOf('Chromium/');
}
if (browserStartIdx === -1) {
// Could not find Chrome or Chromium in user agent...
// At this point, we should assume that it might be newer than 47
return true;
}
var browserEndIdx = userAgent.indexOf(' ', browserStartIdx);
if (browserEndIdx === -1) {
browserString = userAgent.substring(browserStartIdx);
} else {
browserString = userAgent.substring(browserStartIdx, browserEndIdx);
}
browserVersionString = browserString.split('/')[1];
if (browserVersionString.indexOf('.') !== -1) {
browserVersion = parseInt(browserVersionString.split('.')[0], 10);
} else {
browserVersion = parseInt(browserVersionString, 10);
}
// Chrome/Chromium 47 introduces a policy requiring SSL for getUserMedia requests to
// work correctly.
if (browserVersion >= 47) {
return true;
}
}
return false;
},
/**
* Checks to ensure that the current browser has
* the support needed to successfully use tubertc.
*
* @returns {String|null} The return status value. It has three possible
* states, which mean the following:
* 'full' - All APIs are supported and browser is well tested
* 'ssl' - All APIs are supported but the current tuber instance is
* non-TLS and the viewing browser is Chrome 47+
* 'untested' - All APIs are supported but browser is not as well tested
* null - Some required APIs are not supported
* @private
*/
_browserCompatCheck: function() {
var userAgent = navigator.userAgent;
if (!('Notification' in window)) {
ErrorMetric.log('_browserCompatCheck => browser does not support Notifications');
ErrorMetric.log(' => userAgent: ' + userAgent);
return null;
}
if (!('localStorage' in window)) {
ErrorMetric.log('_browserCompatCheck => browser does not support LocalStorage');
ErrorMetric.log(' => userAgent: ' + userAgent);
return null;
}
if (!VTCCore.isBrowserSupported()) {
ErrorMetric.log('_browserCompatCheck => browser does not support WebRTC');
ErrorMetric.log(' => userAgent: ' + userAgent);
return null;
}
// @todo FIXME: We only have tested Chrome, need to refactor this once more browsers are tested
if ('chrome' in window) {
if (Login._checkIfNonTlsAndChromeAbove47()) {
return 'ssl';
}
return 'full';
} else {
return 'untested';
}
},
/**
* Validates the user and room names.
*
* @returns {Boolean} True if user name and
* room name are valid, false otherwise.
* @private
*/
_validate: function() {
var userName = $.trim(_userNameEntry.val());
var roomName = $.trim(_roomNameEntry.val());
if (userName.length === 0) {
_loginAlert
.html('Please provide a <b>user name</b>.')
.stop(true, false)
.slideDown();
_userNameEntry.focus();
return false;
}
if (roomName.length === 0) {
_loginAlert
.html('Please provide a <b>room name</b>.')
.stop(true, false)
.slideDown();
_roomNameEntry.focus();
return false;
}
return true;
},
/**
* Sets up the handlers for the initial "page" form.
*
* @param {Object} config - Configuration object of the form:
* {
* cameraBtn : <StatefulButton>,
* micBtn : <StatefulButton>,
* dashBtn : <StatefulButton>
* }
*
* @returns {Object} The current Login instance for chaining purposes.
* @public
*/
initialize: function(config) {
var _this = this;
if (typeof config.cameraBtn !== 'object' ||
typeof config.micBtn !== 'object' ||
typeof config.dashBtn !== 'object') {
ErrorMetric.log('Log.initialize => config parameter is not valid');
ErrorMetric.log(' => config.cameraBtn is ' + config.cameraBtn);
ErrorMetric.log(' => config.micBtn is ' + config.micBtn);
ErrorMetric.log(' => config.dashBtn is ' + config.dashBtn);
// Break chaining to indicate error
return null;
}
var compatStatus = this._browserCompatCheck();
if (compatStatus === null) {
_userNameEntry.prop('disabled', true);
_roomNameEntry.prop('disabled', true);
_joinBtn.prop('disabled', true);
// @todo FIXME: proofread and make this better
_loginAlert
.html(
'Your browser <b>does not</b> support some of the required APIs.<br>' +
'tubertc will not work on your current system.<br><br>' +
'We recommend using <a href="http://www.google.com/chrome/">Google Chrome</a>.'
)
.slideDown();
// Disable buttons since the app is disabled anyways.
config.cameraBtn.disableButton();
config.micBtn.disableButton();
config.dashBtn.disableButton();
ErrorMetric.log('Login.initialize => ' + navigator.userAgent + ' is not supported');
// Break chaining to indicate error
return null;
} else if (compatStatus === 'untested') {
// @todo FIXME: proofread and make this better
_loginAlert
.html(
'Your browser configuration has not been extensively tested. ' +
'There may be user interface artifacts or missing functionality.<br><br>' +
'We recommend using <a href="http://www.google.com/chrome/">Google Chrome</a>.'
)
.slideDown();
ErrorMetric.log('Login.initialize => ' + navigator.userAgent + ' is untested');
} else if (compatStatus === 'ssl') {
// @todo FIXME: proofread and make this better
_loginAlert
.html(
'Starting with Chrome 47 and higher, WebRTC will cease to function on non-TLS sites.'
)
.slideDown();
ErrorMetric.log('Login.initialize => ' + navigator.userAgent + ' requires SSL for getUserMedia ' +
'to work');
}
var userName = StorageCookie.getValue('userName');
var roomName = Query.getRoomName();
if (userName !== null) {
// @todo Verify that this doesn't introduce XSS
_userNameEntry.val(userName);
}
if (roomName !== null) {
_roomNameEntry
.val(roomName)
.prop('disabled', true);
} else {
// No roomName was specified, to make it friendly to the user, generate one.
// We don't set roomName because we want to make this field modifiable.
_roomNameEntry
.val(generateRoomName());
}
var scCameraEnabled = StorageCookie.getValue('cameraIsEnabled');
var scMicEnabled = StorageCookie.getValue('micIsEnabled');
var scDashMode = StorageCookie.getValue('dashModeEnabled');
var _setInitialBtnState = function(initValue, btn) {
if (initValue !== null && initValue !== btn.isSelected()) {
btn.toggle();
}
};
// Set button's initial state (from localStorage)
_setInitialBtnState(scCameraEnabled, config.cameraBtn);
_setInitialBtnState(scMicEnabled, config.micBtn);
_setInitialBtnState(scDashMode, config.dashBtn);
// Obtain the list of video sources, if none exist, disable the camera button
easyrtc.getVideoSourceList(function(list) {
if (list.length === 0) {
_setInitialBtnState(false, config.cameraBtn);
config.cameraBtn.disableButton();
// @todo FIXME: maybe add a different sort of notification, like a tooltip?
_loginMsg
.html('Disabling camera because not a camera could be found.')
.slideDown();
}
});
_userNameEntry.keypress(function(e) {
// Detect when ENTER button is pressed
if (e.which === 13) {
if (roomName !== null) {
// Room is already populated from query string, simulate a click event
_joinBtn.click();
} else {
// Room is not populated, switch focus to roomNameEntry
_roomNameEntry.focus();
}
}
});
_roomNameEntry.keypress(function(e) {
// Detect when ENTER button is pressed
if (e.which === 13) {
_joinBtn.click();
}
});
_joinBtn.click(function() {
if (_this._validate()) {
_loginAlert
.stop(true, false)
.slideUp();
var params = {
userName: _userNameEntry.val(),
roomName: _roomNameEntry.val(),
rtcName: toRtcRoomName(_roomNameEntry.val()),
cameraIsEnabled: config.cameraBtn.isSelected(),
hasCamera: config.cameraBtn.isEnabled(),
micIsEnabled: config.micBtn.isSelected(),
hasMic: config.micBtn.isEnabled(),
dashIsEnabled: config.dashBtn.isSelected()
};
var trtcConfig = {
userName: params.userName,
cameraIsEnabled: params.cameraIsEnabled,
micIsEnabled: params.micIsEnabled,
dashModeEnabled: params.dashIsEnabled
};
StorageCookie.set(trtcConfig);
if (_this._completionFn !== null) {
$('#loginContent').fadeOut(function() {
_this._completionFn(params);
});
} else {
ErrorMetric.log('joinBtn.click => _completionFn not set');
// @todo FIXME: this case should not happen since we immediately call
// done() to set the completion handler
Dialog.show('An Error Has Occurred', 'tubertc has broke!');
}
} else {
ErrorMetric.log('joinBtn.click => failed to validate');
}
});
return this;
},
/**
* Completion handler, called when the "Join Room" button is clicked and all the input is validated.
* At this point, both the userName and roomName are considered UNTRUSTED and should be sanitized
* using Handlebars.
*
* @param {Function} completionFn - Completion callback of the form:
* function({
* userName : <String>,
* roomName : <String>,
* rtcName : <String>,
* cameraIsEnabled : <boolean>,
* hasCamera : <boolean>,
* micIsEnabled : <boolean>,
* hasMic : <boolean>,
* dashModeEnabled : <boolean>
* })
* @returns {Object} The current Login instance for chaining purposes.
* @public
*/
done: function(completionFn) {
this._completionFn = completionFn;
return this;
}
};
| Fix typo in camera error message | public/js/login.js | Fix typo in camera error message | <ide><path>ublic/js/login.js
<ide>
<ide> // @todo FIXME: maybe add a different sort of notification, like a tooltip?
<ide> _loginMsg
<del> .html('Disabling camera because not a camera could be found.')
<add> .html('Disabling camera functionality because a camera could not be found.')
<ide> .slideDown();
<ide> }
<ide> }); |
|
Java | mit | 80b819d231555a69616f56c77a4a17e70d9ea94b | 0 | hivdb/hiv-genotyper,hivdb/hiv-genotyper | package edu.stanford.hivdb.genotyper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.primitives.Ints;
public interface GenotypeReference {
public static int[] getNAIndice(char na) {
List<Integer> naIndice = new ArrayList<>();
String unNA = AmbiguousNATranslator.translate(na);
for (char sNA : unNA.toCharArray()) {
switch(sNA) {
case 'A':
naIndice.add(0);
break;
case 'C':
naIndice.add(1);
break;
case 'G':
naIndice.add(2);
break;
case 'T':
naIndice.add(3);
break;
}
}
return Ints.toArray(naIndice);
}
public static int[] getInverseNAIndice(char na) {
int[] naIndice = getNAIndice(na);
List<Integer> inverseNAIndice = new ArrayList<>();
for (int i = 0; i < 4; i ++) {
boolean found = false;
for (int naIdx : naIndice) {
if (i == naIdx) {
found = true;
break;
}
}
if (!found) {
inverseNAIndice.add(i);
}
}
return Ints.toArray(inverseNAIndice);
}
public static int[][][] buildReferenceMismatchTree(List<GenotypeReference> references, Integer firstNA, int lastNA) {
int seqLen = lastNA - firstNA + 1;
int numRefs = references.size();
// int[NAPosition][NA] rootNode = [...mismatchedRefs]
int[][][] rootNode = new int[seqLen][4][numRefs + 1];
int[][] rootNodePointer = new int[seqLen][4];
for (int i = 0; i < seqLen; i ++) {
// initialize rootNode; -1 indicates the end of matched refIdx
for (int naIdx = 0; naIdx < 4; naIdx ++) {
rootNode[i][naIdx][0] = -1;
}
}
for (int refIdx = 0; refIdx < numRefs; refIdx ++) {
GenotypeReference ref = references.get(refIdx);
String sequence = ref.getSequence().toUpperCase();
// build tree for each position
for (int i = 0; i < seqLen; i ++) {
char na = sequence.charAt(i);
// should search for mismatched refs but not matched
int[] inverseNAIndice = getInverseNAIndice(na);
for (int naIdx : inverseNAIndice) {
int[] naNode = rootNode[i][naIdx];
// add the newly found refIdx and shift end by 1
naNode[rootNodePointer[i][naIdx] ++] = refIdx;
naNode[rootNodePointer[i][naIdx]] = -1;
}
}
}
return rootNode;
}
public static void appendCodonDiscordance(
int codonStartNAPos, String curCodon,
Map<Integer, List<Integer>> discordanceListPerRef,
Map<Integer, List<Integer>> curCodonDiscordancePerRef,
Map<Integer, Set<String>> ignoredCodons) {
Set<String> codons = ignoredCodons.get(codonStartNAPos);
if (codons == null || !codons.contains(curCodon)) {
// keep the result if the current codon is not a SDRM
for (Map.Entry<Integer, List<Integer>> entry :
curCodonDiscordancePerRef.entrySet()) {
int refIdx = entry.getKey();
if (!discordanceListPerRef.containsKey(refIdx)) {
discordanceListPerRef.put(refIdx, new ArrayList<>());
}
List<Integer> discordanceList = discordanceListPerRef.get(refIdx);
discordanceList.addAll(entry.getValue());
}
}
}
/** compare given sequence with a set of references (provided by mismatchTree)
*
* @param sequence a string of DNA sequence
* @param seqFirstNA starting position of the given sequence
* @param seqLastNA ending position of the given sequence
* @param mismatchTree a fast negative search tree build by buildReferenceMismatchTree()
* @param treeFirstNA starting position of the tree references
* @param treeLastNA ending position of the tree references
* @param codonNAOffset in case to yield discordance when a codon ends, the method
* needs to know which position in the system used by previous NA positions are the
* bp0 of each codon.
* @param ignoredCodons certain codons at certain position can be ignored
*
* @return A list of discordance for each given reference
*
*/
public static Map<Integer, List<Integer>> compareWithSearchTree(
String sequence, int seqFirstNA, int seqLastNA,
int[][][] mismatchTree, int treeFirstNA, int treeLastNA,
int codonNAOffset, Map<Integer, Set<String>> ignoredCodons) {
int maxFirstNA = Math.max(seqFirstNA, treeFirstNA);
int minLastNA = Math.min(seqLastNA, treeLastNA);
int treeOffset = maxFirstNA - treeFirstNA;
int seqOffset = maxFirstNA - seqFirstNA;
int compareLength = minLastNA - maxFirstNA + 1;
Map<Integer, List<Integer>> discordanceListPerRef = new HashMap<>();
Map<Integer, List<Integer>> curCodonDiscordancePerRef = new HashMap<>();
StringBuffer curCodon = new StringBuffer();
for (int i = 0; i < compareLength; i ++) {
if ((maxFirstNA + i - codonNAOffset) % 3 == 0) {
// to check if the current position is the beginning of a codon
appendCodonDiscordance(
/* codonStartNAPos */ maxFirstNA + i - 3,
curCodon.toString(),
discordanceListPerRef, curCodonDiscordancePerRef,
ignoredCodons
);
curCodon.setLength(0);
curCodonDiscordancePerRef.clear();
}
int[][] treeNAs = mismatchTree[treeOffset + i];
char seqNA = sequence.charAt(seqOffset + i);
if (seqNA == '.') {
// no need for further processing if seqNA == '.'
curCodon.append(seqNA);
continue;
}
int[] naIndice = getNAIndice(seqNA);
Map<Integer, Integer> mismatchRefs = new HashMap<>();
for (int naIdx : naIndice) {
for (int mismatchRef : treeNAs[naIdx]) {
if (mismatchRef < 0) {
// the end
break;
}
int mismatchCount = mismatchRefs.getOrDefault(mismatchRef, 0) + 1;
mismatchRefs.put(mismatchRef, mismatchCount);
}
}
for (Map.Entry<Integer, Integer> e : mismatchRefs.entrySet()) {
if (e.getValue() < naIndice.length) {
// only get counted as discordance when no unambiguous NA was matched
continue;
}
int mismatchRef = e.getKey();
if (!curCodonDiscordancePerRef.containsKey(mismatchRef)) {
curCodonDiscordancePerRef.put(mismatchRef, new ArrayList<>());
}
curCodonDiscordancePerRef.get(mismatchRef).add(maxFirstNA + i);
}
curCodon.append(seqNA);
}
appendCodonDiscordance(
/* codonStartNAPos */ minLastNA - 3,
curCodon.toString(),
discordanceListPerRef, curCodonDiscordancePerRef,
ignoredCodons
);
return discordanceListPerRef;
}
/** get BoundGenotype object of given sequence
*
* @param sequence a string of DNA sequence
* @param firstNA starting position of the given sequence
* @param lastNA ending position of the given sequence
* @param discordanceList discordance from the comparison
* @return BoundGenotype object contained the comparison result
*/
default public BoundGenotype getBoundGenotype(
String sequence, int firstNA, int lastNA,
List<Integer> discordanceList) {
firstNA = Math.max(firstNA, getFirstNA());
lastNA = Math.min(lastNA, getLastNA());
return new BoundGenotype(
this, sequence, firstNA, lastNA, discordanceList);
}
/** a getter to get current reference's genotype
*
* @return a Genotype object that indicates the corresponding genotype
*/
public Genotype getGenotype();
/** a getter to get current reference's genbank accession id
*
* @return string
*/
public String getAccession();
/** a getter to get current reference's start position in HXB2
*
* @return integer
*/
public Integer getFirstNA();
/** a getter to get current reference's end position in HXB2
*
* @return integer
*/
public Integer getLastNA();
/** a getter to get current reference's sequence
*
* @return string
*/
public String getSequence();
public String getCountry();
public String getAuthorYear();
public Integer getYear();
}
| src/main/java/edu/stanford/hivdb/genotyper/GenotypeReference.java | package edu.stanford.hivdb.genotyper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.primitives.Ints;
public interface GenotypeReference {
public static int[] getNAIndice(char na) {
List<Integer> naIndice = new ArrayList<>();
String unNA = AmbiguousNATranslator.translate(na);
for (char sNA : unNA.toCharArray()) {
switch(sNA) {
case 'A':
naIndice.add(0);
break;
case 'C':
naIndice.add(1);
break;
case 'G':
naIndice.add(2);
break;
case 'T':
naIndice.add(3);
break;
}
}
return Ints.toArray(naIndice);
}
public static int[] getInverseNAIndice(char na) {
int[] naIndice = getNAIndice(na);
List<Integer> inverseNAIndice = new ArrayList<>();
for (int i = 0; i < 4; i ++) {
boolean found = false;
for (int naIdx : naIndice) {
if (i == naIdx) {
found = true;
break;
}
}
if (!found) {
inverseNAIndice.add(i);
}
}
return Ints.toArray(inverseNAIndice);
}
public static int[][][] buildReferenceMismatchTree(List<GenotypeReference> references, Integer firstNA, int lastNA) {
int seqLen = lastNA - firstNA + 1;
int numRefs = references.size();
// int[NAPosition][NA] rootNode = [...mismatchedRefs]
int[][][] rootNode = new int[seqLen][4][numRefs + 1];
int[][] rootNodePointer = new int[seqLen][4];
for (int i = 0; i < seqLen; i ++) {
// initialize rootNode; -1 indicates the end of matched refIdx
for (int naIdx = 0; naIdx < 4; naIdx ++) {
rootNode[i][naIdx][0] = -1;
}
}
for (int refIdx = 0; refIdx < numRefs; refIdx ++) {
GenotypeReference ref = references.get(refIdx);
String sequence = ref.getSequence().toUpperCase();
// build tree for each position
for (int i = 0; i < seqLen; i ++) {
char na = sequence.charAt(i);
// should search for mismatched refs but not matched
int[] inverseNAIndice = getInverseNAIndice(na);
for (int naIdx : inverseNAIndice) {
int[] naNode = rootNode[i][naIdx];
// add the newly found refIdx and shift end by 1
naNode[rootNodePointer[i][naIdx] ++] = refIdx;
naNode[rootNodePointer[i][naIdx]] = -1;
}
}
}
return rootNode;
}
public static void appendCodonDiscordance(
int codonStartNAPos, String curCodon,
Map<Integer, List<Integer>> discordanceListPerRef,
Map<Integer, List<Integer>> curCodonDiscordancePerRef,
Map<Integer, Set<String>> ignoredCodons) {
Set<String> codons = ignoredCodons.get(codonStartNAPos);
if (codons == null || !codons.contains(curCodon)) {
// keep the result if the current codon is not a SDRM
for (Map.Entry<Integer, List<Integer>> entry :
curCodonDiscordancePerRef.entrySet()) {
int refIdx = entry.getKey();
if (!discordanceListPerRef.containsKey(refIdx)) {
discordanceListPerRef.put(refIdx, new ArrayList<>());
}
List<Integer> discordanceList = discordanceListPerRef.get(refIdx);
discordanceList.addAll(entry.getValue());
}
}
}
/** compare given sequence with a set of references (provided by mismatchTree)
*
* @param sequence a string of DNA sequence
* @param seqFirstNA starting position of the given sequence
* @param seqLastNA ending position of the given sequence
* @param mismatchTree a fast negative search tree build by buildReferenceMismatchTree()
* @param treeFirstNA starting position of the tree references
* @param treeLastNA ending position of the tree references
* @param codonNAOffset in case to yield discordance when a codon ends, the method
* needs to know which position in the system used by previous NA positions are the
* bp0 of each codon.
* @param ignoredCodons certain codons at certain position can be ignored
*
* @return A list of discordance for each given reference
*
*/
public static Map<Integer, List<Integer>> compareWithSearchTree(
String sequence, int seqFirstNA, int seqLastNA,
int[][][] mismatchTree, int treeFirstNA, int treeLastNA,
int codonNAOffset, Map<Integer, Set<String>> ignoredCodons) {
int maxFirstNA = Math.max(seqFirstNA, treeFirstNA);
int minLastNA = Math.min(seqLastNA, treeLastNA);
int treeOffset = maxFirstNA - treeFirstNA;
int seqOffset = maxFirstNA - seqFirstNA;
int compareLength = minLastNA - maxFirstNA + 1;
Map<Integer, List<Integer>> discordanceListPerRef = new HashMap<>();
Map<Integer, List<Integer>> curCodonDiscordancePerRef = new HashMap<>();
StringBuffer curCodon = new StringBuffer();
for (int i = 0; i < compareLength; i ++) {
if ((maxFirstNA + i - codonNAOffset) % 3 == 0) {
// to check if the current position is the beginning of a codon
appendCodonDiscordance(
/* codonStartNAPos */ maxFirstNA + i - 3,
curCodon.toString(),
discordanceListPerRef, curCodonDiscordancePerRef,
ignoredCodons
);
curCodon.setLength(0);
curCodonDiscordancePerRef.clear();
}
int[][] treeNAs = mismatchTree[treeOffset + i];
char seqNA = sequence.charAt(seqOffset + i);
// Note: naIndice is empty if seqNA == '.'
int[] naIndice = getNAIndice(seqNA);
Map<Integer, Integer> mismatchRefs = new HashMap<>();
for (int naIdx : naIndice) {
for (int mismatchRef : treeNAs[naIdx]) {
if (mismatchRef < 0) {
// the end
break;
}
int mismatchCount = mismatchRefs.getOrDefault(mismatchRef, 0) + 1;
mismatchRefs.put(mismatchRef, mismatchCount);
}
}
for (Map.Entry<Integer, Integer> e : mismatchRefs.entrySet()) {
if (e.getValue() < naIndice.length) {
// only get counted as discordance when no unambiguous NA was matched
continue;
}
int mismatchRef = e.getKey();
if (!curCodonDiscordancePerRef.containsKey(mismatchRef)) {
curCodonDiscordancePerRef.put(mismatchRef, new ArrayList<>());
}
curCodonDiscordancePerRef.get(mismatchRef).add(maxFirstNA + i);
}
curCodon.append(seqNA);
}
appendCodonDiscordance(
/* codonStartNAPos */ minLastNA - 3,
curCodon.toString(),
discordanceListPerRef, curCodonDiscordancePerRef,
ignoredCodons
);
return discordanceListPerRef;
}
/** get BoundGenotype object of given sequence
*
* @param sequence a string of DNA sequence
* @param firstNA starting position of the given sequence
* @param lastNA ending position of the given sequence
* @param discordanceList discordance from the comparison
* @return BoundGenotype object contained the comparison result
*/
default public BoundGenotype getBoundGenotype(
String sequence, int firstNA, int lastNA,
List<Integer> discordanceList) {
firstNA = Math.max(firstNA, getFirstNA());
lastNA = Math.min(lastNA, getLastNA());
return new BoundGenotype(
this, sequence, firstNA, lastNA, discordanceList);
}
/** a getter to get current reference's genotype
*
* @return a Genotype object that indicates the corresponding genotype
*/
public Genotype getGenotype();
/** a getter to get current reference's genbank accession id
*
* @return string
*/
public String getAccession();
/** a getter to get current reference's start position in HXB2
*
* @return integer
*/
public Integer getFirstNA();
/** a getter to get current reference's end position in HXB2
*
* @return integer
*/
public Integer getLastNA();
/** a getter to get current reference's sequence
*
* @return string
*/
public String getSequence();
public String getCountry();
public String getAuthorYear();
public Integer getYear();
}
| A little performance optimization
| src/main/java/edu/stanford/hivdb/genotyper/GenotypeReference.java | A little performance optimization | <ide><path>rc/main/java/edu/stanford/hivdb/genotyper/GenotypeReference.java
<ide> }
<ide> int[][] treeNAs = mismatchTree[treeOffset + i];
<ide> char seqNA = sequence.charAt(seqOffset + i);
<del> // Note: naIndice is empty if seqNA == '.'
<add> if (seqNA == '.') {
<add> // no need for further processing if seqNA == '.'
<add> curCodon.append(seqNA);
<add> continue;
<add> }
<ide> int[] naIndice = getNAIndice(seqNA);
<ide> Map<Integer, Integer> mismatchRefs = new HashMap<>();
<ide> for (int naIdx : naIndice) { |
|
Java | mit | b07381c9246f0c856902a79a1b4a5ac7762a2c45 | 0 | augustt198/OvercastStats | package me.ryanw.overcast.impl.util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import java.io.IOException;
import java.net.URL;
import java.util.*;
public class MojangUtil {
/**
* Fetches the username of a user based on the UUID provided. The UUID can be full or trimmed.
* @param uuid Trimmed or full UUID of the user whose username we want to fetch.
* @return The current username of the UUID provided.
*/
public static String getUsername(String uuid) {
String url = "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid.replace("-", "");
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
return ((TextNode) new ObjectMapper().readTree(jsonParser).get("name")).textValue();
} catch (IOException ignored) {}
return null;
}
/**
* Gets the previous username (former) the user has used.
* @param uuid The UUID of the user we want to get the previous username for.
* @return Previous former username that the player used.
*/
public static FormerUsername getFormerUsername(UUID uuid) {
List<FormerUsername> formerUsernames;
String url = "https://api.mojang.com/user/profiles/" + uuid.toString().replaceAll("-", "") + "/names";
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
formerUsernames = Arrays.asList(new ObjectMapper().readValue(jsonParser, FormerUsername[].class));
if (formerUsernames.size() >= 2) return formerUsernames.get(formerUsernames.size() - 2);
} catch (IOException ignored) {}
return null;
}
/**
* Gets the previous username (former) the player has used.
* @param username The username of the user we want to get the previous username for.
* @return Previous former username that the player used.
*/
public static FormerUsername getFormerUsername(String username) {
List<FormerUsername> formerUsernames;
String url = "https://api.mojang.com/user/profiles/" + MojangUtil.getUUID(username, true) + "/names";
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
formerUsernames = Arrays.asList(new ObjectMapper().readValue(jsonParser, FormerUsername[].class));
if (formerUsernames.size() >= 2) return formerUsernames.get(formerUsernames.size() - 2);
} catch (IOException ignored) {}
return null;
}
/**
* Fetches a list of former usernames, in order from oldest to newest.
* @param uuid The UUID of the user we want to get username history for.
* @return List of former usernames in order from oldest to newest.
*/
public static List<FormerUsername> getFormerUsernames(String uuid) {
List<FormerUsername> formerUsernames;
String url = "https://api.mojang.com/user/profiles/" + uuid.replace("-", "") + "/names";
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
formerUsernames = new ArrayList<FormerUsername>(Arrays.asList(new ObjectMapper().readValue(jsonParser, FormerUsername[].class)));
formerUsernames.remove(formerUsernames.size() - 1);
return formerUsernames;
} catch (IOException ignored) {}
return null;
}
/**
* Fetches the UUID of a player by using their current username to look the UUID up.
* @param currentUsername The username to return the uuid of.
* @return The uuid owner of the username provided.
*/
public static String getUUID(String currentUsername, boolean trimmed) {
String url = "https://api.mojang.com/users/profiles/minecraft/" + currentUsername;
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
String uuid = ((TextNode) new ObjectMapper().readTree(jsonParser).get("id")).textValue();
if (!trimmed) return new StringBuilder(uuid).insert(8, "-").insert(13, "-").insert(18, "-").insert(23, "-").toString();
return uuid;
} catch (IOException ignored) {}
return null;
}
/**
* Represents one former username, in a possible array of previous former usernames.
*/
public static class FormerUsername {
private String name;
private String changedToAt;
public String getName() { return name; }
public Date getChangedToAt() { return new Date(changedToAt); }
}
}
| overcast-scraper/src/main/java/me/ryanw/overcast/impl/util/MojangUtil.java | package me.ryanw.overcast.impl.util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class MojangUtil {
/**
* Fetches the username of a user based on the UUID provided. The UUID can be full or trimmed.
* @param uuid Trimmed or full UUID of the user whose username we want to fetch.
* @return The current username of the UUID provided.
*/
public static String getUsername(String uuid) {
String url = "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid.replace("-", "");
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
return ((TextNode) new ObjectMapper().readTree(jsonParser).get("name")).textValue();
} catch (IOException ignored) {}
return null;
}
/**
* Gets the previous username (former) the user has used.
* @param uuid The UUID of the user we want to get the previous username for.
* @return Previous former username that the player used.
*/
public static FormerUsername getFormerUsername(String uuid) {
List<FormerUsername> formerUsernames;
String url = "https://api.mojang.com/user/profiles/" + uuid.replaceAll("-", "") + "/names";
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
formerUsernames = Arrays.asList(new ObjectMapper().readValue(jsonParser, FormerUsername[].class));
if (formerUsernames.size() >= 2) return formerUsernames.get(formerUsernames.size() - 2);
} catch (IOException ignored) {}
return null;
}
/**
* Fetches a list of former usernames, in order from oldest to newest.
* @param uuid The UUID of the user we want to get username history for.
* @return List of former usernames in order from oldest to newest.
*/
public static List<FormerUsername> getFormerUsernames(String uuid) {
List<FormerUsername> formerUsernames;
String url = "https://api.mojang.com/user/profiles/" + uuid.replace("-", "") + "/names";
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
formerUsernames = new ArrayList<FormerUsername>(Arrays.asList(new ObjectMapper().readValue(jsonParser, FormerUsername[].class)));
formerUsernames.remove(formerUsernames.size() - 1);
return formerUsernames;
} catch (IOException ignored) {}
return null;
}
/**
* Fetches the UUID of a player by using their current username to look the UUID up.
* @param currentUsername The username to return the uuid of.
* @return The uuid owner of the username provided.
*/
public static String getUUID(String currentUsername, boolean trimmed) {
String url = "https://api.mojang.com/users/profiles/minecraft/" + currentUsername;
try {
JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
String uuid = ((TextNode) new ObjectMapper().readTree(jsonParser).get("id")).textValue();
if (!trimmed) return new StringBuilder(uuid).insert(8, "-").insert(13, "-").insert(18, "-").insert(23, "-").toString();
return uuid;
} catch (IOException ignored) {}
return null;
}
/**
* Represents one former username, in a possible array of previous former usernames.
*/
public static class FormerUsername {
private String name;
private String changedToAt;
public String getName() { return name; }
public Date getChangedToAt() { return new Date(changedToAt); }
}
}
| Support getting former username from current username
| overcast-scraper/src/main/java/me/ryanw/overcast/impl/util/MojangUtil.java | Support getting former username from current username | <ide><path>vercast-scraper/src/main/java/me/ryanw/overcast/impl/util/MojangUtil.java
<ide>
<ide> import java.io.IOException;
<ide> import java.net.URL;
<del>import java.util.ArrayList;
<del>import java.util.Arrays;
<del>import java.util.Date;
<del>import java.util.List;
<add>import java.util.*;
<ide>
<ide> public class MojangUtil {
<ide>
<ide> * @param uuid The UUID of the user we want to get the previous username for.
<ide> * @return Previous former username that the player used.
<ide> */
<del> public static FormerUsername getFormerUsername(String uuid) {
<add> public static FormerUsername getFormerUsername(UUID uuid) {
<ide> List<FormerUsername> formerUsernames;
<del> String url = "https://api.mojang.com/user/profiles/" + uuid.replaceAll("-", "") + "/names";
<add> String url = "https://api.mojang.com/user/profiles/" + uuid.toString().replaceAll("-", "") + "/names";
<ide> try {
<ide> JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
<ide> formerUsernames = Arrays.asList(new ObjectMapper().readValue(jsonParser, FormerUsername[].class));
<ide> } catch (IOException ignored) {}
<ide> return null;
<ide> }
<add>
<add> /**
<add> * Gets the previous username (former) the player has used.
<add> * @param username The username of the user we want to get the previous username for.
<add> * @return Previous former username that the player used.
<add> */
<add> public static FormerUsername getFormerUsername(String username) {
<add> List<FormerUsername> formerUsernames;
<add> String url = "https://api.mojang.com/user/profiles/" + MojangUtil.getUUID(username, true) + "/names";
<add> try {
<add> JsonParser jsonParser = new JsonFactory().createParser(new URL(url).openStream());
<add> formerUsernames = Arrays.asList(new ObjectMapper().readValue(jsonParser, FormerUsername[].class));
<add> if (formerUsernames.size() >= 2) return formerUsernames.get(formerUsernames.size() - 2);
<add> } catch (IOException ignored) {}
<add> return null;
<add> }
<add>
<ide>
<ide> /**
<ide> * Fetches a list of former usernames, in order from oldest to newest. |
|
Java | apache-2.0 | 5d31a4912e0b13ab45064c72cb07b69c1df26c21 | 0 | gturri/dokuJClient,gturri/dokuJClient,gturri/dokuJClient | package dw.xmlrpc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
import dw.xmlrpc.exception.DokuException;
//! @cond
class Attacher {
private CoreClient _client;
public Attacher(CoreClient client){
_client = client;
}
byte[] serializeFile(File f) throws IOException{
byte[] b = new byte[(int)f.length()];
FileInputStream fileInputStream = new FileInputStream(f);
fileInputStream.read(b);
fileInputStream.close();
return b;
}
void deserializeFile(byte[] b, File f) throws IOException{
FileOutputStream fileOutputStream = new FileOutputStream(f);
fileOutputStream.write(b);
fileOutputStream.close();
}
public void putAttachment(String fileId, byte[] file, boolean overwrite) throws IOException, DokuException{
Map<String, Object> additionalParam = new HashMap<String, Object>();
additionalParam.put("ow", overwrite);
Object[] params = new Object[]{
fileId,
file,
additionalParam
};
_client.genericQuery("wiki.putAttachment", params);
}
public List<MediaChange> getRecentMediaChanges(Integer timestamp) throws DokuException{
Object result = _client.genericQuery("wiki.getRecentMediaChanges", timestamp);
List<MediaChange> res = new ArrayList<MediaChange>();
for(Object o : (Object[]) result){
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) o;
String id = (String) map.get("name");
Date lastModified = (Date) map.get("lastModified");
String author = (String) map.get("author");
Integer version = (Integer) map.get("version");
Integer perms = (Integer) map.get("perms");
Object sizeObj = map.get("size");
Integer size = null;
if ( sizeObj instanceof Integer ){
size = (Integer) sizeObj;
}
res.add(new MediaChange(id, lastModified, author, version, perms, size));
}
return res;
}
public List<AttachmentDetails> getAttachments(String namespace, Map<String, Object> additionalParams) throws DokuException{
if ( additionalParams == null ){
additionalParams = new HashMap<String, Object>();
}
Object[] params = new Object[]{namespace, additionalParams};
Object result = _client.genericQuery("wiki.getAttachments", params);
List<AttachmentDetails> res = new ArrayList<AttachmentDetails>();
for(Object o : (Object[]) result){
res.add(buildAttachmentDetailsFromResult(o));
}
return res;
}
@SuppressWarnings("unchecked")
private AttachmentDetails buildAttachmentDetailsFromResult(Object o){
return buildAttachmentDetailsFromResult((Map<String, Object>) o);
}
private AttachmentDetails buildAttachmentDetailsFromResult(Map<String, Object> m){
String id = (String) m.get("id");
Integer size = (Integer) m.get("size");
Date lastModified = (Date) m.get("lastModified");
Boolean isImg = (Boolean) m.get("isimg");
Boolean writable = (Boolean) m.get("writable");
Integer perms = (Integer) m.get("perm");
if ( perms == null ){
//Because it has been renamed in API v8
perms = (Integer) m.get("perms");
}
return new AttachmentDetails(id, size, lastModified, isImg, writable, perms);
}
public AttachmentInfo getAttachmentInfo(String fileId) throws DokuException{
Object result = _client.genericQuery("wiki.getAttachmentInfo", fileId);
return buildAttachmentInfoFromResult(result, fileId);
}
@SuppressWarnings("unchecked")
private AttachmentInfo buildAttachmentInfoFromResult(Object o, String fileId){
return buildAttachmentInfoFromResult((Map<String, Object>) o, fileId);
}
@SuppressWarnings("deprecation")
private AttachmentInfo buildAttachmentInfoFromResult(Map<String, Object> m, String fileId){
Integer size = (Integer) m.get("size");
Date lastModified = null;
try {
lastModified = (Date) m.get("lastModified");
} catch (ClassCastException e){
//for DW up to 2012-01-25b: when the file doesn't exist,
//"lastModified" is int 0
lastModified = new Date(1970, 1, 1, 0, 0, 0);
}
return new AttachmentInfo(fileId, size, lastModified);
}
public void deleteAttachment(String fileId) throws DokuException{
_client.genericQuery("wiki.deleteAttachment", fileId);
}
public byte[] getAttachment(String fileId) throws DokuException{
Object result = _client.genericQuery("wiki.getAttachment", fileId);
try {
return (byte[]) result;
} catch (ClassCastException e){
//for DW up to 2012-01-25b
String base64Encoded = (String) result;
return DatatypeConverter.parseBase64Binary(base64Encoded);
}
}
//! @endcond
}
| src/dw/xmlrpc/Attacher.java | package dw.xmlrpc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
import dw.xmlrpc.exception.DokuException;
//! @cond
class Attacher {
private CoreClient _client;
public Attacher(CoreClient client){
_client = client;
}
byte[] serializeFile(File f) throws IOException{
byte[] b = new byte[(int)f.length()];
FileInputStream fileInputStream = new FileInputStream(f);
fileInputStream.read(b);
fileInputStream.close();
return b;
}
void deserializeFile(byte[] b, File f) throws IOException{
FileOutputStream fileOutputStream = new FileOutputStream(f);
fileOutputStream.write(b);
fileOutputStream.close();
}
public void putAttachment(String fileId, byte[] file, boolean overwrite) throws IOException, DokuException{
Map<String, Object> additionalParam = new HashMap<String, Object>();
additionalParam.put("ow", overwrite);
Object[] params = new Object[]{
fileId,
file,
additionalParam
};
_client.genericQuery("wiki.putAttachment", params);
}
public List<MediaChange> getRecentMediaChanges(Integer timestamp) throws DokuException{
Object result = _client.genericQuery("wiki.getRecentMediaChanges", timestamp);
List<MediaChange> res = new ArrayList<MediaChange>();
for(Object o : (Object[]) result){
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) o;
String id = (String) map.get("name");
Date lastModified = (Date) map.get("lastModified");
String author = (String) map.get("author");
Integer version = (Integer) map.get("version");
Integer perms = (Integer) map.get("perms");
Object sizeObj = map.get("size");
Integer size = null;
if ( sizeObj instanceof Integer ){
size = (Integer) sizeObj;
}
res.add(new MediaChange(id, lastModified, author, version, perms, size));
}
return res;
}
public List<AttachmentDetails> getAttachments(String namespace, Map<String, Object> additionalParams) throws DokuException{
if ( additionalParams == null ){
additionalParams = new HashMap<String, Object>();
}
Object[] params = new Object[]{namespace, additionalParams};
Object result = _client.genericQuery("wiki.getAttachments", params);
List<AttachmentDetails> res = new ArrayList<AttachmentDetails>();
for(Object o : (Object[]) result){
res.add(buildAttachmentDetailsFromResult(o));
}
return res;
}
@SuppressWarnings("unchecked")
private AttachmentDetails buildAttachmentDetailsFromResult(Object o){
return buildAttachmentDetailsFromResult((Map<String, Object>) o);
}
private AttachmentDetails buildAttachmentDetailsFromResult(Map<String, Object> m){
String id = (String) m.get("id");
Integer size = (Integer) m.get("size");
Date lastModified = (Date) m.get("lastModified");
Boolean isImg = (Boolean) m.get("isimg");
Boolean writable = (Boolean) m.get("writable");
Integer perms = (Integer) m.get("perm");
if ( perms == null ){
//Because it has been renamed in API v8
perms = (Integer) m.get("perms");
}
return new AttachmentDetails(id, size, lastModified, isImg, writable, perms);
}
public AttachmentInfo getAttachmentInfo(String fileId) throws DokuException{
Object result = _client.genericQuery("wiki.getAttachmentInfo", fileId);
return buildAttachmentInfoFromResult(result, fileId);
}
@SuppressWarnings("unchecked")
private AttachmentInfo buildAttachmentInfoFromResult(Object o, String fileId){
return buildAttachmentInfoFromResult((Map<String, Object>) o, fileId);
}
private AttachmentInfo buildAttachmentInfoFromResult(Map<String, Object> m, String fileId){
Integer size = (Integer) m.get("size");
Date lastModified = (Date) m.get("lastModified");
return new AttachmentInfo(fileId, size, lastModified);
}
public void deleteAttachment(String fileId) throws DokuException{
_client.genericQuery("wiki.deleteAttachment", fileId);
}
public byte[] getAttachment(String fileId) throws DokuException{
Object result = _client.genericQuery("wiki.getAttachment", fileId);
try {
return (byte[]) result;
} catch (ClassCastException e){
//for DW up to 2012-01-25b
String base64Encoded = (String) result;
return DatatypeConverter.parseBase64Binary(base64Encoded);
}
}
//! @endcond
}
| Fix getAttachmentInfo for non-existing files for xmlrpc API v6
| src/dw/xmlrpc/Attacher.java | Fix getAttachmentInfo for non-existing files for xmlrpc API v6 | <ide><path>rc/dw/xmlrpc/Attacher.java
<ide> return buildAttachmentInfoFromResult((Map<String, Object>) o, fileId);
<ide> }
<ide>
<add> @SuppressWarnings("deprecation")
<ide> private AttachmentInfo buildAttachmentInfoFromResult(Map<String, Object> m, String fileId){
<ide> Integer size = (Integer) m.get("size");
<del> Date lastModified = (Date) m.get("lastModified");
<add> Date lastModified = null;
<add> try {
<add> lastModified = (Date) m.get("lastModified");
<add> } catch (ClassCastException e){
<add> //for DW up to 2012-01-25b: when the file doesn't exist,
<add> //"lastModified" is int 0
<add> lastModified = new Date(1970, 1, 1, 0, 0, 0);
<add> }
<ide> return new AttachmentInfo(fileId, size, lastModified);
<ide> }
<ide> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.