lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
JavaScript
|
mit
|
aaaf7c2dbe979fd67d2e07d1ff0b2b4b652cdeab
| 0 |
dmitrovskiy/black-jack-api
|
'use strict';
import test from 'ava';
import request from '../helpers/request';
import {assert} from 'chai';
import randomString from 'randomstring';
import userModel from '../../../src/services/user/user-model';
import gameModel from '../../../src/services/game/game-model';
const userStub = {
email: `${randomString.generate(12)}@test.com`
};
const gameStub = {};
test.before('prepare a user', async t => {
await userModel.remove();
await userModel
.create({email: userStub.email})
.then(res => {
userStub.id = res._id.toString();
});
});
test.after('clean up a user', async t => {
await userModel.remove({email: userStub.email});
});
test.after('clean up a game', async t => {
await gameModel.remove({_id: gameStub.id});
});
test('game: should be initialized', async t => {
await request
.post('/games')
.send({
userId: userStub.id,
bet: 10
})
.expect(res => {
assert.isDefined(res.body.id);
assert.isDefined(res.body.clientCards);
assert.isDefined(res.body.dealerCards);
})
.expect(201)
.then(res => {
gameStub.id = res.body.id;
});
});
|
test/integration/game/game-initialization.parallel.test.js
|
'use strict';
import test from 'ava';
import request from '../helpers/request';
import {assert} from 'chai';
import randomString from 'randomstring';
import userModel from '../../../src/services/user/user-model';
import gameModel from '../../../src/services/game/';
const userStub = {
email: `${randomString.generate(12)}@test.com`
};
test.before('prepare a user', async t => {
await userModel.remove();
await userModel
.create({email: userStub.email})
.then(res => {
userStub.id = res._id.toString();
});
});
test.after('clean up a user', async t => {
await userModel.remove({email: userStub.email});
});
test('game: should be initialized', async t => {
await request
.post('/games')
.send({
userId: userStub.id,
bet: 10
})
.expect(res => {
assert.isDefined(res.body.clientCards);
assert.isDefined(res.body.dealerCards);
})
.expect(201);
});
|
Fix: game clean up
|
test/integration/game/game-initialization.parallel.test.js
|
Fix: game clean up
|
<ide><path>est/integration/game/game-initialization.parallel.test.js
<ide> import randomString from 'randomstring';
<ide>
<ide> import userModel from '../../../src/services/user/user-model';
<del>import gameModel from '../../../src/services/game/';
<add>import gameModel from '../../../src/services/game/game-model';
<ide>
<ide> const userStub = {
<ide> email: `${randomString.generate(12)}@test.com`
<ide> };
<add>
<add>const gameStub = {};
<ide>
<ide> test.before('prepare a user', async t => {
<ide> await userModel.remove();
<ide> await userModel.remove({email: userStub.email});
<ide> });
<ide>
<add>test.after('clean up a game', async t => {
<add> await gameModel.remove({_id: gameStub.id});
<add>});
<add>
<ide> test('game: should be initialized', async t => {
<ide> await request
<ide> .post('/games')
<ide> bet: 10
<ide> })
<ide> .expect(res => {
<add> assert.isDefined(res.body.id);
<ide> assert.isDefined(res.body.clientCards);
<ide> assert.isDefined(res.body.dealerCards);
<ide> })
<del> .expect(201);
<add> .expect(201)
<add> .then(res => {
<add> gameStub.id = res.body.id;
<add> });
<ide> });
|
|
Java
|
apache-2.0
|
eae10595fa08e7f66816eaa4e08ff6a699d21dd7
| 0 |
mitonize/okuyama-client-java
|
package mitonize.datastore.okuyama;
import java.nio.ByteBuffer;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class JdkDeflaterCompressor extends Compressor {
private static final int BLOCK_SIZE_DECOMPRESS = 8192;
private static final int BLOCK_SIZE_COMPRESS = 4096;
private static final int POOL_SIZE = 10;
int averageRatio = 4;
ArrayBlockingQueue<Deflater> deflaters;
ArrayBlockingQueue<Inflater> inflaters;
byte[] allocatedBytesCompress = new byte[BLOCK_SIZE_COMPRESS];
byte[] allocatedBytesDecompress = new byte[BLOCK_SIZE_DECOMPRESS];
public JdkDeflaterCompressor() {
deflaters = new ArrayBlockingQueue<>(POOL_SIZE);
inflaters = new ArrayBlockingQueue<>(POOL_SIZE);
registerCompressor();
}
private Deflater getDeflater() {
Deflater deflater = deflaters.poll();
if (deflater != null) {
return deflater;
}
return new Deflater(Deflater.BEST_SPEED);
}
private void recycleDeflater(Deflater deflater) {
deflater.reset();
boolean pooled = deflaters.offer(deflater);
if (!pooled) {
// 返却できなかったら捨てられる。
deflater.end();
}
}
private Inflater getInflater() {
Inflater inflater = inflaters.poll();
if (inflater != null) {
return inflater;
}
return new Inflater();
}
private void recycleInflater(Inflater inflater) {
inflater.reset();
boolean pooled = inflaters.offer(inflater);
if (!pooled) {
// 返却できなかったら捨てられる。
inflater.end();
}
}
@Override
int getCompressorId() {
return 0;
}
public ByteBuffer compress(byte[] serialized) {
return compress(serialized, 0, serialized.length);
}
public ByteBuffer compress(byte[] serialized, int offset, int length) {
Deflater deflater = null;
try {
deflater = getDeflater();
deflater.setInput(serialized, offset, length);
deflater.finish();
int blocks = serialized.length / averageRatio / BLOCK_SIZE_COMPRESS;
blocks = blocks < 1 ? 1: blocks;
byte[] z;
if (blocks > 1) {
z = new byte[BLOCK_SIZE_COMPRESS * blocks];
} else {
z = allocatedBytesCompress;
}
writeMagicBytes(z);
int compressed = 3;
while (!deflater.finished()) {
int remain = z.length - compressed;
int size = deflater.deflate(z, compressed, remain);
remain -= size;
compressed += size;
if (remain < 100) {
byte[] z0 = new byte[z.length + BLOCK_SIZE_COMPRESS];
System.arraycopy(z, 0, z0, 0, z.length);
z = z0;
}
}
return ByteBuffer.wrap(z, 0, compressed);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (deflater != null) {
recycleDeflater(deflater);
}
}
}
public ByteBuffer decompress(byte[] b, int offset, int length) {
int blocks = (length * averageRatio) / BLOCK_SIZE_DECOMPRESS;
blocks = blocks < 1 ? 1: blocks;
byte[] z;
if (blocks > 1) {
z = new byte[BLOCK_SIZE_DECOMPRESS * blocks];
} else {
z = allocatedBytesDecompress;
}
int extracted = 0;
Inflater inflater = null;
try {
inflater = getInflater();
inflater.reset();
inflater.setInput(b, offset+3, length-3);
while (!inflater.finished()) {
int remain = z.length - extracted;
int size = inflater.inflate(z, extracted, remain);
remain -= size;
extracted += size;
if (size == 0) {
break;
}
if (remain < 100) {
byte[] z0 = new byte[z.length + BLOCK_SIZE_DECOMPRESS];
System.arraycopy(z, 0, z0, 0, z.length);
z = z0;
}
}
} catch (DataFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inflater != null) {
recycleInflater(inflater);
}
}
return ByteBuffer.wrap(z, 0, extracted);
}
}
|
src/main/java/mitonize/datastore/okuyama/JdkDeflaterCompressor.java
|
package mitonize.datastore.okuyama;
import java.nio.ByteBuffer;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class JdkDeflaterCompressor extends Compressor {
private static final int BLOCK_SIZE_DECOMPRESS = 8192;
private static final int BLOCK_SIZE_COMPRESS = 4096;
int averageRatio = 4;
Deflater deflater;
Inflater inflater;
byte[] allocatedBytesCompress = new byte[BLOCK_SIZE_COMPRESS];
byte[] allocatedBytesDecompress = new byte[BLOCK_SIZE_DECOMPRESS];
public JdkDeflaterCompressor() {
deflater = new Deflater(Deflater.BEST_SPEED);
inflater = new Inflater();
registerCompressor();
}
@Override
int getCompressorId() {
return 0;
}
public ByteBuffer compress(byte[] serialized) {
return compress(serialized, 0, serialized.length);
}
public ByteBuffer compress(byte[] serialized, int offset, int length) {
try {
Deflater deflater = this.deflater;
deflater.reset();
deflater.setInput(serialized, offset, length);
deflater.finish();
int blocks = serialized.length / averageRatio / BLOCK_SIZE_COMPRESS;
blocks = blocks < 1 ? 1: blocks;
byte[] z;
if (blocks > 1) {
z = new byte[BLOCK_SIZE_COMPRESS * blocks];
} else {
z = allocatedBytesCompress;
}
writeMagicBytes(z);
int compressed = 3;
while (!deflater.finished()) {
int remain = z.length - compressed;
int size = deflater.deflate(z, compressed, remain);
remain -= size;
compressed += size;
if (remain < 100) {
byte[] z0 = new byte[z.length + BLOCK_SIZE_COMPRESS];
System.arraycopy(z, 0, z0, 0, z.length);
z = z0;
}
}
return ByteBuffer.wrap(z, 0, compressed);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public ByteBuffer decompress(byte[] b, int offset, int length) {
Inflater inflater = this.inflater;
inflater.reset();
inflater.setInput(b, offset+3, length-3);
int blocks = (length * averageRatio) / BLOCK_SIZE_DECOMPRESS;
blocks = blocks < 1 ? 1: blocks;
byte[] z;
if (blocks > 1) {
z = new byte[BLOCK_SIZE_DECOMPRESS * blocks];
} else {
z = allocatedBytesDecompress;
}
int extracted = 0;
try {
while (!inflater.finished()) {
int remain = z.length - extracted;
int size = inflater.inflate(z, extracted, remain);
remain -= size;
extracted += size;
if (size == 0) {
break;
}
if (remain < 100) {
byte[] z0 = new byte[z.length + BLOCK_SIZE_DECOMPRESS];
System.arraycopy(z, 0, z0, 0, z.length);
z = z0;
}
}
} catch (DataFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return ByteBuffer.wrap(z, 0, extracted);
}
}
|
Deflater,Inflaterを複数プールするようにした。
|
src/main/java/mitonize/datastore/okuyama/JdkDeflaterCompressor.java
|
Deflater,Inflaterを複数プールするようにした。
|
<ide><path>rc/main/java/mitonize/datastore/okuyama/JdkDeflaterCompressor.java
<ide> package mitonize.datastore.okuyama;
<ide>
<ide> import java.nio.ByteBuffer;
<add>import java.util.concurrent.ArrayBlockingQueue;
<ide> import java.util.zip.DataFormatException;
<ide> import java.util.zip.Deflater;
<ide> import java.util.zip.Inflater;
<ide> public class JdkDeflaterCompressor extends Compressor {
<ide> private static final int BLOCK_SIZE_DECOMPRESS = 8192;
<ide> private static final int BLOCK_SIZE_COMPRESS = 4096;
<add> private static final int POOL_SIZE = 10;
<ide> int averageRatio = 4;
<del> Deflater deflater;
<del> Inflater inflater;
<add>
<add> ArrayBlockingQueue<Deflater> deflaters;
<add> ArrayBlockingQueue<Inflater> inflaters;
<add>
<ide> byte[] allocatedBytesCompress = new byte[BLOCK_SIZE_COMPRESS];
<ide> byte[] allocatedBytesDecompress = new byte[BLOCK_SIZE_DECOMPRESS];
<ide>
<ide> public JdkDeflaterCompressor() {
<del> deflater = new Deflater(Deflater.BEST_SPEED);
<del> inflater = new Inflater();
<add> deflaters = new ArrayBlockingQueue<>(POOL_SIZE);
<add> inflaters = new ArrayBlockingQueue<>(POOL_SIZE);
<ide> registerCompressor();
<ide> }
<add>
<add> private Deflater getDeflater() {
<add> Deflater deflater = deflaters.poll();
<add> if (deflater != null) {
<add> return deflater;
<add> }
<add> return new Deflater(Deflater.BEST_SPEED);
<add> }
<add>
<add> private void recycleDeflater(Deflater deflater) {
<add> deflater.reset();
<add> boolean pooled = deflaters.offer(deflater);
<add> if (!pooled) {
<add> // 返却できなかったら捨てられる。
<add> deflater.end();
<add> }
<add> }
<ide>
<add> private Inflater getInflater() {
<add> Inflater inflater = inflaters.poll();
<add> if (inflater != null) {
<add> return inflater;
<add> }
<add> return new Inflater();
<add> }
<add>
<add> private void recycleInflater(Inflater inflater) {
<add> inflater.reset();
<add> boolean pooled = inflaters.offer(inflater);
<add> if (!pooled) {
<add> // 返却できなかったら捨てられる。
<add> inflater.end();
<add> }
<add> }
<add>
<add>
<ide> @Override
<ide> int getCompressorId() {
<ide> return 0;
<ide> }
<ide>
<ide> public ByteBuffer compress(byte[] serialized, int offset, int length) {
<add> Deflater deflater = null;
<ide> try {
<del> Deflater deflater = this.deflater;
<del> deflater.reset();
<add> deflater = getDeflater();
<ide> deflater.setInput(serialized, offset, length);
<ide> deflater.finish();
<ide>
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
<ide> throw e;
<add> } finally {
<add> if (deflater != null) {
<add> recycleDeflater(deflater);
<add> }
<ide> }
<ide> }
<ide>
<ide> public ByteBuffer decompress(byte[] b, int offset, int length) {
<del> Inflater inflater = this.inflater;
<del> inflater.reset();
<del> inflater.setInput(b, offset+3, length-3);
<del>
<ide> int blocks = (length * averageRatio) / BLOCK_SIZE_DECOMPRESS;
<ide> blocks = blocks < 1 ? 1: blocks;
<ide> byte[] z;
<ide> z = allocatedBytesDecompress;
<ide> }
<ide> int extracted = 0;
<add> Inflater inflater = null;
<ide> try {
<add> inflater = getInflater();
<add> inflater.reset();
<add> inflater.setInput(b, offset+3, length-3);
<add>
<ide> while (!inflater.finished()) {
<ide> int remain = z.length - extracted;
<ide> int size = inflater.inflate(z, extracted, remain);
<ide> e.printStackTrace();
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
<add> } finally {
<add> if (inflater != null) {
<add> recycleInflater(inflater);
<add> }
<ide> }
<ide> return ByteBuffer.wrap(z, 0, extracted);
<ide> }
|
|
Java
|
apache-2.0
|
d06f9ee7c40071a5b47ecad05c7260507527204f
| 0 |
langkilde/epic,langkilde/epic
|
package JavaProject;
import epic.sequences.SemiCRF;
import java.io.*;
import java.util.*;
public class SelectQuery {
/**
* SelectQuery finds the next batch for labeling. It goes through a file and finds the value of the current sentence
* according to the current model
* @param fileName The name of the file from which the sentences in the unlabeled pool are to be read
* @param batchSize The size of the batch that this function is to return
* @param modelChoice Which kind of active learning is active
* @param models If we use vote entropy this contains all the models which vote. If not this list contains only
* one model
* @param threshold If we use adaptive batch size this is the threshold which determines how many sentences we send
* back
* @param informationDensities If information density is used this list contains the similarity scores of each
* sentence
* @return A Batch which contains the best sentences, their corresponding scores and ids.
*/
public Batch SelectQuery(File fileName, int batchSize, String modelChoice, List<SemiCRF<String,String>> models,
double threshold, List<List<Double>> informationDensities) {
List<Double> bestValues = new ArrayList<Double>();
List<Double> randomIDs = new ArrayList<Double>();
List<String> bestSentences = new ArrayList<String>();
double confidenceSum = 0;
List<Double> ids = new ArrayList<>();
List<Double> densities = new ArrayList<>();
double densScore;
if (informationDensities.size()>0){
System.out.println("In SQ, infodens > 0");
ids = informationDensities.get(0);
densities = informationDensities.get(1);
System.out.println("Ids: " + Arrays.toString(ids.subList(0,20).toArray()));
System.out.println("Densities: " + Arrays.toString(densities.subList(0,20).toArray()));
}
double positives = 0.0;
double c = 0.0;
try {
// This will reference one line at a time
String line = null;
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
//Kan behöva läggas till -inf beroende på vilken model vi använder
//double maxValue = Double.NEGATIVE_INFINITY;
//String bestSentence;
double minValue;
int minIndex;
double tmpValue;
double tmpRandomID;
double maxValue = Double.NEGATIVE_INFINITY;
int counter = 1;
int index;
System.out.println("I'm in SelectQuery");
long startTime = System.currentTimeMillis();
System.out.println("**********BATCH SIZE INSIDE***********");
while ((line = bufferedReader.readLine()) != null) {
c++;
if (c / 1000 == Math.floor(c / 1000)) {
System.out.println(c / 1000 + "takes " + (System.currentTimeMillis() - startTime) / 1000 + "s");
System.out.println("Average vote value: " + confidenceSum / c);
}
String randomID = line.substring(line.indexOf("u'random':") + 11);
randomID = randomID.substring(0, randomID.indexOf(", u'"));
String tmpLine = line.substring(line.indexOf("sentence': u") + 13);
tmpLine = tmpLine.substring(0, tmpLine.indexOf(", u'") - 1);
tmpLine = tmpLine.replaceAll("\\s+", " ");
String tmpConll = line.substring(line.indexOf("u'conll': u'") + 12);
tmpConll = tmpConll.substring(0, tmpConll.indexOf(", u'"));
densScore = -1;
if (informationDensities.size()>0){
index = ids.indexOf(Double.parseDouble(randomID));
if (index!= -1){
densScore = densities.get(index);
}
System.out.println("********RandomID********** "+ randomID);
System.out.println("********Index********** "+ index);
}
tmpValue = MethodChoice.getValueMethod(models, modelChoice, tmpLine, tmpConll,densScore);
if (tmpConll.contains("_MALWARE")){
positives++;
}
confidenceSum += tmpValue;
if (informationDensities.size() > 0) {
index = ids.indexOf(Double.parseDouble(randomID));
if (index != -1) {
tmpValue = tmpValue * densities.get(index);
}
}
tmpRandomID = Double.parseDouble(randomID);
if (counter <= batchSize && !bestValues.contains(tmpValue)) {
bestValues.add(tmpValue);
randomIDs.add(tmpRandomID);
bestSentences.add(tmpValue + " " + tmpConll);
counter++;
} else if (!bestValues.contains(tmpValue)) {
minValue = Collections.min(bestValues);
minIndex = bestValues.indexOf(minValue);
if (minValue < tmpValue && !bestValues.contains(tmpValue)) {
bestValues.set(minIndex, tmpValue);
randomIDs.set(minIndex, tmpRandomID);
bestSentences.set(minIndex, tmpValue + " " + tmpConll);
}
}
}
if (threshold > 0) {
return thresholdBatch(bestValues, randomIDs, bestSentences, threshold, positives/c);
}
int loop = randomIDs.size();
if (loop > 5) {
loop = 5;
}
for (int i = 0; i < loop; i++) {
System.out.println(bestValues.get(i));
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
} catch (IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
return new Batch(bestSentences,randomIDs,bestValues,positives/c);
}
/**
* If adaptive batch size is active thresholdBatch is called. It loops over a sorted list of values and chooses
* values until the sum of the values are bigger than the threshold. Hence it returns the best values and their
* corresponding sentences and ids as a Batch object.
* @param bestValues The scores of each sentences
* @param randomIDs The ids of each sentence
* @param bestSentences each sentence
* @param threshold The threshold for the adaptive batch size
* @return A Batch object consisting of the best sentences, their corresponding values and ids.
*/
public Batch thresholdBatch(List<Double> bestValues, List<Double> randomIDs, List<String> bestSentences, double threshold, double perc){
List<Double> sortedIds = new ArrayList<>();
List<Double> sortedValues = new ArrayList<>(bestValues);
List<String> sortedSentences = new ArrayList<>();
Collections.sort(sortedValues);
double positives = 0.0;
int idIndex;
for (int i = 0; i < sortedValues.size();i++){
idIndex = bestValues.indexOf(sortedValues.get(i));
bestValues.set(idIndex,-1000.0);
sortedSentences.add(bestSentences.get(idIndex));
sortedIds.add(randomIDs.get(idIndex));
}
double sum = 0;
int i = sortedValues.size()-1;
List<Double> threshIds = new ArrayList<>();
List<Double> threshValues = new ArrayList<>();
List<String> threshSentences = new ArrayList<>();
while (sum < threshold && i > -1){
threshValues.add(sortedValues.get(i));
threshIds.add(sortedIds.get(i));
threshSentences.add(sortedSentences.get(i));
sum += 1+sortedValues.get(i);
i--;
}
return new Batch(threshSentences,threshIds,threshValues,perc);
}
}
|
src/main/scala/JavaProject/SelectQuery.java
|
package JavaProject;
import epic.sequences.SemiCRF;
import java.io.*;
import java.util.*;
public class SelectQuery {
/**
* SelectQuery finds the next batch for labeling. It goes through a file and finds the value of the current sentence
* according to the current model
* @param fileName The name of the file from which the sentences in the unlabeled pool are to be read
* @param batchSize The size of the batch that this function is to return
* @param modelChoice Which kind of active learning is active
* @param models If we use vote entropy this contains all the models which vote. If not this list contains only
* one model
* @param threshold If we use adaptive batch size this is the threshold which determines how many sentences we send
* back
* @param informationDensities If information density is used this list contains the similarity scores of each
* sentence
* @return A Batch which contains the best sentences, their corresponding scores and ids.
*/
public Batch SelectQuery(File fileName, int batchSize, String modelChoice, List<SemiCRF<String,String>> models,
double threshold, List<List<Double>> informationDensities) {
List<Double> bestValues = new ArrayList<Double>();
List<Double> randomIDs = new ArrayList<Double>();
List<String> bestSentences = new ArrayList<String>();
double confidenceSum = 0;
List<Double> ids = new ArrayList<>();
List<Double> densities = new ArrayList<>();
double densScore;
if (informationDensities.size()>0){
System.out.println("In SQ, infodens > 0");
ids = informationDensities.get(0);
densities = informationDensities.get(1);
System.out.println("Ids: " + Arrays.toString(ids.subList(0,20).toArray()));
System.out.println("Densities: " + Arrays.toString(densities.subList(0,20).toArray()));
}
double positives = 0.0;
double c = 0.0;
try {
// This will reference one line at a time
String line = null;
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
//Kan behöva läggas till -inf beroende på vilken model vi använder
//double maxValue = Double.NEGATIVE_INFINITY;
//String bestSentence;
double minValue;
int minIndex;
double tmpValue;
double tmpRandomID;
double maxValue = Double.NEGATIVE_INFINITY;
int counter = 1;
int index;
System.out.println("I'm in SelectQuery");
long startTime = System.currentTimeMillis();
System.out.println("**********BATCH SIZE INSIDE***********");
while ((line = bufferedReader.readLine()) != null) {
c++;
if (c / 1000 == Math.floor(c / 1000)) {
System.out.println(c / 1000 + "takes " + (System.currentTimeMillis() - startTime) / 1000 + "s");
System.out.println("Average vote value: " + confidenceSum / c);
}
String randomID = line.substring(line.indexOf("u'random':") + 11);
randomID = randomID.substring(0, randomID.indexOf(", u'"));
String tmpLine = line.substring(line.indexOf("sentence': u") + 13);
tmpLine = tmpLine.substring(0, tmpLine.indexOf(", u'") - 1);
tmpLine = tmpLine.replaceAll("\\s+", " ");
String tmpConll = line.substring(line.indexOf("u'conll': u'") + 12);
tmpConll = tmpConll.substring(0, tmpConll.indexOf(", u'"));
densScore = -1;
if (informationDensities.size()>0){
System.out.println("********RandomID********** "+ randomID);
index = ids.indexOf(Double.parseDouble(randomID));
if (index!= -1){
densScore = densities.get(index);
}
}
tmpValue = MethodChoice.getValueMethod(models, modelChoice, tmpLine, tmpConll,densScore);
if (tmpConll.contains("_MALWARE")){
positives++;
}
confidenceSum += tmpValue;
if (informationDensities.size() > 0) {
index = ids.indexOf(Double.parseDouble(randomID));
if (index != -1) {
tmpValue = tmpValue * densities.get(index);
}
}
tmpRandomID = Double.parseDouble(randomID);
if (counter <= batchSize && !bestValues.contains(tmpValue)) {
bestValues.add(tmpValue);
randomIDs.add(tmpRandomID);
bestSentences.add(tmpValue + " " + tmpConll);
counter++;
} else if (!bestValues.contains(tmpValue)) {
minValue = Collections.min(bestValues);
minIndex = bestValues.indexOf(minValue);
if (minValue < tmpValue && !bestValues.contains(tmpValue)) {
bestValues.set(minIndex, tmpValue);
randomIDs.set(minIndex, tmpRandomID);
bestSentences.set(minIndex, tmpValue + " " + tmpConll);
}
}
}
if (threshold > 0) {
return thresholdBatch(bestValues, randomIDs, bestSentences, threshold, positives/c);
}
int loop = randomIDs.size();
if (loop > 5) {
loop = 5;
}
for (int i = 0; i < loop; i++) {
System.out.println(bestValues.get(i));
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
} catch (IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
return new Batch(bestSentences,randomIDs,bestValues,positives/c);
}
/**
* If adaptive batch size is active thresholdBatch is called. It loops over a sorted list of values and chooses
* values until the sum of the values are bigger than the threshold. Hence it returns the best values and their
* corresponding sentences and ids as a Batch object.
* @param bestValues The scores of each sentences
* @param randomIDs The ids of each sentence
* @param bestSentences each sentence
* @param threshold The threshold for the adaptive batch size
* @return A Batch object consisting of the best sentences, their corresponding values and ids.
*/
public Batch thresholdBatch(List<Double> bestValues, List<Double> randomIDs, List<String> bestSentences, double threshold, double perc){
List<Double> sortedIds = new ArrayList<>();
List<Double> sortedValues = new ArrayList<>(bestValues);
List<String> sortedSentences = new ArrayList<>();
Collections.sort(sortedValues);
double positives = 0.0;
int idIndex;
for (int i = 0; i < sortedValues.size();i++){
idIndex = bestValues.indexOf(sortedValues.get(i));
bestValues.set(idIndex,-1000.0);
sortedSentences.add(bestSentences.get(idIndex));
sortedIds.add(randomIDs.get(idIndex));
}
double sum = 0;
int i = sortedValues.size()-1;
List<Double> threshIds = new ArrayList<>();
List<Double> threshValues = new ArrayList<>();
List<String> threshSentences = new ArrayList<>();
while (sum < threshold && i > -1){
threshValues.add(sortedValues.get(i));
threshIds.add(sortedIds.get(i));
threshSentences.add(sortedSentences.get(i));
sum += 1+sortedValues.get(i);
i--;
}
return new Batch(threshSentences,threshIds,threshValues,perc);
}
}
|
Gibbs run
|
src/main/scala/JavaProject/SelectQuery.java
|
Gibbs run
|
<ide><path>rc/main/scala/JavaProject/SelectQuery.java
<ide> tmpConll = tmpConll.substring(0, tmpConll.indexOf(", u'"));
<ide> densScore = -1;
<ide> if (informationDensities.size()>0){
<add> index = ids.indexOf(Double.parseDouble(randomID));
<add> if (index!= -1){
<add> densScore = densities.get(index);
<add> }
<ide> System.out.println("********RandomID********** "+ randomID);
<del> index = ids.indexOf(Double.parseDouble(randomID));
<del> if (index!= -1){
<del> densScore = densities.get(index);
<del> }
<add> System.out.println("********Index********** "+ index);
<ide> }
<ide> tmpValue = MethodChoice.getValueMethod(models, modelChoice, tmpLine, tmpConll,densScore);
<ide> if (tmpConll.contains("_MALWARE")){
|
|
Java
|
apache-2.0
|
896f63a3c38f92b34c0df0fb6eb9379eb83580e8
| 0 |
JasonFengHot/ExoPlayerSource,ebr11/ExoPlayer,tntcrowd/ExoPlayer,tntcrowd/ExoPlayer,androidx/media,michalliu/ExoPlayer,MaTriXy/ExoPlayer,superbderrick/ExoPlayer,jeoliva/ExoPlayer,jeoliva/ExoPlayer,KiminRyu/ExoPlayer,saki4510t/ExoPlayer,KiminRyu/ExoPlayer,amzn/exoplayer-amazon-port,JasonFengHot/ExoPlayerSource,amzn/exoplayer-amazon-port,androidx/media,google/ExoPlayer,superbderrick/ExoPlayer,michalliu/ExoPlayer,stari4ek/ExoPlayer,zhouweiguo2017/ExoPlayer,stari4ek/ExoPlayer,saki4510t/ExoPlayer,ened/ExoPlayer,google/ExoPlayer,amzn/exoplayer-amazon-port,kiall/ExoPlayer,KiminRyu/ExoPlayer,MaTriXy/ExoPlayer,kiall/ExoPlayer,ened/ExoPlayer,superbderrick/ExoPlayer,tntcrowd/ExoPlayer,jeoliva/ExoPlayer,androidx/media,JasonFengHot/ExoPlayerSource,stari4ek/ExoPlayer,google/ExoPlayer,ebr11/ExoPlayer,saki4510t/ExoPlayer,MaTriXy/ExoPlayer,zhouweiguo2017/ExoPlayer,zhouweiguo2017/ExoPlayer,michalliu/ExoPlayer,ened/ExoPlayer,kiall/ExoPlayer,ebr11/ExoPlayer
|
/*
* 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.android.exoplayer2.extractor.flv;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.extractor.TrackOutput;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.NalUnitUtil;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.video.AvcConfig;
/**
* Parses video tags from an FLV stream and extracts H.264 nal units.
*/
/* package */ final class VideoTagPayloadReader extends TagPayloadReader {
// Video codec.
private static final int VIDEO_CODEC_AVC = 7;
// Frame types.
private static final int VIDEO_FRAME_KEYFRAME = 1;
private static final int VIDEO_FRAME_VIDEO_INFO = 5;
// Packet types.
private static final int AVC_PACKET_TYPE_SEQUENCE_HEADER = 0;
private static final int AVC_PACKET_TYPE_AVC_NALU = 1;
// Temporary arrays.
private final ParsableByteArray nalStartCode;
private final ParsableByteArray nalLength;
private int nalUnitLengthFieldLength;
// State variables.
private boolean hasOutputFormat;
private int frameType;
/**
* @param output A {@link TrackOutput} to which samples should be written.
*/
public VideoTagPayloadReader(TrackOutput output) {
super(output);
nalStartCode = new ParsableByteArray(NalUnitUtil.NAL_START_CODE);
nalLength = new ParsableByteArray(4);
}
@Override
public void seek() {
// Do nothing.
}
@Override
protected boolean parseHeader(ParsableByteArray data) throws UnsupportedFormatException {
int header = data.readUnsignedByte();
int frameType = (header >> 4) & 0x0F;
int videoCodec = (header & 0x0F);
// Support just H.264 encoded content.
if (videoCodec != VIDEO_CODEC_AVC) {
throw new UnsupportedFormatException("Video format not supported: " + videoCodec);
}
this.frameType = frameType;
return (frameType != VIDEO_FRAME_VIDEO_INFO);
}
@Override
protected void parsePayload(ParsableByteArray data, long timeUs) throws ParserException {
int packetType = data.readUnsignedByte();
int compositionTimeMs = data.readUnsignedInt24();
timeUs += compositionTimeMs * 1000L;
// Parse avc sequence header in case this was not done before.
if (packetType == AVC_PACKET_TYPE_SEQUENCE_HEADER && !hasOutputFormat) {
ParsableByteArray videoSequence = new ParsableByteArray(new byte[data.bytesLeft()]);
data.readBytes(videoSequence.data, 0, data.bytesLeft());
AvcConfig avcConfig = AvcConfig.parse(videoSequence);
nalUnitLengthFieldLength = avcConfig.nalUnitLengthFieldLength;
// Construct and output the format.
Format format = Format.createVideoSampleFormat(null, MimeTypes.VIDEO_H264, null,
Format.NO_VALUE, Format.NO_VALUE, avcConfig.width, avcConfig.height, Format.NO_VALUE,
avcConfig.initializationData, Format.NO_VALUE, avcConfig.pixelWidthAspectRatio, null);
output.format(format);
hasOutputFormat = true;
} else if (packetType == AVC_PACKET_TYPE_AVC_NALU && hasOutputFormat) {
// TODO: Deduplicate with Mp4Extractor.
// Zero the top three bytes of the array that we'll use to decode nal unit lengths, in case
// they're only 1 or 2 bytes long.
byte[] nalLengthData = nalLength.data;
nalLengthData[0] = 0;
nalLengthData[1] = 0;
nalLengthData[2] = 0;
if(nalUnitLengthFieldLength == 0) nalUnitLengthFieldLength = 4;
int nalUnitLengthFieldLengthDiff = 4 - nalUnitLengthFieldLength;
// NAL units are length delimited, but the decoder requires start code delimited units.
// Loop until we've written the sample to the track output, replacing length delimiters with
// start codes as we encounter them.
int bytesWritten = 0;
int bytesToWrite;
while (data.bytesLeft() > 0) {
// Read the NAL length so that we know where we find the next one.
data.readBytes(nalLength.data, nalUnitLengthFieldLengthDiff, nalUnitLengthFieldLength);
nalLength.setPosition(0);
bytesToWrite = nalLength.readUnsignedIntToInt();
// Write a start code for the current NAL unit.
nalStartCode.setPosition(0);
output.sampleData(nalStartCode, 4);
bytesWritten += 4;
// Write the payload of the NAL unit.
output.sampleData(data, bytesToWrite);
bytesWritten += bytesToWrite;
}
output.sampleMetadata(timeUs, frameType == VIDEO_FRAME_KEYFRAME ? C.BUFFER_FLAG_KEY_FRAME : 0,
bytesWritten, 0, null);
}
}
}
|
library/core/src/main/java/com/google/android/exoplayer2/extractor/flv/VideoTagPayloadReader.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.android.exoplayer2.extractor.flv;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.extractor.TrackOutput;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.NalUnitUtil;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.video.AvcConfig;
/**
* Parses video tags from an FLV stream and extracts H.264 nal units.
*/
/* package */ final class VideoTagPayloadReader extends TagPayloadReader {
// Video codec.
private static final int VIDEO_CODEC_AVC = 7;
// Frame types.
private static final int VIDEO_FRAME_KEYFRAME = 1;
private static final int VIDEO_FRAME_VIDEO_INFO = 5;
// Packet types.
private static final int AVC_PACKET_TYPE_SEQUENCE_HEADER = 0;
private static final int AVC_PACKET_TYPE_AVC_NALU = 1;
// Temporary arrays.
private final ParsableByteArray nalStartCode;
private final ParsableByteArray nalLength;
private int nalUnitLengthFieldLength;
// State variables.
private boolean hasOutputFormat;
private int frameType;
/**
* @param output A {@link TrackOutput} to which samples should be written.
*/
public VideoTagPayloadReader(TrackOutput output) {
super(output);
nalStartCode = new ParsableByteArray(NalUnitUtil.NAL_START_CODE);
nalLength = new ParsableByteArray(4);
}
@Override
public void seek() {
// Do nothing.
}
@Override
protected boolean parseHeader(ParsableByteArray data) throws UnsupportedFormatException {
int header = data.readUnsignedByte();
int frameType = (header >> 4) & 0x0F;
int videoCodec = (header & 0x0F);
// Support just H.264 encoded content.
if (videoCodec != VIDEO_CODEC_AVC) {
throw new UnsupportedFormatException("Video format not supported: " + videoCodec);
}
this.frameType = frameType;
return (frameType != VIDEO_FRAME_VIDEO_INFO);
}
@Override
protected void parsePayload(ParsableByteArray data, long timeUs) throws ParserException {
int packetType = data.readUnsignedByte();
int compositionTimeMs = data.readUnsignedInt24();
timeUs += compositionTimeMs * 1000L;
// Parse avc sequence header in case this was not done before.
if (packetType == AVC_PACKET_TYPE_SEQUENCE_HEADER && !hasOutputFormat) {
ParsableByteArray videoSequence = new ParsableByteArray(new byte[data.bytesLeft()]);
data.readBytes(videoSequence.data, 0, data.bytesLeft());
AvcConfig avcConfig = AvcConfig.parse(videoSequence);
nalUnitLengthFieldLength = avcConfig.nalUnitLengthFieldLength;
// Construct and output the format.
Format format = Format.createVideoSampleFormat(null, MimeTypes.VIDEO_H264, null,
Format.NO_VALUE, Format.NO_VALUE, avcConfig.width, avcConfig.height, Format.NO_VALUE,
avcConfig.initializationData, Format.NO_VALUE, avcConfig.pixelWidthAspectRatio, null);
output.format(format);
hasOutputFormat = true;
} else if (packetType == AVC_PACKET_TYPE_AVC_NALU) {
// TODO: Deduplicate with Mp4Extractor.
// Zero the top three bytes of the array that we'll use to decode nal unit lengths, in case
// they're only 1 or 2 bytes long.
byte[] nalLengthData = nalLength.data;
nalLengthData[0] = 0;
nalLengthData[1] = 0;
nalLengthData[2] = 0;
int nalUnitLengthFieldLengthDiff = 4 - nalUnitLengthFieldLength;
// NAL units are length delimited, but the decoder requires start code delimited units.
// Loop until we've written the sample to the track output, replacing length delimiters with
// start codes as we encounter them.
int bytesWritten = 0;
int bytesToWrite;
while (data.bytesLeft() > 0) {
// Read the NAL length so that we know where we find the next one.
data.readBytes(nalLength.data, nalUnitLengthFieldLengthDiff, nalUnitLengthFieldLength);
nalLength.setPosition(0);
bytesToWrite = nalLength.readUnsignedIntToInt();
// Write a start code for the current NAL unit.
nalStartCode.setPosition(0);
output.sampleData(nalStartCode, 4);
bytesWritten += 4;
// Write the payload of the NAL unit.
output.sampleData(data, bytesToWrite);
bytesWritten += bytesToWrite;
}
output.sampleMetadata(timeUs, frameType == VIDEO_FRAME_KEYFRAME ? C.BUFFER_FLAG_KEY_FRAME : 0,
bytesWritten, 0, null);
}
}
}
|
Fixes OOM that can occur from reading first NAL packet before sequence header
|
library/core/src/main/java/com/google/android/exoplayer2/extractor/flv/VideoTagPayloadReader.java
|
Fixes OOM that can occur from reading first NAL packet before sequence header
|
<ide><path>ibrary/core/src/main/java/com/google/android/exoplayer2/extractor/flv/VideoTagPayloadReader.java
<ide> avcConfig.initializationData, Format.NO_VALUE, avcConfig.pixelWidthAspectRatio, null);
<ide> output.format(format);
<ide> hasOutputFormat = true;
<del> } else if (packetType == AVC_PACKET_TYPE_AVC_NALU) {
<add> } else if (packetType == AVC_PACKET_TYPE_AVC_NALU && hasOutputFormat) {
<ide> // TODO: Deduplicate with Mp4Extractor.
<ide> // Zero the top three bytes of the array that we'll use to decode nal unit lengths, in case
<ide> // they're only 1 or 2 bytes long.
<ide> nalLengthData[0] = 0;
<ide> nalLengthData[1] = 0;
<ide> nalLengthData[2] = 0;
<add> if(nalUnitLengthFieldLength == 0) nalUnitLengthFieldLength = 4;
<ide> int nalUnitLengthFieldLengthDiff = 4 - nalUnitLengthFieldLength;
<ide> // NAL units are length delimited, but the decoder requires start code delimited units.
<ide> // Loop until we've written the sample to the track output, replacing length delimiters with
|
|
JavaScript
|
apache-2.0
|
cc6c8028dc4c7fec824eaa492fe0e5c156c6df3a
| 0 |
marianosimone/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,lernae/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,levaly/zeroclickinfo-spice,deserted/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,soleo/zeroclickinfo-spice,lerna/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,P71/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,levaly/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,loganom/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,sevki/zeroclickinfo-spice,stennie/zeroclickinfo-spice,sevki/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,levaly/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,P71/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,ppant/zeroclickinfo-spice,P71/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,soleo/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,loganom/zeroclickinfo-spice,loganom/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,imwally/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,imwally/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,digit4lfa1l/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,P71/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,mayo/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,ppant/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lerna/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,imwally/zeroclickinfo-spice,stennie/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,imwally/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,levaly/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,mayo/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,mayo/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,lernae/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,mohan08p/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,soleo/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,loganom/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,lernae/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,lernae/zeroclickinfo-spice,lerna/zeroclickinfo-spice,mayo/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,Faiz7412/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,ppant/zeroclickinfo-spice,deserted/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,stennie/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,levaly/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,echosa/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,echosa/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,soleo/zeroclickinfo-spice,deserted/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,hshackathons/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,rubinovitz/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,soleo/zeroclickinfo-spice,dachinzo/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,evejweinberg/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,levaly/zeroclickinfo-spice,jyounker/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,alexandernext/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,soleo/zeroclickinfo-spice,Queeniebee/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,lernae/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,ColasBroux/zeroclickinfo-spice,lw7360/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,imwally/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,sevki/zeroclickinfo-spice,bdjnk/zeroclickinfo-spice,deserted/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Dwaligon/zeroclickinfo-spice,echosa/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,ppant/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,deserted/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,sevki/zeroclickinfo-spice,AcriCAA/zeroclickinfo-spice,lerna/zeroclickinfo-spice,claytonspinner/zeroclickinfo-spice,echosa/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,navjotahuja92/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,stevenmg/zeroclickinfo-spice,stennie/zeroclickinfo-spice,dheeraj143/zeroclickinfo-spice,toenu23/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,lerna/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,gautamkrishnar/zeroclickinfo-spice,deserted/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice
|
(function (env) {
"use strict";
function getUrl(watchable) {
return 'http://gowatchit.com' + (watchable.url ? watchable.url : "");
}
env.ddg_spice_go_watch_it = function(api_result) {
// Check if the data that we get is sane.
if (!api_result || api_result.error || !DDG.getProperty(api_result, 'search.movies') ||
!DDG.getProperty(api_result, 'search.shows') || api_result.search.movies.length === 0 &&
api_result.search.shows.length === 0) {
return Spice.failed('go_watch_it');
}
// Get the first result.
// This probably shouldn't be the way to do it, but it works for now.
var movie = api_result.search.movies[0],
show = api_result.search.shows[0],
watchable = movie || show;
var streaming_providers = {
"YouTube": 1,
"Google Play": 1
};
Spice.add({
id: "go_watch_it",
name: "How to Watch",
data: watchable.availabilities,
meta: {
sourceName: 'GoWatchIt',
sourceUrl: getUrl(watchable),
itemType: 'Availabilities'
},
normalize: function(item) {
// If the provider is in this hash, it means that they provide
// streaming if they don't buy or sell stuff.
if(item.provider_name in streaming_providers &&
item.buy_line === "" && item.rent_line === "") {
item.buy_line = "Available for Streaming";
}
// Change the format line to match the other tiles.
if(item.format_line === "DVD & Blu-ray") {
item.format_line = "DVD / Blu-ray";
}
return {
url: item.watch_now_url
}
},
templates: {
item: 'base_item',
options: {
content: Spice.go_watch_it.content
}
}
});
};
Spice.registerHelper("buyOrRent", function(buy_line, rent_line, options) {
if(buy_line && buy_line !== "") {
this.line = buy_line;
return options.fn(this);
}
this.line = rent_line;
return options.fn(this);
});
// Check to see if both buy_line and rent_line are present.
Spice.registerHelper("gwi_ifHasBothBuyAndRent", function(buy_line, rent_line, options) {
if (buy_line && buy_line !== "" && rent_line && rent_line !== "") {
return options.fn(this);
} else {
return options.inverse(this);
}
});
// Check to see if the buy_line/rent_line includes a price.
// This is because some provider formats (like Netflix) have
// 'Included with Subscription' in their buy line.
Spice.registerHelper("gwi_ifHasPrice", function(line, options) {
if (line.split("$").length > 1) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
// Grab dollar amount from 'Rent from $X.XX' string.
Spice.registerHelper("gwi_price", function(line, options) {
var strings = line.split("$")
return "$" + strings[strings.length - 1]
});
// Get the class for the footer element based on whether or not both the buy_line
// and rent_line are present.
Spice.registerHelper("gwi_footerClass", function(buy_line, rent_line, options) {
var klass = 'gwi-footer';
if (buy_line && buy_line != '' && rent_line && rent_line != '') {
klass += ' double';
}
return klass;
});
}(this));
|
share/spice/go_watch_it/go_watch_it.js
|
(function (env) {
"use strict";
function getAlertAvailability(watchable) {
var avail = {
provider_format_logos: {
dark: 'http://s3.amazonaws.com/gowatchit/partner_logos/gowatchit_logo_white_bars.jpg'
},
buy_line: watchable.title,
format_line: "Set Alerts",
watch_now_url: getUrl(watchable)
}
return avail;
}
function getUrl(watchable) {
return 'http://gowatchit.com' + (watchable.url ? watchable.url : "");
}
env.ddg_spice_go_watch_it = function(api_result) {
// Check if the data that we get is sane.
if (!api_result || api_result.error || !DDG.getProperty(api_result, 'search.movies') ||
!DDG.getProperty(api_result, 'search.shows') || api_result.search.movies.length === 0 &&
api_result.search.shows.length === 0) {
return Spice.failed('go_watch_it');
}
// Get the first result.
// This probably shouldn't be the way to do it, but it works for now.
var movie = api_result.search.movies[0],
show = api_result.search.shows[0],
watchable = movie || show;
watchable.availabilities.push(getAlertAvailability(watchable));
var streaming_providers = {
"YouTube": 1,
"Google Play": 1
};
Spice.add({
id: "go_watch_it",
name: "How to Watch",
data: watchable.availabilities,
meta: {
sourceName: 'GoWatchIt',
sourceUrl: getUrl(watchable),
itemType: 'Availabilities'
},
normalize: function(item) {
// If the provider is in this hash, it means that they provide
// streaming if they don't buy or sell stuff.
if(item.provider_name in streaming_providers &&
item.buy_line === "" && item.rent_line === "") {
item.buy_line = "Available for Streaming";
}
// Change the format line to match the other tiles.
if(item.format_line === "DVD & Blu-ray") {
item.format_line = "DVD / Blu-ray";
}
return {
url: item.watch_now_url
}
},
templates: {
item: 'base_item',
options: {
content: Spice.go_watch_it.content
}
}
});
};
Spice.registerHelper("buyOrRent", function(buy_line, rent_line, options) {
if(buy_line && buy_line !== "") {
this.line = buy_line;
return options.fn(this);
}
this.line = rent_line;
return options.fn(this);
});
// Check to see if both buy_line and rent_line are present.
Spice.registerHelper("gwi_ifHasBothBuyAndRent", function(buy_line, rent_line, options) {
if (buy_line && buy_line !== "" && rent_line && rent_line !== "") {
return options.fn(this);
} else {
return options.inverse(this);
}
});
// Check to see if the buy_line/rent_line includes a price.
// This is because some provider formats (like Netflix) have
// 'Included with Subscription' in their buy line.
Spice.registerHelper("gwi_ifHasPrice", function(line, options) {
if (line.split("$").length > 1) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
// Grab dollar amount from 'Rent from $X.XX' string.
Spice.registerHelper("gwi_price", function(line, options) {
var strings = line.split("$")
return "$" + strings[strings.length - 1]
});
// Get the class for the footer element based on whether or not both the buy_line
// and rent_line are present.
Spice.registerHelper("gwi_footerClass", function(buy_line, rent_line, options) {
var klass = 'gwi-footer';
if (buy_line && buy_line != '' && rent_line && rent_line != '') {
klass += ' double';
}
return klass;
});
}(this));
|
GoWatchIt: Remove the "Alert" tile.
|
share/spice/go_watch_it/go_watch_it.js
|
GoWatchIt: Remove the "Alert" tile.
|
<ide><path>hare/spice/go_watch_it/go_watch_it.js
<ide> (function (env) {
<ide> "use strict";
<del>
<del> function getAlertAvailability(watchable) {
<del> var avail = {
<del> provider_format_logos: {
<del> dark: 'http://s3.amazonaws.com/gowatchit/partner_logos/gowatchit_logo_white_bars.jpg'
<del> },
<del> buy_line: watchable.title,
<del> format_line: "Set Alerts",
<del> watch_now_url: getUrl(watchable)
<del> }
<del> return avail;
<del> }
<ide>
<ide> function getUrl(watchable) {
<ide> return 'http://gowatchit.com' + (watchable.url ? watchable.url : "");
<ide> var movie = api_result.search.movies[0],
<ide> show = api_result.search.shows[0],
<ide> watchable = movie || show;
<del>
<del> watchable.availabilities.push(getAlertAvailability(watchable));
<ide>
<ide> var streaming_providers = {
<ide> "YouTube": 1,
|
|
Java
|
apache-2.0
|
18ca5aecce63b95787f5f5cd57544365c49e80ae
| 0 |
jgrunert/Microservice-Fault-Injection,orcas-elite/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,orcas-elite/Microservice-Fault-Injection,orcas-elite/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection,jgrunert/Microservice-Fault-Injection
|
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.UUID;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import proxy.Proxy;
import proxycontrol.MasterHeartbeatSender;
import proxycontrol.MetricsManager;
import proxycontrol.ProxyControl;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static final String DbName = "ProxyMetrics";
public static void main(String... args) throws Exception {
if (args.length < 6) {
showHelp();
return;
}
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
logger.info("--- Start Network interfaces ---");
for (NetworkInterface netint : Collections.list(nets))
logInterfaceInformation(netint);
logger.info("--- End Network interfaces ---");
Proxy proxy = null;
Server proxyControlServer = null;
try {
final int controlPort = Integer.parseInt(args[0]);
final int proxyPort = Integer.parseInt(args[1]);
final String proxyTo = args[2];
final String proxyTag = args[3];
final String masterUrl = args[4];
final String influxdbUrl = args[5];
final String proxyUuid = UUID.randomUUID().toString();
logger.info("Starting proxy " + proxyTag + "_" + proxyUuid);
// Try to connect to influxdb
final InfluxDB influxDB = connectToDatabase(influxdbUrl);
// Start proxy
logger.info("Proxy starting on port " + proxyPort);
proxy = Proxy.startProxy(proxyPort, controlPort, proxyTo, proxyTag, proxyUuid);
// Start metrics
MetricsManager metricsManager = null;
if(influxDB != null) {
logger.info("Starting MetricsManager to influxDb");
metricsManager = new MetricsManager(proxyTag, proxyUuid, influxDB, proxy, DbName);
}
else {
logger.error("Unable to start MetricsManager without influxDb connection");
}
// Start control server
ResourceConfig config = new ResourceConfig();
config.packages("proxycontrol");
ServletHolder servlet = new ServletHolder(new ServletContainer(config));
logger.info("Control server starting on port " + controlPort);
proxyControlServer = new Server(controlPort);
ServletContextHandler context = new ServletContextHandler(proxyControlServer, "/*");
context.addServlet(servlet, "/*");
proxyControlServer.start();
ProxyControl.setup(proxy, metricsManager);
// Start master message sender
new MasterHeartbeatSender(proxy, masterUrl);
proxy.joinProxy();
} catch (Exception e) {
logger.error("MAIN exception", e);
showHelp();
} finally {
if (proxyControlServer != null)
proxyControlServer.destroy();
if (proxy != null)
proxy.destroy();
}
}
static void logInterfaceInformation(NetworkInterface netint) throws SocketException {
StringBuilder sb = new StringBuilder();
sb.append(netint.getDisplayName() + "(" + netint.getName() + "): ");
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
sb.append(inetAddress + ", ");
}
logger.info(sb.toString());
}
private static InfluxDB connectToDatabase(String influxdbUrl) {
try {
// Connect to influxdb database
logger.info("Start connecting to InfluxDB");
InfluxDB influxDB = InfluxDBFactory.connect(influxdbUrl, "root", "root");
String dbName = DbName;
influxDB.createDatabase(dbName);
logger.info("Connected to InfluxDB");
return influxDB;
} catch (Exception e) {
logger.error("connectToDatabase exception", e);
return null;
}
}
private static void showHelp() {
System.out.println("Usage: [control-port] [proxy-listen-port] [proxyTo] [proxy-id] [master-url] [influxdb-url]");
System.out.println("Example: 8089 8090 http://0.0.0.0:8080/ ProxyForDatabase http://0.0.0.0:8080/ http://172.17.0.2:8086/");
}
}
|
jproxy/src/main/java/Main.java
|
import java.util.UUID;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.influxdb.InfluxDB;
import org.influxdb.InfluxDBFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import proxy.Proxy;
import proxycontrol.MasterHeartbeatSender;
import proxycontrol.MetricsManager;
import proxycontrol.ProxyControl;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static final String DbName = "ProxyMetrics";
public static void main(String... args) throws Exception {
if (args.length < 6) {
showHelp();
return;
}
Proxy proxy = null;
Server proxyControlServer = null;
try {
final int controlPort = Integer.parseInt(args[0]);
final int proxyPort = Integer.parseInt(args[1]);
final String proxyTo = args[2];
final String proxyTag = args[3];
final String masterUrl = args[4];
final String influxdbUrl = args[5];
final String proxyUuid = UUID.randomUUID().toString();
logger.info("Starting proxy " + proxyTag + "_" + proxyUuid);
// Try to connect to influxdb
final InfluxDB influxDB = connectToDatabase(influxdbUrl);
// Start proxy
logger.info("Proxy starting on port " + proxyPort);
proxy = Proxy.startProxy(proxyPort, controlPort, proxyTo, proxyTag, proxyUuid);
// Start metrics
MetricsManager metricsManager = null;
if(influxDB != null) {
logger.info("Starting MetricsManager to influxDb");
metricsManager = new MetricsManager(proxyTag, proxyUuid, influxDB, proxy, DbName);
}
else {
logger.error("Unable to start MetricsManager without influxDb connection");
}
// Start control server
ResourceConfig config = new ResourceConfig();
config.packages("proxycontrol");
ServletHolder servlet = new ServletHolder(new ServletContainer(config));
logger.info("Control server starting on port " + controlPort);
proxyControlServer = new Server(controlPort);
ServletContextHandler context = new ServletContextHandler(proxyControlServer, "/*");
context.addServlet(servlet, "/*");
proxyControlServer.start();
ProxyControl.setup(proxy, metricsManager);
// Start master message sender
new MasterHeartbeatSender(proxy, masterUrl);
proxy.joinProxy();
} catch (Exception e) {
logger.error("MAIN exception", e);
showHelp();
} finally {
if (proxyControlServer != null)
proxyControlServer.destroy();
if (proxy != null)
proxy.destroy();
}
}
private static InfluxDB connectToDatabase(String influxdbUrl) {
try {
// Connect to influxdb database
logger.info("Start connecting to InfluxDB");
InfluxDB influxDB = InfluxDBFactory.connect(influxdbUrl, "root", "root");
String dbName = DbName;
influxDB.createDatabase(dbName);
logger.info("Connected to InfluxDB");
return influxDB;
} catch (Exception e) {
logger.error("connectToDatabase exception", e);
return null;
}
}
private static void showHelp() {
System.out.println("Usage: [control-port] [proxy-listen-port] [proxyTo] [proxy-id] [master-url] [influxdb-url]");
System.out.println("Example: 8089 8090 http://0.0.0.0:8080/ ProxyForDatabase http://0.0.0.0:8080/ http://172.17.0.2:8086/");
}
}
|
Proxies logging netinterfaces
|
jproxy/src/main/java/Main.java
|
Proxies logging netinterfaces
|
<ide><path>proxy/src/main/java/Main.java
<ide>
<add>import java.net.InetAddress;
<add>import java.net.NetworkInterface;
<add>import java.net.SocketException;
<add>import java.util.Collections;
<add>import java.util.Enumeration;
<ide> import java.util.UUID;
<ide>
<ide> import org.eclipse.jetty.server.Server;
<ide> showHelp();
<ide> return;
<ide> }
<add>
<add> Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
<add> logger.info("--- Start Network interfaces ---");
<add> for (NetworkInterface netint : Collections.list(nets))
<add> logInterfaceInformation(netint);
<add> logger.info("--- End Network interfaces ---");
<ide>
<ide> Proxy proxy = null;
<ide> Server proxyControlServer = null;
<ide> }
<ide> }
<ide>
<add> static void logInterfaceInformation(NetworkInterface netint) throws SocketException {
<add> StringBuilder sb = new StringBuilder();
<add> sb.append(netint.getDisplayName() + "(" + netint.getName() + "): ");
<add> Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
<add> for (InetAddress inetAddress : Collections.list(inetAddresses)) {
<add> sb.append(inetAddress + ", ");
<add> }
<add> logger.info(sb.toString());
<add> }
<add>
<ide> private static InfluxDB connectToDatabase(String influxdbUrl) {
<ide> try {
<ide> // Connect to influxdb database
|
|
JavaScript
|
apache-2.0
|
768c2109ab2d5ddb98a1d521fb74b5e508a3ee07
| 0 |
spinnaker/deck,icfantv/deck,ajordens/deck,ajordens/deck,icfantv/deck,spinnaker/deck,duftler/deck,spinnaker/deck,sgarlick987/deck,icfantv/deck,sgarlick987/deck,duftler/deck,ajordens/deck,duftler/deck,icfantv/deck,spinnaker/deck,duftler/deck,sgarlick987/deck,ajordens/deck,sgarlick987/deck
|
'use strict';
const angular = require('angular');
import _ from 'lodash';
import { AuthenticationService } from 'core/authentication';
import { Registry } from 'core/registry';
import { SETTINGS } from 'core/config/settings';
import { UrlParser } from 'core/navigation';
import { AppNotificationsService } from 'core/notification/AppNotificationsService';
import { PipelineTemplateReader } from 'core/pipeline/config/templates/PipelineTemplateReader';
import { PipelineTemplateV2Service } from 'core/pipeline';
import { STAGE_MANUAL_COMPONENTS } from './stageManualComponents.component';
import { TRIGGER_TEMPLATE } from './triggerTemplate.component';
import { ARTIFACT_LIST } from '../status/artifactList.component';
import './manualPipelineExecution.less';
module.exports = angular
.module('spinnaker.core.pipeline.manualPipelineExecution.controller', [
require('angular-ui-bootstrap'),
ARTIFACT_LIST,
TRIGGER_TEMPLATE,
STAGE_MANUAL_COMPONENTS,
])
.controller('ManualPipelineExecutionCtrl', [
'$scope',
'$uibModalInstance',
'pipeline',
'application',
'trigger',
function($scope, $uibModalInstance, pipeline, application, trigger) {
let applicationNotifications = [];
let pipelineNotifications = [];
this.hiddenParameters = new Set();
this.notificationTooltip = require('./notifications.tooltip.html');
AppNotificationsService.getNotificationsForApplication(application.name).then(notifications => {
Object.keys(notifications)
.sort()
.filter(k => Array.isArray(notifications[k]))
.forEach(type => {
notifications[type].forEach(notification => {
applicationNotifications.push(notification);
});
});
synchronizeNotifications();
});
let user = AuthenticationService.getAuthenticatedUser();
let synchronizeNotifications = () => {
this.notifications = applicationNotifications.concat(pipelineNotifications);
};
this.getNotifications = () => {
return _.has(this.command, 'pipeline.notifications')
? this.command.pipeline.notifications.concat(applicationNotifications)
: applicationNotifications;
};
let userEmail = user.authenticated && user.name.includes('@') ? user.name : null;
this.command = {
pipeline: pipeline,
trigger: null,
dryRun: false,
notificationEnabled: false,
notification: {
type: 'email',
address: userEmail,
when: ['pipeline.complete', 'pipeline.failed'],
},
};
this.dryRunEnabled = SETTINGS.feature.dryRunEnabled;
// Poor react setState
const updateCommand = () => {
$scope.$applyAsync(() => {
this.command = _.cloneDeep(this.command);
});
};
let addTriggers = () => {
let pipeline = this.command.pipeline;
if (!pipeline || !pipeline.triggers || !pipeline.triggers.length) {
this.triggers = null;
this.command.trigger = null;
return;
}
this.triggers = pipeline.triggers
.filter(t => Registry.pipeline.hasManualExecutionComponentForTriggerType(t.type))
.map(t => {
let copy = _.clone(t);
copy.description = '...'; // placeholder
Registry.pipeline
.getManualExecutionComponentForTriggerType(t.type)
.formatLabel(t)
.then(label => (copy.description = label));
return copy;
});
if (trigger && trigger.type === 'manual' && this.triggers.length) {
trigger.type = this.triggers[0].type;
}
const suppliedTriggerHasManualComponent =
trigger && Registry.pipeline.hasManualExecutionComponentForTriggerType(trigger.type);
if (suppliedTriggerHasManualComponent) {
Registry.pipeline
.getManualExecutionComponentForTriggerType(trigger.type)
.formatLabel(trigger)
.then(label => (trigger.description = label));
// If the trigger has a manual component, we don't want to also explicitly
// send along the artifacts from the last run, as the manual component will
// populate enough information (ex: build number, docker tag) to re-inflate
// these on a subsequent run.
trigger.artifacts = [];
}
if (trigger) {
// Find the pipeline.trigger that matches trigger (the trigger from the execution being re-run)
this.command.trigger = this.triggers.find(t =>
Object.keys(t)
.filter(k => k !== 'description')
.every(k => t[k] === trigger[k]),
);
// If we found a match, rehydrate it with everything from trigger, otherwise just default back to setting it to trigger
this.command.trigger = this.command.trigger ? Object.assign(this.command.trigger, trigger) : trigger;
} else {
this.command.trigger = _.head(this.triggers);
}
};
const updatePipelinePlan = pipeline => {
if (pipeline.type === 'templatedPipeline' && (pipeline.stages === undefined || pipeline.stages.length === 0)) {
PipelineTemplateReader.getPipelinePlan(pipeline)
.then(plan => (this.stageComponents = getManualExecutionComponents(plan.stages)))
.catch(() => getManualExecutionComponents(pipeline.stages));
} else {
this.stageComponents = getManualExecutionComponents(pipeline.stages);
}
};
const getManualExecutionComponents = stages => {
const additionalComponents = stages.map(stage => Registry.pipeline.getManualExecutionComponentForStage(stage));
return _.uniq(_.compact(additionalComponents));
};
/**
* Controller API
*/
this.triggerUpdated = trigger => {
let command = this.command;
command.triggerInvalid = false;
if (trigger !== undefined) {
command.trigger = trigger;
}
if (command.trigger && Registry.pipeline.hasManualExecutionComponentForTriggerType(command.trigger.type)) {
this.triggerComponent = Registry.pipeline.getManualExecutionComponentForTriggerType(command.trigger.type);
} else {
this.triggerComponent = null;
}
updateCommand();
};
this.pipelineSelected = () => {
const pipeline = this.command.pipeline,
executions = application.executions.data || [];
pipelineNotifications = pipeline.notifications || [];
synchronizeNotifications();
this.currentlyRunningExecutions = executions.filter(
execution => execution.pipelineConfigId === pipeline.id && execution.isActive,
);
addTriggers();
this.triggerUpdated();
updatePipelinePlan(pipeline);
if (pipeline.parameterConfig && pipeline.parameterConfig.length) {
this.parameters = {};
this.hasRequiredParameters = pipeline.parameterConfig.some(p => p.required);
pipeline.parameterConfig.forEach(p => this.addParameter(p));
this.updateParameters();
}
};
this.addParameter = parameterConfig => {
const [, queryString] = window.location.href.split('?');
const queryParams = UrlParser.parseQueryString(queryString);
// Inject the default value into the options list if it is absent
if (
parameterConfig.default &&
parameterConfig.options &&
!parameterConfig.options.some(option => option.value === parameterConfig.default)
) {
parameterConfig.options.unshift({ value: parameterConfig.default });
}
const { name } = parameterConfig;
const parameters = trigger ? trigger.parameters : {};
if (queryParams[name]) {
this.parameters[name] = queryParams[name];
}
if (this.parameters[name] === undefined) {
this.parameters[name] = parameters[name] !== undefined ? parameters[name] : parameterConfig.default;
}
};
this.updateParameters = () => {
this.command.pipeline.parameterConfig.forEach(p => {
if (p.conditional) {
const include = this.shouldInclude(p);
if (!include) {
delete this.parameters[p.name];
this.hiddenParameters.add(p.name);
} else {
this.hiddenParameters.delete(p.name);
this.addParameter(p);
}
}
});
};
this.shouldInclude = p => {
if (p.conditional) {
const comparingTo = this.parameters[p.conditional.parameter];
const value = p.conditional.comparatorValue;
switch (p.conditional.comparator) {
case '>':
return parseFloat(comparingTo) > parseFloat(value);
case '>=':
return parseFloat(comparingTo) >= parseFloat(value);
case '<':
return parseFloat(comparingTo) < parseFloat(value);
case '<=':
return parseFloat(comparingTo) <= parseFloat(value);
case '!=':
return comparingTo !== value;
case '=':
return comparingTo === value;
}
}
return true;
};
this.execute = () => {
let selectedTrigger = this.command.trigger || {},
command = {
trigger: selectedTrigger,
},
pipeline = this.command.pipeline;
if (this.command.notificationEnabled && this.command.notification.address) {
selectedTrigger.notifications = [this.command.notification];
}
// include any extra data populated by trigger manual execution handlers
angular.extend(selectedTrigger, this.command.extraFields);
command.pipelineName = pipeline.name;
selectedTrigger.type = 'manual';
selectedTrigger.dryRun = this.command.dryRun;
// The description is not part of the trigger spec, so don't send it
delete selectedTrigger.description;
if (pipeline.parameterConfig && pipeline.parameterConfig.length) {
selectedTrigger.parameters = this.parameters;
}
$uibModalInstance.close(command);
};
this.cancel = $uibModalInstance.dismiss;
this.hasStageOf = stageType => {
return this.getStagesOf(stageType).length > 0;
};
this.getStagesOf = stageType => {
if (!this.command.pipeline) {
return [];
}
return this.command.pipeline.stages.filter(stage => stage.type === stageType);
};
this.dateOptions = {
dateDisabled: false,
showWeeks: false,
minDate: new Date(),
startingDay: 1,
};
this.dateOpened = {};
this.openDate = parameterName => {
this.dateOpened[parameterName] = true;
};
/**
* Initialization
*/
if (pipeline) {
this.pipelineSelected();
}
if (!pipeline) {
this.pipelineOptions = application.pipelineConfigs.data.filter(
c => !c.disabled && PipelineTemplateV2Service.isConfigurable(c),
);
}
},
]);
|
app/scripts/modules/core/src/pipeline/manualExecution/manualPipelineExecution.controller.js
|
'use strict';
const angular = require('angular');
import _ from 'lodash';
import { AuthenticationService } from 'core/authentication';
import { Registry } from 'core/registry';
import { SETTINGS } from 'core/config/settings';
import { UrlParser } from 'core/navigation';
import { AppNotificationsService } from 'core/notification/AppNotificationsService';
import { PipelineTemplateReader } from 'core/pipeline/config/templates/PipelineTemplateReader';
import { PipelineTemplateV2Service } from 'core/pipeline';
import { STAGE_MANUAL_COMPONENTS } from './stageManualComponents.component';
import { TRIGGER_TEMPLATE } from './triggerTemplate.component';
import { ARTIFACT_LIST } from '../status/artifactList.component';
import './manualPipelineExecution.less';
module.exports = angular
.module('spinnaker.core.pipeline.manualPipelineExecution.controller', [
require('angular-ui-bootstrap'),
ARTIFACT_LIST,
TRIGGER_TEMPLATE,
STAGE_MANUAL_COMPONENTS,
])
.controller('ManualPipelineExecutionCtrl', [
'$scope',
'$uibModalInstance',
'pipeline',
'application',
'trigger',
function($scope, $uibModalInstance, pipeline, application, trigger) {
let applicationNotifications = [];
let pipelineNotifications = [];
this.hiddenParameters = new Set();
this.notificationTooltip = require('./notifications.tooltip.html');
AppNotificationsService.getNotificationsForApplication(application.name).then(notifications => {
Object.keys(notifications)
.sort()
.filter(k => Array.isArray(notifications[k]))
.forEach(type => {
notifications[type].forEach(notification => {
applicationNotifications.push(notification);
});
});
synchronizeNotifications();
});
let user = AuthenticationService.getAuthenticatedUser();
let synchronizeNotifications = () => {
this.notifications = applicationNotifications.concat(pipelineNotifications);
};
this.getNotifications = () => {
return _.has(this.command, 'pipeline.notifications')
? this.command.pipeline.notifications.concat(applicationNotifications)
: applicationNotifications;
};
let userEmail = user.authenticated && user.name.includes('@') ? user.name : null;
this.command = {
pipeline: pipeline,
trigger: null,
dryRun: false,
notificationEnabled: false,
notification: {
type: 'email',
address: userEmail,
when: ['pipeline.complete', 'pipeline.failed'],
},
};
this.dryRunEnabled = SETTINGS.feature.dryRunEnabled;
// Poor react setState
const updateCommand = () => {
$scope.$applyAsync(() => {
this.command = _.cloneDeep(this.command);
});
};
let addTriggers = () => {
let pipeline = this.command.pipeline;
if (!pipeline || !pipeline.triggers || !pipeline.triggers.length) {
this.triggers = null;
this.command.trigger = null;
return;
}
this.triggers = pipeline.triggers
.filter(t => Registry.pipeline.hasManualExecutionComponentForTriggerType(t.type))
.map(t => {
let copy = _.clone(t);
copy.description = '...'; // placeholder
Registry.pipeline
.getManualExecutionComponentForTriggerType(t.type)
.formatLabel(t)
.then(label => (copy.description = label));
return copy;
});
if (trigger && trigger.type === 'manual' && this.triggers.length) {
trigger.type = this.triggers[0].type;
}
const suppliedTriggerHasManualComponent =
trigger && Registry.pipeline.hasManualExecutionComponentForTriggerType(trigger.type);
if (suppliedTriggerHasManualComponent) {
Registry.pipeline
.getManualExecutionComponentForTriggerType(trigger.type)
.formatLabel(trigger)
.then(label => (trigger.description = label));
// If the trigger has a manual component, we don't want to also explicitly
// send along the artifacts from the last run, as the manual component will
// populate enough information (ex: build number, docker tag) to re-inflate
// these on a subsequent run.
trigger.artifacts = [];
}
this.command.trigger = trigger || _.head(this.triggers);
};
const updatePipelinePlan = pipeline => {
if (pipeline.type === 'templatedPipeline' && (pipeline.stages === undefined || pipeline.stages.length === 0)) {
PipelineTemplateReader.getPipelinePlan(pipeline)
.then(plan => (this.stageComponents = getManualExecutionComponents(plan.stages)))
.catch(() => getManualExecutionComponents(pipeline.stages));
} else {
this.stageComponents = getManualExecutionComponents(pipeline.stages);
}
};
const getManualExecutionComponents = stages => {
const additionalComponents = stages.map(stage => Registry.pipeline.getManualExecutionComponentForStage(stage));
return _.uniq(_.compact(additionalComponents));
};
/**
* Controller API
*/
this.triggerUpdated = trigger => {
let command = this.command;
command.triggerInvalid = false;
if (trigger !== undefined) {
command.trigger = trigger;
}
if (command.trigger && Registry.pipeline.hasManualExecutionComponentForTriggerType(command.trigger.type)) {
this.triggerComponent = Registry.pipeline.getManualExecutionComponentForTriggerType(command.trigger.type);
} else {
this.triggerComponent = null;
}
updateCommand();
};
this.pipelineSelected = () => {
const pipeline = this.command.pipeline,
executions = application.executions.data || [];
pipelineNotifications = pipeline.notifications || [];
synchronizeNotifications();
this.currentlyRunningExecutions = executions.filter(
execution => execution.pipelineConfigId === pipeline.id && execution.isActive,
);
addTriggers();
this.triggerUpdated();
updatePipelinePlan(pipeline);
if (pipeline.parameterConfig && pipeline.parameterConfig.length) {
this.parameters = {};
this.hasRequiredParameters = pipeline.parameterConfig.some(p => p.required);
pipeline.parameterConfig.forEach(p => this.addParameter(p));
this.updateParameters();
}
};
this.addParameter = parameterConfig => {
const [, queryString] = window.location.href.split('?');
const queryParams = UrlParser.parseQueryString(queryString);
// Inject the default value into the options list if it is absent
if (
parameterConfig.default &&
parameterConfig.options &&
!parameterConfig.options.some(option => option.value === parameterConfig.default)
) {
parameterConfig.options.unshift({ value: parameterConfig.default });
}
const { name } = parameterConfig;
const parameters = trigger ? trigger.parameters : {};
if (queryParams[name]) {
this.parameters[name] = queryParams[name];
}
if (this.parameters[name] === undefined) {
this.parameters[name] = parameters[name] !== undefined ? parameters[name] : parameterConfig.default;
}
};
this.updateParameters = () => {
this.command.pipeline.parameterConfig.forEach(p => {
if (p.conditional) {
const include = this.shouldInclude(p);
if (!include) {
delete this.parameters[p.name];
this.hiddenParameters.add(p.name);
} else {
this.hiddenParameters.delete(p.name);
this.addParameter(p);
}
}
});
};
this.shouldInclude = p => {
if (p.conditional) {
const comparingTo = this.parameters[p.conditional.parameter];
const value = p.conditional.comparatorValue;
switch (p.conditional.comparator) {
case '>':
return parseFloat(comparingTo) > parseFloat(value);
case '>=':
return parseFloat(comparingTo) >= parseFloat(value);
case '<':
return parseFloat(comparingTo) < parseFloat(value);
case '<=':
return parseFloat(comparingTo) <= parseFloat(value);
case '!=':
return comparingTo !== value;
case '=':
return comparingTo === value;
}
}
return true;
};
this.execute = () => {
let selectedTrigger = this.command.trigger || {},
command = {
trigger: selectedTrigger,
},
pipeline = this.command.pipeline;
if (this.command.notificationEnabled && this.command.notification.address) {
selectedTrigger.notifications = [this.command.notification];
}
// include any extra data populated by trigger manual execution handlers
angular.extend(selectedTrigger, this.command.extraFields);
command.pipelineName = pipeline.name;
selectedTrigger.type = 'manual';
selectedTrigger.dryRun = this.command.dryRun;
// The description is not part of the trigger spec, so don't send it
delete selectedTrigger.description;
if (pipeline.parameterConfig && pipeline.parameterConfig.length) {
selectedTrigger.parameters = this.parameters;
}
$uibModalInstance.close(command);
};
this.cancel = $uibModalInstance.dismiss;
this.hasStageOf = stageType => {
return this.getStagesOf(stageType).length > 0;
};
this.getStagesOf = stageType => {
if (!this.command.pipeline) {
return [];
}
return this.command.pipeline.stages.filter(stage => stage.type === stageType);
};
this.dateOptions = {
dateDisabled: false,
showWeeks: false,
minDate: new Date(),
startingDay: 1,
};
this.dateOpened = {};
this.openDate = parameterName => {
this.dateOpened[parameterName] = true;
};
/**
* Initialization
*/
if (pipeline) {
this.pipelineSelected();
}
if (!pipeline) {
this.pipelineOptions = application.pipelineConfigs.data.filter(
c => !c.disabled && PipelineTemplateV2Service.isConfigurable(c),
);
}
},
]);
|
fix(executions): Correctly populate trigger when rerunning an execution (#7205)
|
app/scripts/modules/core/src/pipeline/manualExecution/manualPipelineExecution.controller.js
|
fix(executions): Correctly populate trigger when rerunning an execution (#7205)
|
<ide><path>pp/scripts/modules/core/src/pipeline/manualExecution/manualPipelineExecution.controller.js
<ide> // these on a subsequent run.
<ide> trigger.artifacts = [];
<ide> }
<del> this.command.trigger = trigger || _.head(this.triggers);
<add> if (trigger) {
<add> // Find the pipeline.trigger that matches trigger (the trigger from the execution being re-run)
<add> this.command.trigger = this.triggers.find(t =>
<add> Object.keys(t)
<add> .filter(k => k !== 'description')
<add> .every(k => t[k] === trigger[k]),
<add> );
<add> // If we found a match, rehydrate it with everything from trigger, otherwise just default back to setting it to trigger
<add> this.command.trigger = this.command.trigger ? Object.assign(this.command.trigger, trigger) : trigger;
<add> } else {
<add> this.command.trigger = _.head(this.triggers);
<add> }
<ide> };
<ide>
<ide> const updatePipelinePlan = pipeline => {
|
|
Java
|
bsd-3-clause
|
5f3c75b0f94115dce40497b1abbc25479b829946
| 0 |
Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java
|
/*
* Copyright (c) 1998-2020 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package ucar.nc2.internal.dataset;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.StringTokenizer;
import javax.annotation.Nullable;
import ucar.ma2.Array;
import ucar.ma2.DataType;
import ucar.nc2.Attribute;
import ucar.nc2.Dimension;
import ucar.nc2.Group;
import ucar.nc2.NetcdfFiles;
import ucar.nc2.Variable;
import ucar.nc2.constants.AxisType;
import ucar.nc2.constants.CF;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.dataset.CoordinateAxis;
import ucar.nc2.dataset.CoordinateSystem;
import ucar.nc2.dataset.CoordinateTransform;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dataset.StructureDS;
import ucar.nc2.dataset.VariableDS;
import ucar.nc2.dataset.spi.CoordSystemBuilderFactory;
import ucar.nc2.util.CancelTask;
import ucar.nc2.util.EscapeStrings;
import ucar.unidata.util.Parameter;
/**
* Super class for implementing Convention-specific parsing of netCDF files.
* This class processes the "_Coordinate conventions", see
* https://www.unidata.ucar.edu/software/netcdf-java/current/reference/CoordinateAttributes.html
*
* A good strategy is for subclasses to add those attributes, and let this class construct the coordinate systems.
*/
/*
* Implementation notes:
*
* Generally, subclasses should add the _Coordinate conventions, see
* https://www.unidata.ucar.edu/software/netcdf-java/current/reference/CoordinateAttributes.html
* Then let this class do the rest of the work.
*
* How to add Coordinate Transforms:
* A.
* 1) create a dummy Variable called the Coordinate Transform Variable.
* This Coordinate Transform variable always has a name that identifies the transform,
* and any attributes needed for the transformation.
* 2) explicitly point to it by adding a _CoordinateTransform attribute to a Coordinate System Variable
* _CoordinateTransforms = "LambertProjection HybridSigmaVerticalTransform"
*
* B. You could explicitly add it by overriding assignCoordinateTransforms()
*/
public class CoordSystemBuilder {
protected static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CoordSystemBuilder.class);
private static boolean useMaximalCoordSys = true;
private static final String CONVENTION_NAME = _Coordinate.Convention;
public static class Factory implements CoordSystemBuilderFactory {
@Override
public String getConventionName() {
return CONVENTION_NAME;
}
@Override
public CoordSystemBuilder open(NetcdfDataset.Builder datasetBuilder) {
return new CoordSystemBuilder(datasetBuilder);
}
}
/**
* Calculate if this is a classic coordinate variable: has same name as its first dimension.
* If type char, must be 2D, else must be 1D.
*
* @return true if a coordinate variable.
*/
public static boolean isCoordinateVariable(Variable.Builder<?> vb) {
// Structures and StructureMembers cant be coordinate variables
if ((vb.dataType == DataType.STRUCTURE) || vb.getParentStructureBuilder() != null)
return false;
int rank = vb.getRank();
if (rank == 1) {
String firstd = vb.getFirstDimensionName();
if (vb.shortName.equals(firstd)) {
return true;
}
}
if (rank == 2) { // two dimensional
String firstd = vb.getFirstDimensionName();
// must be char valued (then its really a String)
return vb.shortName.equals(firstd) && (vb.dataType == DataType.CHAR);
}
return false;
}
public static int countDomainSize(Variable.Builder<?>... axes) {
Set<Dimension> domain = new HashSet<>();
for (Variable.Builder<?> axis : axes) {
domain.addAll(axis.getDimensions());
}
return domain.size();
}
/**
* Does this axis "fit" this variable. True if all of the dimensions in the axis also appear in
* the variable. If char variable, last dimension is left out.
*
* @param axis check if this axis is ok for the given variable
* @param vp the given variable
* @return true if all of the dimensions in the axis also appear in the variable.
*/
protected boolean isCoordinateAxisForVariable(CoordinateAxis.Builder<?> axis, VarProcess vp) {
ImmutableList<Dimension> varDims = vp.vb.getDimensions();
ImmutableList<Dimension> axisDims = axis.getDimensions();
// a CHAR variable must really be a STRING, so leave out the last (string length) dimension
int checkDims = axisDims.size();
if (axis.dataType == DataType.CHAR)
checkDims--;
for (int i = 0; i < checkDims; i++) {
Dimension axisDim = axisDims.get(i);
if (!varDims.contains(axisDim)) {
return false;
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////
protected NetcdfDataset.Builder<?> datasetBuilder;
protected Group.Builder rootGroup;
protected CoordinatesHelper.Builder coords;
protected List<VarProcess> varList = new ArrayList<>();
// coordinate variables for Dimension (full name)
protected Multimap<String, VarProcess> coordVarsForDimension = ArrayListMultimap.create();
// default name of Convention, override in subclass
protected String conventionName = _Coordinate.Convention;
protected Formatter parseInfo = new Formatter();
protected Formatter userAdvice = new Formatter();
protected boolean debug;
// Used when using NcML to provide convention attributes.
protected CoordSystemBuilder(NetcdfDataset.Builder<?> datasetBuilder) {
this.datasetBuilder = datasetBuilder;
this.rootGroup = datasetBuilder.rootGroup;
this.coords = datasetBuilder.coords;
}
protected void setConventionUsed(String convName) {
this.conventionName = convName;
}
public String getConventionUsed() {
return conventionName;
}
protected void addUserAdvice(String advice) {
userAdvice.format("%s", advice);
}
public String getParseInfo() {
return parseInfo.toString();
}
public String getUserAdvice() {
return userAdvice.toString();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// subclasses can override any of these routines
protected void augmentDataset(CancelTask cancelTask) throws IOException {}
// All these steps may be overriden by subclasses.
protected void buildCoordinateSystems() {
// put status info into parseInfo that can be shown to someone trying to debug this process
parseInfo.format("Parsing with Convention = %s%n", conventionName);
// Bookkeeping info for each variable is kept in the VarProcess inner class
addVariables(datasetBuilder.rootGroup);
// identify which variables are coordinate axes
identifyCoordinateAxes();
// identify which variables are used to describe coordinate systems
identifyCoordinateSystems();
// identify which variables are used to describe coordinate transforms
identifyCoordinateTransforms();
// turn Variables into CoordinateAxis objects
makeCoordinateAxes();
// make Coordinate Systems for all Coordinate Systems Variables
makeCoordinateSystems();
// assign explicit CoordinateSystem objects to variables
assignCoordinateSystemsExplicit();
// assign implicit CoordinateSystem objects to variables
makeCoordinateSystemsImplicit();
// optionally assign implicit CoordinateSystem objects to variables that dont have one yet
if (useMaximalCoordSys) {
makeCoordinateSystemsMaximal();
}
// make Coordinate Transforms
makeCoordinateTransforms();
// assign Coordinate Transforms
assignCoordinateTransforms();
}
private void addVariables(Group.Builder group) {
for (Variable.Builder vb : group.vbuilders) {
if (vb instanceof VariableDS.Builder) {
varList.add(new VarProcess(group, (VariableDS.Builder) vb));
} else if (vb instanceof StructureDS.Builder) {
addStructure(group, (StructureDS.Builder) vb);
}
}
for (Group.Builder nested : group.gbuilders) {
addVariables(nested);
}
}
private void addStructure(Group.Builder group, StructureDS.Builder<?> structure) {
List<Variable.Builder<?>> nested = structure.vbuilders;
for (Variable.Builder<?> vb : nested) {
if (vb instanceof VariableDS.Builder) {
varList.add(new VarProcess(group, (VariableDS.Builder) vb));
} else if (vb instanceof StructureDS.Builder) { // LOOK the actual Structure isnt in the VarProcess list.
addStructure(group, (StructureDS.Builder) vb);
}
}
}
/** Everything named in the coordinateAxes or coordinates attribute are Coordinate axes. */
protected void identifyCoordinateAxes() {
for (VarProcess vp : varList) {
if (vp.coordinateAxes != null) {
identifyCoordinateAxes(vp, vp.coordinateAxes);
}
if (vp.coordinates != null) {
identifyCoordinateAxes(vp, vp.coordinates);
}
}
}
// Mark named coordinates as "isCoordinateAxis"
private void identifyCoordinateAxes(VarProcess vp, String coordinates) {
StringTokenizer stoker = new StringTokenizer(coordinates);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap == null) {
Group.Builder gb = vp.vb.getParentGroupBuilder();
Optional<Variable.Builder<?>> vopt = gb.findVariableOrInParent(vname);
if (vopt.isPresent()) {
ap = findVarProcess(vopt.get().getFullName(), vp);
} else {
parseInfo.format("***Cant find coordAxis %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find coordAxis %s referenced from var= %s%n", vname, vp);
}
}
if (ap != null) {
if (!ap.isCoordinateAxis) {
parseInfo.format(" CoordinateAxis = %s added; referenced from var= %s%n", vname, vp);
}
ap.isCoordinateAxis = true;
} else {
parseInfo.format("***Cant find coordAxis %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find coordAxis %s referenced from var= %s%n", vname, vp);
}
}
}
/** Identify coordinate systems, using _Coordinate.Systems attribute. */
protected void identifyCoordinateSystems() {
for (VarProcess vp : varList) {
if (vp.coordinateSystems != null) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateSystems);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap != null) {
if (!ap.isCoordinateSystem) {
parseInfo.format(" CoordinateSystem = %s added; referenced from var= %s%n", vname, vp);
}
ap.isCoordinateSystem = true;
} else {
parseInfo.format("***Cant find coordSystem %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find coordSystem %s referenced from var= %s%n", vname, vp);
}
}
}
}
}
/** Identify coordinate transforms, using _CoordinateTransforms attribute. */
protected void identifyCoordinateTransforms() {
for (VarProcess vp : varList) {
if (vp.coordinateTransforms != null) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateTransforms);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap != null) {
if (!ap.isCoordinateTransform) {
parseInfo.format(" CoordinateTransform = %s added; referenced from var= %s%n", vname, vp);
}
ap.isCoordinateTransform = true;
} else {
parseInfo.format("***Cant find CoordinateTransform %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find CoordinateTransform %s referenced from var= %s%n", vname, vp);
}
}
}
}
}
/**
* Identify what kind of AxisType the named variable is. Only called for variables already
* identified as Coordinate Axes. Default null - subclasses can override.
*
* @param vb a variable already identified as a Coordinate Axis
* @return AxisType or null if unknown.
*/
@Nullable
protected AxisType getAxisType(VariableDS.Builder vb) {
return null;
}
/**
* Take previously identified Coordinate Axis and Coordinate Variables and make them into a
* CoordinateAxis. Uses the getAxisType() method to figure out the type, if not already set.
*/
protected void makeCoordinateAxes() {
// The ones identified as coordinate variables or axes
for (VarProcess vp : varList) {
if (vp.isCoordinateAxis || vp.isCoordinateVariable) {
if (vp.axisType == null) {
vp.axisType = getAxisType(vp.vb);
}
if (vp.axisType == null) {
userAdvice.format("Coordinate Axis %s does not have an assigned AxisType%n", vp);
}
vp.makeIntoCoordinateAxis();
}
}
// The ones marked as Coordinate Systems, which will reference Coordinates
for (VarProcess vp : varList) {
if (vp.isCoordinateSystem) {
vp.makeCoordinatesFromCoordinateSystem();
}
}
}
protected void makeCoordinateSystems() {
// The ones marked as Coordinate Systems, which will reference Coordinates
for (VarProcess vp : varList) {
if (vp.isCoordinateSystem) {
vp.makeCoordinateSystem();
}
}
}
/**
* Assign explicit CoordinateSystem objects to variables.
*/
protected void assignCoordinateSystemsExplicit() {
// look for explicit references to coord sys variables
for (VarProcess vp : varList) {
if (vp.coordinateSystems != null && !vp.isCoordinateTransform) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateSystems);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap == null) {
parseInfo.format("***Cant find Coordinate System variable %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find Coordinate System variable %s referenced from var= %s%n", vname, vp);
} else if (ap.cs == null) {
parseInfo.format("***Not a Coordinate System variable %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Not a Coordinate System variable %s referenced from var= %s%n", vname, vp);
} else {
String sysName = coords.makeCanonicalName(vp.vb, ap.cs.coordAxesNames);
vp.vb.addCoordinateSystemName(sysName);
}
}
}
}
// look for explicit references from coord sys variables to data variables
for (VarProcess csVar : varList) {
if (!csVar.isCoordinateSystem || (csVar.coordinateSystemsFor == null)) {
continue;
}
// get list of dimensions from '_CoordinateSystemFor' attribute
Set<String> dimList = new HashSet<>();
StringTokenizer stoker = new StringTokenizer(csVar.coordinateSystemsFor);
while (stoker.hasMoreTokens()) {
String dname = stoker.nextToken();
Optional<Dimension> dimOpt = rootGroup.findDimension(dname);
if (dimOpt.isPresent()) {
dimList.add(dimOpt.get().getShortName());
} else {
parseInfo.format("***Cant find Dimension %s referenced from CoordSys var= %s%n", dname, csVar);
userAdvice.format("***Cant find Dimension %s referenced from CoordSys var= %s%n", dname, csVar);
}
}
// look for vars with those dimensions
for (VarProcess vp : varList) {
if (!vp.hasCoordinateSystem() && vp.isData() && (csVar.cs != null)) {
if (CoordinateSystem.isSubset(dimList, vp.vb.getDimensionsAll())
&& CoordinateSystem.isSubset(vp.vb.getDimensionsAll(), dimList)) {
vp.vb.addCoordinateSystemName(csVar.cs.coordAxesNames);
}
}
}
}
// look for explicit listings of coordinate axes
for (VarProcess vp : varList) {
if (!vp.hasCoordinateSystem() && (vp.coordinateAxes != null) && vp.isData()) {
String coordSysName = coords.makeCanonicalName(vp.vb, vp.coordinateAxes);
Optional<CoordinateSystem.Builder> cso = coords.findCoordinateSystem(coordSysName);
if (cso.isPresent()) {
vp.vb.addCoordinateSystemName(coordSysName);
parseInfo.format(" assigned explicit CoordSystem '%s' for var= %s%n", coordSysName, vp);
} else {
CoordinateSystem.Builder csnew = CoordinateSystem.builder().setCoordAxesNames(coordSysName);
coords.addCoordinateSystem(csnew);
vp.vb.addCoordinateSystemName(coordSysName);
parseInfo.format(" created explicit CoordSystem '%s' for var= %s%n", coordSysName, vp);
}
}
}
}
/**
* Make implicit CoordinateSystem objects for variables that dont already have one, by using the
* variables' list of coordinate axes, and any coordinateVariables for it. Must be at least 2
* axes. All of a variable's _Coordinate Variables_ plus any variables listed in a
* *__CoordinateAxes_* or *_coordinates_* attribute will be made into an *_implicit_* Coordinate
* System. If there are at least two axes, and the coordinate system uses all of the variable's
* dimensions, it will be assigned to the data variable.
*/
protected void makeCoordinateSystemsImplicit() {
for (VarProcess vp : varList) {
if (!vp.hasCoordinateSystem() && vp.maybeData()) {
List<CoordinateAxis.Builder> dataAxesList = vp.findCoordinateAxes(true);
if (dataAxesList.size() < 2) {
continue;
}
String csName = coords.makeCanonicalName(dataAxesList);
Optional<CoordinateSystem.Builder> csOpt = coords.findCoordinateSystem(csName);
if (csOpt.isPresent() && coords.isComplete(csOpt.get(), vp.vb)) {
vp.vb.addCoordinateSystemName(csName);
parseInfo.format(" assigned implicit CoordSystem '%s' for var= %s%n", csName, vp);
} else {
CoordinateSystem.Builder csnew = CoordinateSystem.builder().setCoordAxesNames(csName).setImplicit(true);
if (coords.isComplete(csnew, vp.vb)) {
vp.vb.addCoordinateSystemName(csName);
coords.addCoordinateSystem(csnew);
parseInfo.format(" created implicit CoordSystem '%s' for var= %s%n", csName, vp);
}
}
}
}
}
/**
* If a variable still doesnt have a coordinate system, use hueristics to try to find one that was
* probably forgotten. Examine existing CS. create a subset of axes that fits the variable. Choose
* the one with highest rank. It must have X,Y or lat,lon. If so, add it.
*/
private void makeCoordinateSystemsMaximal() {
boolean requireCompleteCoordSys =
!datasetBuilder.getEnhanceMode().contains(NetcdfDataset.Enhance.IncompleteCoordSystems);
for (VarProcess vp : varList) {
if (vp.hasCoordinateSystem() || !vp.isData()) {
continue;
}
// look through all axes that fit
List<CoordinateAxis.Builder> axisList = new ArrayList<>();
for (CoordinateAxis.Builder axis : coords.coordAxes) {
if (isCoordinateAxisForVariable(axis, vp)) {
axisList.add(axis);
}
}
if (axisList.size() < 2) {
continue;
}
String csName = coords.makeCanonicalName(axisList);
Optional<CoordinateSystem.Builder> csOpt = coords.findCoordinateSystem(csName);
boolean okToBuild = false;
// do coordinate systems need to be complete?
// default enhance mode is yes, they must be complete
if (requireCompleteCoordSys) {
if (csOpt.isPresent()) {
// only build if coordinate system is complete
okToBuild = coords.isComplete(csOpt.get(), vp.vb);
}
} else {
// coordinate system can be incomplete, so we're ok to build if we find something
okToBuild = true;
}
if (csOpt.isPresent() && okToBuild) {
vp.vb.addCoordinateSystemName(csName);
parseInfo.format(" assigned maximal CoordSystem '%s' for var= %s%n", csName, vp);
} else {
CoordinateSystem.Builder csnew = CoordinateSystem.builder().setCoordAxesNames(csName);
// again, do coordinate systems need to be complete?
// default enhance mode is yes, they must be complete
if (requireCompleteCoordSys) {
// only build if new coordinate system is complete
okToBuild = coords.isComplete(csnew, vp.vb);
}
if (okToBuild) {
csnew.setImplicit(true);
vp.vb.addCoordinateSystemName(csName);
coords.addCoordinateSystem(csnew);
parseInfo.format(" created maximal CoordSystem '%s' for var= %s%n", csnew.coordAxesNames, vp);
}
}
}
}
/**
* Take all previously identified Coordinate Transforms and create a CoordinateTransform object by
* calling CoordTransBuilder.makeCoordinateTransform().
*/
protected void makeCoordinateTransforms() {
for (VarProcess vp : varList) {
if (vp.isCoordinateTransform && vp.ct == null) { // TODO dont have ncd
vp.ct = makeCoordinateTransform(vp.vb);
if (vp.ct != null) {
coords.addCoordinateTransform(vp.ct);
}
}
}
}
protected CoordinateTransform.Builder makeCoordinateTransform(VariableDS.Builder<?> vb) {
return CoordinateTransform.builder().setName(vb.getFullName()).setAttributeContainer(vb.getAttributeContainer());
}
/** Assign CoordinateTransform objects to Variables and Coordinate Systems. */
protected void assignCoordinateTransforms() {
// look for explicit transform assignments on the coordinate systems
for (VarProcess vp : varList) {
if (vp.isCoordinateSystem && vp.coordinateTransforms != null) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateTransforms);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap != null) {
if (ap.ct != null) {
vp.addCoordinateTransform(ap.ct);
parseInfo.format(" assign explicit coordTransform %s to CoordSys= %s%n", ap.ct, vp.cs);
} else {
parseInfo.format("***Cant find coordTransform in %s referenced from var= %s%n", vname,
vp.vb.getFullName());
userAdvice.format("***Cant find coordTransform in %s referenced from var= %s%n", vname,
vp.vb.getFullName());
}
} else {
parseInfo.format("***Cant find coordTransform variable= %s referenced from var= %s%n", vname,
vp.vb.getFullName());
userAdvice.format("***Cant find coordTransform variable= %s referenced from var= %s%n", vname,
vp.vb.getFullName());
}
}
}
}
// look for explicit coordSys assignments on the coordinate transforms
for (VarProcess vp : varList) {
if (vp.isCoordinateTransform && (vp.ct != null) && (vp.coordinateSystems != null)) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateSystems);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess vcs = findVarProcess(vname, vp);
if (vcs == null) {
parseInfo.format("***Cant find coordSystem variable= %s referenced from var= %s%n", vname,
vp.vb.getFullName());
userAdvice.format("***Cant find coordSystem variable= %s referenced from var= %s%n", vname,
vp.vb.getFullName());
} else {
vcs.addCoordinateTransform(vp.ct);
parseInfo.format("***assign explicit coordTransform %s to CoordSys= %s%n", vp.ct, vp.cs);
}
}
}
}
// look for coordAxes assignments on the coordinate transforms
for (VarProcess vp : varList) {
if (vp.isCoordinateTransform && (vp.ct != null) && (vp.coordinateAxes != null)) {
List<CoordinateAxis.Builder> dataAxesList = vp.findCoordinateAxes(false);
if (!dataAxesList.isEmpty()) {
for (CoordinateSystem.Builder cs : coords.coordSys) {
if (coords.containsAxes(cs, dataAxesList)) {
coords.addCoordinateTransform(vp.ct);
cs.addCoordinateTransformByName(vp.ct.name);
parseInfo.format("***assign (implicit coordAxes) coordTransform %s to CoordSys= %s%n", vp.ct, cs);
}
}
}
}
}
// look for coordAxisType assignments on the coordinate transforms
for (VarProcess vp : varList) {
if (vp.isCoordinateTransform && (vp.ct != null) && (vp.coordAxisTypes != null)) {
List<AxisType> axisTypesList = new ArrayList<>();
StringTokenizer stoker = new StringTokenizer(vp.coordAxisTypes);
while (stoker.hasMoreTokens()) {
String name = stoker.nextToken();
AxisType atype;
if (null != (atype = AxisType.getType(name))) {
axisTypesList.add(atype);
}
}
if (!axisTypesList.isEmpty()) {
for (CoordinateSystem.Builder cs : coords.coordSys) {
if (coords.containsAxisTypes(cs, axisTypesList)) {
cs.addCoordinateTransformByName(vp.ct.name);
parseInfo.format("***assign (implicit coordAxisType) coordTransform %s to CoordSys= %s%n", vp.ct, cs);
}
}
}
}
}
}
protected VarProcess findVarProcess(String name, VarProcess from) {
if (name == null) {
return null;
}
// compare full name
for (VarProcess vp : varList) {
if (name.equals(vp.vb.getFullName())) {
return vp;
}
}
// prefer ones in the same group
if (from != null) {
for (VarProcess vp : varList) {
if (vp.vb == null || vp.vb.getParentGroupBuilder() == null || from.vb == null) {
continue;
}
if (name.equals(vp.vb.shortName) && vp.vb.getParentGroupBuilder().equals(from.vb.getParentGroupBuilder())) {
return vp;
}
}
}
// WAEF, use short name
for (VarProcess vp : varList) {
if (name.equals(vp.vb.shortName)) {
return vp;
}
}
return null;
}
protected VarProcess findCoordinateAxis(String name) {
if (name == null) {
return null;
}
for (VarProcess vp : varList) {
if (name.equals(vp.vb.getFullName()) && (vp.isCoordinateVariable || vp.isCoordinateAxis)) {
return vp;
}
}
return null;
}
/**
* Create a "dummy" Coordinate Transform Variable based on the given CoordinateTransform.
* This creates a scalar Variable with dummy data, and adds the Parameters of the CoordinateTransform
* as attributes.
*
* @param ct based on the CoordinateTransform
* @return the Coordinate Transform Variable. You must add it to the dataset.
*/
protected VariableDS.Builder makeCoordinateTransformVariable(CoordinateTransform ct) {
VariableDS.Builder v = VariableDS.builder().setName(ct.getName()).setDataType(DataType.CHAR);
List<Parameter> params = ct.getParameters();
for (Parameter p : params) {
if (p.isString())
v.addAttribute(new Attribute(p.getName(), p.getStringValue()));
else {
double[] data = p.getNumericValues();
Array dataA = Array.factory(DataType.DOUBLE, new int[] {data.length}, data);
v.addAttribute(new Attribute(p.getName(), dataA));
}
}
v.addAttribute(new Attribute(_Coordinate.TransformType, ct.getTransformType().toString()));
// fake data
Array data = Array.factory(DataType.CHAR, new int[] {}, new char[] {' '});
v.setCachedData(data, true);
parseInfo.format(" made CoordinateTransformVariable: %s%n", ct.getName());
return v;
}
@Nullable
private String findDimFullName(Variable.Builder vb, String dimShortName) {
String dimName = EscapeStrings.backslashEscape(dimShortName, NetcdfFiles.reservedFullName);
// In order to get the "full" dimension name, we need to know what group it lives in. We will start in the group
// that the variable belongs to and work our way up the group tree. If we don't find the dimension, we get null.
Group.Builder gb = vb.getParentGroupBuilder();
return findDimension(gb, dimShortName);
}
@Nullable
private String findDimension(@Nullable Group.Builder gb, String dimName) {
if (gb == null) {
return null;
} else {
Optional<Dimension> dim = gb.findDimensionLocal(dimName);
return dim.isPresent() ? makeDimFullName(gb, dimName) : findDimension(gb.getParentGroup(), dimName);
}
}
private String makeDimFullName(Variable.Builder vb, Dimension d) {
return makeDimFullName(vb.getParentGroupBuilder(), d);
}
private String makeDimFullName(Variable.Builder vb, String dimName) {
return makeDimFullName(vb.getParentGroupBuilder(), dimName);
}
private String makeDimFullName(Group.Builder gb, Dimension d) {
return makeDimFullName(gb, d.getShortName());
}
private String makeDimFullName(Group.Builder gb, String dimShortName) {
String dimName = EscapeStrings.backslashEscape(dimShortName, NetcdfFiles.reservedFullName);
return gb.makeFullName() + dimName;
}
/** Classifications of Variables into axis, systems and transforms */
protected class VarProcess {
public Group.Builder gb;
public VariableDS.Builder<?> vb;
// attributes
public String coordVarAlias; // _Coordinate.AliasForDimension
public String positive; // _Coordinate.ZisPositive or CF.POSITIVE
public String coordinateAxes; // _Coordinate.Axes
public String coordinateSystems; // _Coordinate.Systems
public String coordinateSystemsFor; // _Coordinate.SystemsFor
public String coordinateTransforms; // _Coordinate.Transforms
public String coordAxisTypes; // _Coordinate.AxisTypes
public String coordTransformType; // _Coordinate.TransformType
public String coordinates; // CF coordinates (set by subclasses)
// coord axes
public boolean isCoordinateVariable; // classic coordinate variable
public boolean isCoordinateAxis;
public AxisType axisType;
public CoordinateAxis.Builder<?> axis; // if its made into a Coordinate Axis, this is not null
// coord systems
public boolean isCoordinateSystem;
public CoordinateSystem.Builder cs;
// coord transform
public boolean isCoordinateTransform;
public CoordinateTransform.Builder ct;
/**
* Wrap the given variable. Identify Coordinate Variables. Process all _Coordinate attributes.
*
* @param v wrap this Variable
*/
private VarProcess(Group.Builder gb, VariableDS.Builder<?> v) {
this.gb = gb;
this.vb = v;
isCoordinateVariable =
isCoordinateVariable(v) || (null != v.getAttributeContainer().findAttribute(_Coordinate.AliasForDimension));
if (isCoordinateVariable) {
String dimFullName = makeDimFullName(v, v.getFirstDimensionName());
coordVarsForDimension.put(dimFullName, this);
}
Attribute att = v.getAttributeContainer().findAttributeIgnoreCase(_Coordinate.AxisType);
if (att != null) {
String axisName = att.getStringValue();
axisType = AxisType.getType(axisName);
isCoordinateAxis = true;
parseInfo.format(" Coordinate Axis added = %s type= %s%n", v.getFullName(), axisName);
}
coordVarAlias = v.getAttributeContainer().findAttributeString(_Coordinate.AliasForDimension, null);
if (coordVarAlias != null) {
coordVarAlias = coordVarAlias.trim();
if (v.getRank() != 1) {
parseInfo.format("**ERROR Coordinate Variable Alias %s has rank %d%n", v.getFullName(), v.getRank());
userAdvice.format("**ERROR Coordinate Variable Alias %s has rank %d%n", v.getFullName(), v.getRank());
} else {
Optional<Dimension> coordDimOpt = gb.findDimension(coordVarAlias);
coordDimOpt.ifPresent(coordDim -> {
String vDim = v.getFirstDimensionName();
if (!coordDim.getShortName().equals(vDim)) {
parseInfo.format("**ERROR Coordinate Variable Alias %s names wrong dimension %s%n", v.getFullName(),
coordVarAlias);
userAdvice.format("**ERROR Coordinate Variable Alias %s names wrong dimension %s%n", v.getFullName(),
coordVarAlias);
} else {
isCoordinateAxis = true;
String dimFullName = makeDimFullName(v, coordDim);
coordVarsForDimension.put(dimFullName, this);
parseInfo.format(" Coordinate Variable Alias added = %s for dimension= %s%n", v.getFullName(),
coordVarAlias);
}
});
}
}
positive = v.getAttributeContainer().findAttributeString(_Coordinate.ZisPositive, null);
if (positive == null) {
positive = v.getAttributeContainer().findAttributeString(CF.POSITIVE, null);
} else {
isCoordinateAxis = true;
positive = positive.trim();
parseInfo.format(" Coordinate Axis added(from positive attribute ) = %s for dimension= %s%n", v.getFullName(),
coordVarAlias);
}
coordinateAxes = v.getAttributeContainer().findAttributeString(_Coordinate.Axes, null);
coordinateSystems = v.getAttributeContainer().findAttributeString(_Coordinate.Systems, null);
coordinateSystemsFor = v.getAttributeContainer().findAttributeString(_Coordinate.SystemFor, null);
coordinateTransforms = v.getAttributeContainer().findAttributeString(_Coordinate.Transforms, null);
isCoordinateSystem = (coordinateTransforms != null) || (coordinateSystemsFor != null);
coordAxisTypes = v.getAttributeContainer().findAttributeString(_Coordinate.AxisTypes, null);
coordTransformType = v.getAttributeContainer().findAttributeString(_Coordinate.TransformType, null);
isCoordinateTransform = (coordTransformType != null) || (coordAxisTypes != null);
}
protected boolean isData() {
return !isCoordinateVariable && !isCoordinateAxis && !isCoordinateSystem && !isCoordinateTransform;
}
protected boolean maybeData() {
return !isCoordinateVariable && !isCoordinateSystem && !isCoordinateTransform;
}
protected boolean hasCoordinateSystem() {
return !vb.coordSysNames.isEmpty();
}
public String toString() {
return vb.shortName;
}
/**
* Turn the variable into a coordinate axis.
* Add to the dataset, replacing variable if needed.
*
* @return coordinate axis
*/
protected CoordinateAxis.Builder makeIntoCoordinateAxis() {
if (axis != null) {
return axis;
}
if (vb instanceof CoordinateAxis.Builder) {
axis = (CoordinateAxis.Builder) vb;
} else {
// Create a CoordinateAxis out of this variable.
vb = axis = CoordinateAxis.fromVariableDS(vb);
}
if (axisType != null) {
axis.setAxisType(axisType);
axis.addAttribute(new Attribute(_Coordinate.AxisType, axisType.toString()));
if (((axisType == AxisType.Height) || (axisType == AxisType.Pressure) || (axisType == AxisType.GeoZ))
&& (positive != null)) {
axis.setPositive(positive);
axis.addAttribute(new Attribute(_Coordinate.ZisPositive, positive));
}
}
coords.replaceCoordinateAxis(axis);
if (axis.getParentStructureBuilder() != null) {
axis.getParentStructureBuilder().replaceMemberVariable(axis);
} else {
gb.replaceVariable(axis);
}
return axis;
}
/** For any variable listed in a coordinateAxes attribute, make into a coordinate. */
protected void makeCoordinatesFromCoordinateSystem() {
// find referenced coordinate axes
if (coordinateAxes != null) {
StringTokenizer stoker = new StringTokenizer(coordinateAxes); // _CoordinateAxes attribute
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, this);
if (ap != null) {
ap.makeIntoCoordinateAxis();
} else {
parseInfo.format(" Cant find axes %s for Coordinate System %s%n", vname, vb);
userAdvice.format(" Cant find axes %s for Coordinate System %s%n", vname, vb);
}
}
}
}
/** For explicit coordinate system variables, make a CoordinateSystem. */
protected void makeCoordinateSystem() {
if (coordinateAxes != null) {
String sysName = coords.makeCanonicalName(vb, coordinateAxes);
this.cs = CoordinateSystem.builder().setCoordAxesNames(sysName);
parseInfo.format(" Made Coordinate System '%s'", sysName);
coords.addCoordinateSystem(this.cs);
}
}
/**
* Create a list of coordinate axes for this data variable. Use the list of names in axes or
* coordinates field.
*
* @param addCoordVariables if true, add any coordinate variables that are missing.
* @return list of coordinate axes for this data variable.
*/
protected List<CoordinateAxis.Builder> findCoordinateAxes(boolean addCoordVariables) {
List<CoordinateAxis.Builder> axesList = new ArrayList<>();
if (coordinateAxes != null) { // explicit axes
StringTokenizer stoker = new StringTokenizer(coordinateAxes);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, this);
if (ap != null) {
CoordinateAxis.Builder axis = ap.makeIntoCoordinateAxis();
if (!axesList.contains(axis)) {
axesList.add(axis);
}
}
}
} else if (coordinates != null) { // CF partial listing of axes
StringTokenizer stoker = new StringTokenizer(coordinates);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, this);
if (ap != null) {
CoordinateAxis.Builder axis = ap.makeIntoCoordinateAxis(); // LOOK check if its legal
if (!axesList.contains(axis)) {
axesList.add(axis);
}
}
}
}
if (addCoordVariables) {
for (String d : vb.getDimensionsAll()) {
String dimFullName = findDimFullName(vb, d);
for (VarProcess vp : coordVarsForDimension.get(dimFullName)) {
CoordinateAxis.Builder axis = vp.makeIntoCoordinateAxis();
if (!axesList.contains(axis)) {
axesList.add(axis);
}
}
}
}
return axesList;
}
void addCoordinateTransform(CoordinateTransform.Builder ct) {
if (cs == null) {
parseInfo.format(" %s: no CoordinateSystem for CoordinateTransformVariable: %s%n", vb.getFullName(), ct.name);
return;
}
cs.addCoordinateTransformByName(ct.name);
}
} // VarProcess
}
|
cdm/core/src/main/java/ucar/nc2/internal/dataset/CoordSystemBuilder.java
|
/*
* Copyright (c) 1998-2020 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package ucar.nc2.internal.dataset;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.StringTokenizer;
import javax.annotation.Nullable;
import ucar.ma2.Array;
import ucar.ma2.DataType;
import ucar.nc2.Attribute;
import ucar.nc2.Dimension;
import ucar.nc2.Group;
import ucar.nc2.Variable;
import ucar.nc2.constants.AxisType;
import ucar.nc2.constants.CF;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.dataset.CoordinateAxis;
import ucar.nc2.dataset.CoordinateSystem;
import ucar.nc2.dataset.CoordinateTransform;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.dataset.StructureDS;
import ucar.nc2.dataset.VariableDS;
import ucar.nc2.dataset.spi.CoordSystemBuilderFactory;
import ucar.nc2.util.CancelTask;
import ucar.unidata.util.Parameter;
/**
* Super class for implementing Convention-specific parsing of netCDF files.
* This class processes the "_Coordinate conventions", see
* https://www.unidata.ucar.edu/software/netcdf-java/current/reference/CoordinateAttributes.html
*
* A good strategy is for subclasses to add those attributes, and let this class construct the coordinate systems.
*/
/*
* Implementation notes:
*
* Generally, subclasses should add the _Coordinate conventions, see
* https://www.unidata.ucar.edu/software/netcdf-java/current/reference/CoordinateAttributes.html
* Then let this class do the rest of the work.
*
* How to add Coordinate Transforms:
* A.
* 1) create a dummy Variable called the Coordinate Transform Variable.
* This Coordinate Transform variable always has a name that identifies the transform,
* and any attributes needed for the transformation.
* 2) explicitly point to it by adding a _CoordinateTransform attribute to a Coordinate System Variable
* _CoordinateTransforms = "LambertProjection HybridSigmaVerticalTransform"
*
* B. You could explicitly add it by overriding assignCoordinateTransforms()
*/
public class CoordSystemBuilder {
protected static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CoordSystemBuilder.class);
private static boolean useMaximalCoordSys = true;
private static final String CONVENTION_NAME = _Coordinate.Convention;
public static class Factory implements CoordSystemBuilderFactory {
@Override
public String getConventionName() {
return CONVENTION_NAME;
}
@Override
public CoordSystemBuilder open(NetcdfDataset.Builder datasetBuilder) {
return new CoordSystemBuilder(datasetBuilder);
}
}
/**
* Calculate if this is a classic coordinate variable: has same name as its first dimension.
* If type char, must be 2D, else must be 1D.
*
* @return true if a coordinate variable.
*/
public static boolean isCoordinateVariable(Variable.Builder<?> vb) {
// Structures and StructureMembers cant be coordinate variables
if ((vb.dataType == DataType.STRUCTURE) || vb.getParentStructureBuilder() != null)
return false;
int rank = vb.getRank();
if (rank == 1) {
String firstd = vb.getFirstDimensionName();
if (vb.shortName.equals(firstd)) {
return true;
}
}
if (rank == 2) { // two dimensional
String firstd = vb.getFirstDimensionName();
// must be char valued (then its really a String)
return vb.shortName.equals(firstd) && (vb.dataType == DataType.CHAR);
}
return false;
}
public static int countDomainSize(Variable.Builder<?>... axes) {
Set<Dimension> domain = new HashSet<>();
for (Variable.Builder<?> axis : axes) {
domain.addAll(axis.getDimensions());
}
return domain.size();
}
/**
* Does this axis "fit" this variable. True if all of the dimensions in the axis also appear in
* the variable. If char variable, last dimension is left out.
*
* @param axis check if this axis is ok for the given variable
* @param vp the given variable
* @return true if all of the dimensions in the axis also appear in the variable.
*/
protected boolean isCoordinateAxisForVariable(CoordinateAxis.Builder<?> axis, VarProcess vp) {
ImmutableList<Dimension> varDims = vp.vb.getDimensions();
ImmutableList<Dimension> axisDims = axis.getDimensions();
// a CHAR variable must really be a STRING, so leave out the last (string length) dimension
int checkDims = axisDims.size();
if (axis.dataType == DataType.CHAR)
checkDims--;
for (int i = 0; i < checkDims; i++) {
Dimension axisDim = axisDims.get(i);
if (!varDims.contains(axisDim)) {
return false;
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////
protected NetcdfDataset.Builder<?> datasetBuilder;
protected Group.Builder rootGroup;
protected CoordinatesHelper.Builder coords;
protected List<VarProcess> varList = new ArrayList<>();
// coordinate variables for Dimension (name)
protected Multimap<String, VarProcess> coordVarsForDimension = ArrayListMultimap.create();
// default name of Convention, override in subclass
protected String conventionName = _Coordinate.Convention;
protected Formatter parseInfo = new Formatter();
protected Formatter userAdvice = new Formatter();
protected boolean debug;
// Used when using NcML to provide convention attributes.
protected CoordSystemBuilder(NetcdfDataset.Builder<?> datasetBuilder) {
this.datasetBuilder = datasetBuilder;
this.rootGroup = datasetBuilder.rootGroup;
this.coords = datasetBuilder.coords;
}
protected void setConventionUsed(String convName) {
this.conventionName = convName;
}
public String getConventionUsed() {
return conventionName;
}
protected void addUserAdvice(String advice) {
userAdvice.format("%s", advice);
}
public String getParseInfo() {
return parseInfo.toString();
}
public String getUserAdvice() {
return userAdvice.toString();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// subclasses can override any of these routines
protected void augmentDataset(CancelTask cancelTask) throws IOException {}
// All these steps may be overriden by subclasses.
protected void buildCoordinateSystems() {
// put status info into parseInfo that can be shown to someone trying to debug this process
parseInfo.format("Parsing with Convention = %s%n", conventionName);
// Bookkeeping info for each variable is kept in the VarProcess inner class
addVariables(datasetBuilder.rootGroup);
// identify which variables are coordinate axes
identifyCoordinateAxes();
// identify which variables are used to describe coordinate systems
identifyCoordinateSystems();
// identify which variables are used to describe coordinate transforms
identifyCoordinateTransforms();
// turn Variables into CoordinateAxis objects
makeCoordinateAxes();
// make Coordinate Systems for all Coordinate Systems Variables
makeCoordinateSystems();
// assign explicit CoordinateSystem objects to variables
assignCoordinateSystemsExplicit();
// assign implicit CoordinateSystem objects to variables
makeCoordinateSystemsImplicit();
// optionally assign implicit CoordinateSystem objects to variables that dont have one yet
if (useMaximalCoordSys) {
makeCoordinateSystemsMaximal();
}
// make Coordinate Transforms
makeCoordinateTransforms();
// assign Coordinate Transforms
assignCoordinateTransforms();
}
private void addVariables(Group.Builder group) {
for (Variable.Builder vb : group.vbuilders) {
if (vb instanceof VariableDS.Builder) {
varList.add(new VarProcess(group, (VariableDS.Builder) vb));
} else if (vb instanceof StructureDS.Builder) {
addStructure(group, (StructureDS.Builder) vb);
}
}
for (Group.Builder nested : group.gbuilders) {
addVariables(nested);
}
}
private void addStructure(Group.Builder group, StructureDS.Builder<?> structure) {
List<Variable.Builder<?>> nested = structure.vbuilders;
for (Variable.Builder<?> vb : nested) {
if (vb instanceof VariableDS.Builder) {
varList.add(new VarProcess(group, (VariableDS.Builder) vb));
} else if (vb instanceof StructureDS.Builder) { // LOOK the actual Structure isnt in the VarProcess list.
addStructure(group, (StructureDS.Builder) vb);
}
}
}
/** Everything named in the coordinateAxes or coordinates attribute are Coordinate axes. */
protected void identifyCoordinateAxes() {
for (VarProcess vp : varList) {
if (vp.coordinateAxes != null) {
identifyCoordinateAxes(vp, vp.coordinateAxes);
}
if (vp.coordinates != null) {
identifyCoordinateAxes(vp, vp.coordinates);
}
}
}
// Mark named coordinates as "isCoordinateAxis"
private void identifyCoordinateAxes(VarProcess vp, String coordinates) {
StringTokenizer stoker = new StringTokenizer(coordinates);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap == null) {
Group.Builder gb = vp.vb.getParentGroupBuilder();
Optional<Variable.Builder<?>> vopt = gb.findVariableOrInParent(vname);
if (vopt.isPresent()) {
ap = findVarProcess(vopt.get().getFullName(), vp);
} else {
parseInfo.format("***Cant find coordAxis %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find coordAxis %s referenced from var= %s%n", vname, vp);
}
}
if (ap != null) {
if (!ap.isCoordinateAxis) {
parseInfo.format(" CoordinateAxis = %s added; referenced from var= %s%n", vname, vp);
}
ap.isCoordinateAxis = true;
} else {
parseInfo.format("***Cant find coordAxis %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find coordAxis %s referenced from var= %s%n", vname, vp);
}
}
}
/** Identify coordinate systems, using _Coordinate.Systems attribute. */
protected void identifyCoordinateSystems() {
for (VarProcess vp : varList) {
if (vp.coordinateSystems != null) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateSystems);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap != null) {
if (!ap.isCoordinateSystem) {
parseInfo.format(" CoordinateSystem = %s added; referenced from var= %s%n", vname, vp);
}
ap.isCoordinateSystem = true;
} else {
parseInfo.format("***Cant find coordSystem %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find coordSystem %s referenced from var= %s%n", vname, vp);
}
}
}
}
}
/** Identify coordinate transforms, using _CoordinateTransforms attribute. */
protected void identifyCoordinateTransforms() {
for (VarProcess vp : varList) {
if (vp.coordinateTransforms != null) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateTransforms);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap != null) {
if (!ap.isCoordinateTransform) {
parseInfo.format(" CoordinateTransform = %s added; referenced from var= %s%n", vname, vp);
}
ap.isCoordinateTransform = true;
} else {
parseInfo.format("***Cant find CoordinateTransform %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find CoordinateTransform %s referenced from var= %s%n", vname, vp);
}
}
}
}
}
/**
* Identify what kind of AxisType the named variable is. Only called for variables already
* identified as Coordinate Axes. Default null - subclasses can override.
*
* @param vb a variable already identified as a Coordinate Axis
* @return AxisType or null if unknown.
*/
@Nullable
protected AxisType getAxisType(VariableDS.Builder vb) {
return null;
}
/**
* Take previously identified Coordinate Axis and Coordinate Variables and make them into a
* CoordinateAxis. Uses the getAxisType() method to figure out the type, if not already set.
*/
protected void makeCoordinateAxes() {
// The ones identified as coordinate variables or axes
for (VarProcess vp : varList) {
if (vp.isCoordinateAxis || vp.isCoordinateVariable) {
if (vp.axisType == null) {
vp.axisType = getAxisType(vp.vb);
}
if (vp.axisType == null) {
userAdvice.format("Coordinate Axis %s does not have an assigned AxisType%n", vp);
}
vp.makeIntoCoordinateAxis();
}
}
// The ones marked as Coordinate Systems, which will reference Coordinates
for (VarProcess vp : varList) {
if (vp.isCoordinateSystem) {
vp.makeCoordinatesFromCoordinateSystem();
}
}
}
protected void makeCoordinateSystems() {
// The ones marked as Coordinate Systems, which will reference Coordinates
for (VarProcess vp : varList) {
if (vp.isCoordinateSystem) {
vp.makeCoordinateSystem();
}
}
}
/**
* Assign explicit CoordinateSystem objects to variables.
*/
protected void assignCoordinateSystemsExplicit() {
// look for explicit references to coord sys variables
for (VarProcess vp : varList) {
if (vp.coordinateSystems != null && !vp.isCoordinateTransform) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateSystems);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap == null) {
parseInfo.format("***Cant find Coordinate System variable %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Cant find Coordinate System variable %s referenced from var= %s%n", vname, vp);
} else if (ap.cs == null) {
parseInfo.format("***Not a Coordinate System variable %s referenced from var= %s%n", vname, vp);
userAdvice.format("***Not a Coordinate System variable %s referenced from var= %s%n", vname, vp);
} else {
String sysName = coords.makeCanonicalName(vp.vb, ap.cs.coordAxesNames);
vp.vb.addCoordinateSystemName(sysName);
}
}
}
}
// look for explicit references from coord sys variables to data variables
for (VarProcess csVar : varList) {
if (!csVar.isCoordinateSystem || (csVar.coordinateSystemsFor == null)) {
continue;
}
// get list of dimensions from '_CoordinateSystemFor' attribute
Set<String> dimList = new HashSet<>();
StringTokenizer stoker = new StringTokenizer(csVar.coordinateSystemsFor);
while (stoker.hasMoreTokens()) {
String dname = stoker.nextToken();
Optional<Dimension> dimOpt = rootGroup.findDimension(dname);
if (dimOpt.isPresent()) {
dimList.add(dimOpt.get().getShortName());
} else {
parseInfo.format("***Cant find Dimension %s referenced from CoordSys var= %s%n", dname, csVar);
userAdvice.format("***Cant find Dimension %s referenced from CoordSys var= %s%n", dname, csVar);
}
}
// look for vars with those dimensions
for (VarProcess vp : varList) {
if (!vp.hasCoordinateSystem() && vp.isData() && (csVar.cs != null)) {
if (CoordinateSystem.isSubset(dimList, vp.vb.getDimensionsAll())
&& CoordinateSystem.isSubset(vp.vb.getDimensionsAll(), dimList)) {
vp.vb.addCoordinateSystemName(csVar.cs.coordAxesNames);
}
}
}
}
// look for explicit listings of coordinate axes
for (VarProcess vp : varList) {
if (!vp.hasCoordinateSystem() && (vp.coordinateAxes != null) && vp.isData()) {
String coordSysName = coords.makeCanonicalName(vp.vb, vp.coordinateAxes);
Optional<CoordinateSystem.Builder> cso = coords.findCoordinateSystem(coordSysName);
if (cso.isPresent()) {
vp.vb.addCoordinateSystemName(coordSysName);
parseInfo.format(" assigned explicit CoordSystem '%s' for var= %s%n", coordSysName, vp);
} else {
CoordinateSystem.Builder csnew = CoordinateSystem.builder().setCoordAxesNames(coordSysName);
coords.addCoordinateSystem(csnew);
vp.vb.addCoordinateSystemName(coordSysName);
parseInfo.format(" created explicit CoordSystem '%s' for var= %s%n", coordSysName, vp);
}
}
}
}
/**
* Make implicit CoordinateSystem objects for variables that dont already have one, by using the
* variables' list of coordinate axes, and any coordinateVariables for it. Must be at least 2
* axes. All of a variable's _Coordinate Variables_ plus any variables listed in a
* *__CoordinateAxes_* or *_coordinates_* attribute will be made into an *_implicit_* Coordinate
* System. If there are at least two axes, and the coordinate system uses all of the variable's
* dimensions, it will be assigned to the data variable.
*/
protected void makeCoordinateSystemsImplicit() {
for (VarProcess vp : varList) {
if (!vp.hasCoordinateSystem() && vp.maybeData()) {
List<CoordinateAxis.Builder> dataAxesList = vp.findCoordinateAxes(true);
if (dataAxesList.size() < 2) {
continue;
}
String csName = coords.makeCanonicalName(dataAxesList);
Optional<CoordinateSystem.Builder> csOpt = coords.findCoordinateSystem(csName);
if (csOpt.isPresent() && coords.isComplete(csOpt.get(), vp.vb)) {
vp.vb.addCoordinateSystemName(csName);
parseInfo.format(" assigned implicit CoordSystem '%s' for var= %s%n", csName, vp);
} else {
CoordinateSystem.Builder csnew = CoordinateSystem.builder().setCoordAxesNames(csName).setImplicit(true);
if (coords.isComplete(csnew, vp.vb)) {
vp.vb.addCoordinateSystemName(csName);
coords.addCoordinateSystem(csnew);
parseInfo.format(" created implicit CoordSystem '%s' for var= %s%n", csName, vp);
}
}
}
}
}
/**
* If a variable still doesnt have a coordinate system, use hueristics to try to find one that was
* probably forgotten. Examine existing CS. create a subset of axes that fits the variable. Choose
* the one with highest rank. It must have X,Y or lat,lon. If so, add it.
*/
private void makeCoordinateSystemsMaximal() {
boolean requireCompleteCoordSys =
!datasetBuilder.getEnhanceMode().contains(NetcdfDataset.Enhance.IncompleteCoordSystems);
for (VarProcess vp : varList) {
if (vp.hasCoordinateSystem() || !vp.isData()) {
continue;
}
// look through all axes that fit
List<CoordinateAxis.Builder> axisList = new ArrayList<>();
for (CoordinateAxis.Builder axis : coords.coordAxes) {
if (isCoordinateAxisForVariable(axis, vp)) {
axisList.add(axis);
}
}
if (axisList.size() < 2) {
continue;
}
String csName = coords.makeCanonicalName(axisList);
Optional<CoordinateSystem.Builder> csOpt = coords.findCoordinateSystem(csName);
boolean okToBuild = false;
// do coordinate systems need to be complete?
// default enhance mode is yes, they must be complete
if (requireCompleteCoordSys) {
if (csOpt.isPresent()) {
// only build if coordinate system is complete
okToBuild = coords.isComplete(csOpt.get(), vp.vb);
}
} else {
// coordinate system can be incomplete, so we're ok to build if we find something
okToBuild = true;
}
if (csOpt.isPresent() && okToBuild) {
vp.vb.addCoordinateSystemName(csName);
parseInfo.format(" assigned maximal CoordSystem '%s' for var= %s%n", csName, vp);
} else {
CoordinateSystem.Builder csnew = CoordinateSystem.builder().setCoordAxesNames(csName);
// again, do coordinate systems need to be complete?
// default enhance mode is yes, they must be complete
if (requireCompleteCoordSys) {
// only build if new coordinate system is complete
okToBuild = coords.isComplete(csnew, vp.vb);
}
if (okToBuild) {
csnew.setImplicit(true);
vp.vb.addCoordinateSystemName(csName);
coords.addCoordinateSystem(csnew);
parseInfo.format(" created maximal CoordSystem '%s' for var= %s%n", csnew.coordAxesNames, vp);
}
}
}
}
/**
* Take all previously identified Coordinate Transforms and create a CoordinateTransform object by
* calling CoordTransBuilder.makeCoordinateTransform().
*/
protected void makeCoordinateTransforms() {
for (VarProcess vp : varList) {
if (vp.isCoordinateTransform && vp.ct == null) { // TODO dont have ncd
vp.ct = makeCoordinateTransform(vp.vb);
if (vp.ct != null) {
coords.addCoordinateTransform(vp.ct);
}
}
}
}
protected CoordinateTransform.Builder makeCoordinateTransform(VariableDS.Builder<?> vb) {
return CoordinateTransform.builder().setName(vb.getFullName()).setAttributeContainer(vb.getAttributeContainer());
}
/** Assign CoordinateTransform objects to Variables and Coordinate Systems. */
protected void assignCoordinateTransforms() {
// look for explicit transform assignments on the coordinate systems
for (VarProcess vp : varList) {
if (vp.isCoordinateSystem && vp.coordinateTransforms != null) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateTransforms);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, vp);
if (ap != null) {
if (ap.ct != null) {
vp.addCoordinateTransform(ap.ct);
parseInfo.format(" assign explicit coordTransform %s to CoordSys= %s%n", ap.ct, vp.cs);
} else {
parseInfo.format("***Cant find coordTransform in %s referenced from var= %s%n", vname,
vp.vb.getFullName());
userAdvice.format("***Cant find coordTransform in %s referenced from var= %s%n", vname,
vp.vb.getFullName());
}
} else {
parseInfo.format("***Cant find coordTransform variable= %s referenced from var= %s%n", vname,
vp.vb.getFullName());
userAdvice.format("***Cant find coordTransform variable= %s referenced from var= %s%n", vname,
vp.vb.getFullName());
}
}
}
}
// look for explicit coordSys assignments on the coordinate transforms
for (VarProcess vp : varList) {
if (vp.isCoordinateTransform && (vp.ct != null) && (vp.coordinateSystems != null)) {
StringTokenizer stoker = new StringTokenizer(vp.coordinateSystems);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess vcs = findVarProcess(vname, vp);
if (vcs == null) {
parseInfo.format("***Cant find coordSystem variable= %s referenced from var= %s%n", vname,
vp.vb.getFullName());
userAdvice.format("***Cant find coordSystem variable= %s referenced from var= %s%n", vname,
vp.vb.getFullName());
} else {
vcs.addCoordinateTransform(vp.ct);
parseInfo.format("***assign explicit coordTransform %s to CoordSys= %s%n", vp.ct, vp.cs);
}
}
}
}
// look for coordAxes assignments on the coordinate transforms
for (VarProcess vp : varList) {
if (vp.isCoordinateTransform && (vp.ct != null) && (vp.coordinateAxes != null)) {
List<CoordinateAxis.Builder> dataAxesList = vp.findCoordinateAxes(false);
if (!dataAxesList.isEmpty()) {
for (CoordinateSystem.Builder cs : coords.coordSys) {
if (coords.containsAxes(cs, dataAxesList)) {
coords.addCoordinateTransform(vp.ct);
cs.addCoordinateTransformByName(vp.ct.name);
parseInfo.format("***assign (implicit coordAxes) coordTransform %s to CoordSys= %s%n", vp.ct, cs);
}
}
}
}
}
// look for coordAxisType assignments on the coordinate transforms
for (VarProcess vp : varList) {
if (vp.isCoordinateTransform && (vp.ct != null) && (vp.coordAxisTypes != null)) {
List<AxisType> axisTypesList = new ArrayList<>();
StringTokenizer stoker = new StringTokenizer(vp.coordAxisTypes);
while (stoker.hasMoreTokens()) {
String name = stoker.nextToken();
AxisType atype;
if (null != (atype = AxisType.getType(name))) {
axisTypesList.add(atype);
}
}
if (!axisTypesList.isEmpty()) {
for (CoordinateSystem.Builder cs : coords.coordSys) {
if (coords.containsAxisTypes(cs, axisTypesList)) {
cs.addCoordinateTransformByName(vp.ct.name);
parseInfo.format("***assign (implicit coordAxisType) coordTransform %s to CoordSys= %s%n", vp.ct, cs);
}
}
}
}
}
}
protected VarProcess findVarProcess(String name, VarProcess from) {
if (name == null) {
return null;
}
// compare full name
for (VarProcess vp : varList) {
if (name.equals(vp.vb.getFullName())) {
return vp;
}
}
// prefer ones in the same group
if (from != null) {
for (VarProcess vp : varList) {
if (vp.vb == null || vp.vb.getParentGroupBuilder() == null || from.vb == null) {
continue;
}
if (name.equals(vp.vb.shortName) && vp.vb.getParentGroupBuilder().equals(from.vb.getParentGroupBuilder())) {
return vp;
}
}
}
// WAEF, use short name
for (VarProcess vp : varList) {
if (name.equals(vp.vb.shortName)) {
return vp;
}
}
return null;
}
protected VarProcess findCoordinateAxis(String name) {
if (name == null) {
return null;
}
for (VarProcess vp : varList) {
if (name.equals(vp.vb.getFullName()) && (vp.isCoordinateVariable || vp.isCoordinateAxis)) {
return vp;
}
}
return null;
}
/**
* Create a "dummy" Coordinate Transform Variable based on the given CoordinateTransform.
* This creates a scalar Variable with dummy data, and adds the Parameters of the CoordinateTransform
* as attributes.
*
* @param ct based on the CoordinateTransform
* @return the Coordinate Transform Variable. You must add it to the dataset.
*/
protected VariableDS.Builder makeCoordinateTransformVariable(CoordinateTransform ct) {
VariableDS.Builder v = VariableDS.builder().setName(ct.getName()).setDataType(DataType.CHAR);
List<Parameter> params = ct.getParameters();
for (Parameter p : params) {
if (p.isString())
v.addAttribute(new Attribute(p.getName(), p.getStringValue()));
else {
double[] data = p.getNumericValues();
Array dataA = Array.factory(DataType.DOUBLE, new int[] {data.length}, data);
v.addAttribute(new Attribute(p.getName(), dataA));
}
}
v.addAttribute(new Attribute(_Coordinate.TransformType, ct.getTransformType().toString()));
// fake data
Array data = Array.factory(DataType.CHAR, new int[] {}, new char[] {' '});
v.setCachedData(data, true);
parseInfo.format(" made CoordinateTransformVariable: %s%n", ct.getName());
return v;
}
/** Classifications of Variables into axis, systems and transforms */
protected class VarProcess {
public Group.Builder gb;
public VariableDS.Builder<?> vb;
// attributes
public String coordVarAlias; // _Coordinate.AliasForDimension
public String positive; // _Coordinate.ZisPositive or CF.POSITIVE
public String coordinateAxes; // _Coordinate.Axes
public String coordinateSystems; // _Coordinate.Systems
public String coordinateSystemsFor; // _Coordinate.SystemsFor
public String coordinateTransforms; // _Coordinate.Transforms
public String coordAxisTypes; // _Coordinate.AxisTypes
public String coordTransformType; // _Coordinate.TransformType
public String coordinates; // CF coordinates (set by subclasses)
// coord axes
public boolean isCoordinateVariable; // classic coordinate variable
public boolean isCoordinateAxis;
public AxisType axisType;
public CoordinateAxis.Builder<?> axis; // if its made into a Coordinate Axis, this is not null
// coord systems
public boolean isCoordinateSystem;
public CoordinateSystem.Builder cs;
// coord transform
public boolean isCoordinateTransform;
public CoordinateTransform.Builder ct;
/**
* Wrap the given variable. Identify Coordinate Variables. Process all _Coordinate attributes.
*
* @param v wrap this Variable
*/
private VarProcess(Group.Builder gb, VariableDS.Builder<?> v) {
this.gb = gb;
this.vb = v;
isCoordinateVariable =
isCoordinateVariable(v) || (null != v.getAttributeContainer().findAttribute(_Coordinate.AliasForDimension));
if (isCoordinateVariable) {
String fullDimName = v.getParentGroupBuilder().makeFullName() + v.getFirstDimensionName();
coordVarsForDimension.put(fullDimName, this);
}
Attribute att = v.getAttributeContainer().findAttributeIgnoreCase(_Coordinate.AxisType);
if (att != null) {
String axisName = att.getStringValue();
axisType = AxisType.getType(axisName);
isCoordinateAxis = true;
parseInfo.format(" Coordinate Axis added = %s type= %s%n", v.getFullName(), axisName);
}
coordVarAlias = v.getAttributeContainer().findAttributeString(_Coordinate.AliasForDimension, null);
if (coordVarAlias != null) {
coordVarAlias = coordVarAlias.trim();
if (v.getRank() != 1) {
parseInfo.format("**ERROR Coordinate Variable Alias %s has rank %d%n", v.getFullName(), v.getRank());
userAdvice.format("**ERROR Coordinate Variable Alias %s has rank %d%n", v.getFullName(), v.getRank());
} else {
Optional<Dimension> coordDimOpt = gb.findDimension(coordVarAlias);
coordDimOpt.ifPresent(coordDim -> {
String vDim = v.getFirstDimensionName();
if (!coordDim.getShortName().equals(vDim)) {
parseInfo.format("**ERROR Coordinate Variable Alias %s names wrong dimension %s%n", v.getFullName(),
coordVarAlias);
userAdvice.format("**ERROR Coordinate Variable Alias %s names wrong dimension %s%n", v.getFullName(),
coordVarAlias);
} else {
isCoordinateAxis = true;
coordVarsForDimension.put(coordDim.getShortName(), this);
parseInfo.format(" Coordinate Variable Alias added = %s for dimension= %s%n", v.getFullName(),
coordVarAlias);
}
});
}
}
positive = v.getAttributeContainer().findAttributeString(_Coordinate.ZisPositive, null);
if (positive == null) {
positive = v.getAttributeContainer().findAttributeString(CF.POSITIVE, null);
} else {
isCoordinateAxis = true;
positive = positive.trim();
parseInfo.format(" Coordinate Axis added(from positive attribute ) = %s for dimension= %s%n", v.getFullName(),
coordVarAlias);
}
coordinateAxes = v.getAttributeContainer().findAttributeString(_Coordinate.Axes, null);
coordinateSystems = v.getAttributeContainer().findAttributeString(_Coordinate.Systems, null);
coordinateSystemsFor = v.getAttributeContainer().findAttributeString(_Coordinate.SystemFor, null);
coordinateTransforms = v.getAttributeContainer().findAttributeString(_Coordinate.Transforms, null);
isCoordinateSystem = (coordinateTransforms != null) || (coordinateSystemsFor != null);
coordAxisTypes = v.getAttributeContainer().findAttributeString(_Coordinate.AxisTypes, null);
coordTransformType = v.getAttributeContainer().findAttributeString(_Coordinate.TransformType, null);
isCoordinateTransform = (coordTransformType != null) || (coordAxisTypes != null);
}
protected boolean isData() {
return !isCoordinateVariable && !isCoordinateAxis && !isCoordinateSystem && !isCoordinateTransform;
}
protected boolean maybeData() {
return !isCoordinateVariable && !isCoordinateSystem && !isCoordinateTransform;
}
protected boolean hasCoordinateSystem() {
return !vb.coordSysNames.isEmpty();
}
public String toString() {
return vb.shortName;
}
/**
* Turn the variable into a coordinate axis.
* Add to the dataset, replacing variable if needed.
*
* @return coordinate axis
*/
protected CoordinateAxis.Builder makeIntoCoordinateAxis() {
if (axis != null) {
return axis;
}
if (vb instanceof CoordinateAxis.Builder) {
axis = (CoordinateAxis.Builder) vb;
} else {
// Create a CoordinateAxis out of this variable.
vb = axis = CoordinateAxis.fromVariableDS(vb);
}
if (axisType != null) {
axis.setAxisType(axisType);
axis.addAttribute(new Attribute(_Coordinate.AxisType, axisType.toString()));
if (((axisType == AxisType.Height) || (axisType == AxisType.Pressure) || (axisType == AxisType.GeoZ))
&& (positive != null)) {
axis.setPositive(positive);
axis.addAttribute(new Attribute(_Coordinate.ZisPositive, positive));
}
}
coords.replaceCoordinateAxis(axis);
if (axis.getParentStructureBuilder() != null) {
axis.getParentStructureBuilder().replaceMemberVariable(axis);
} else {
gb.replaceVariable(axis);
}
return axis;
}
/** For any variable listed in a coordinateAxes attribute, make into a coordinate. */
protected void makeCoordinatesFromCoordinateSystem() {
// find referenced coordinate axes
if (coordinateAxes != null) {
StringTokenizer stoker = new StringTokenizer(coordinateAxes); // _CoordinateAxes attribute
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, this);
if (ap != null) {
ap.makeIntoCoordinateAxis();
} else {
parseInfo.format(" Cant find axes %s for Coordinate System %s%n", vname, vb);
userAdvice.format(" Cant find axes %s for Coordinate System %s%n", vname, vb);
}
}
}
}
/** For explicit coordinate system variables, make a CoordinateSystem. */
protected void makeCoordinateSystem() {
if (coordinateAxes != null) {
String sysName = coords.makeCanonicalName(vb, coordinateAxes);
this.cs = CoordinateSystem.builder().setCoordAxesNames(sysName);
parseInfo.format(" Made Coordinate System '%s'", sysName);
coords.addCoordinateSystem(this.cs);
}
}
/**
* Create a list of coordinate axes for this data variable. Use the list of names in axes or
* coordinates field.
*
* @param addCoordVariables if true, add any coordinate variables that are missing.
* @return list of coordinate axes for this data variable.
*/
protected List<CoordinateAxis.Builder> findCoordinateAxes(boolean addCoordVariables) {
List<CoordinateAxis.Builder> axesList = new ArrayList<>();
if (coordinateAxes != null) { // explicit axes
StringTokenizer stoker = new StringTokenizer(coordinateAxes);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, this);
if (ap != null) {
CoordinateAxis.Builder axis = ap.makeIntoCoordinateAxis();
if (!axesList.contains(axis)) {
axesList.add(axis);
}
}
}
} else if (coordinates != null) { // CF partial listing of axes
StringTokenizer stoker = new StringTokenizer(coordinates);
while (stoker.hasMoreTokens()) {
String vname = stoker.nextToken();
VarProcess ap = findVarProcess(vname, this);
if (ap != null) {
CoordinateAxis.Builder axis = ap.makeIntoCoordinateAxis(); // LOOK check if its legal
if (!axesList.contains(axis)) {
axesList.add(axis);
}
}
}
}
if (addCoordVariables) {
for (String d : vb.getDimensionsAll()) {
for (VarProcess vp : coordVarsForDimension.get(d)) {
CoordinateAxis.Builder axis = vp.makeIntoCoordinateAxis();
if (!axesList.contains(axis)) {
axesList.add(axis);
}
}
}
}
return axesList;
}
void addCoordinateTransform(CoordinateTransform.Builder ct) {
if (cs == null) {
parseInfo.format(" %s: no CoordinateSystem for CoordinateTransformVariable: %s%n", vb.getFullName(), ct.name);
return;
}
cs.addCoordinateTransformByName(ct.name);
}
} // VarProcess
}
|
Track dimensions using their full name when building coordinate systems
|
cdm/core/src/main/java/ucar/nc2/internal/dataset/CoordSystemBuilder.java
|
Track dimensions using their full name when building coordinate systems
|
<ide><path>dm/core/src/main/java/ucar/nc2/internal/dataset/CoordSystemBuilder.java
<ide> import ucar.nc2.Attribute;
<ide> import ucar.nc2.Dimension;
<ide> import ucar.nc2.Group;
<add>import ucar.nc2.NetcdfFiles;
<ide> import ucar.nc2.Variable;
<ide> import ucar.nc2.constants.AxisType;
<ide> import ucar.nc2.constants.CF;
<ide> import ucar.nc2.dataset.VariableDS;
<ide> import ucar.nc2.dataset.spi.CoordSystemBuilderFactory;
<ide> import ucar.nc2.util.CancelTask;
<add>import ucar.nc2.util.EscapeStrings;
<ide> import ucar.unidata.util.Parameter;
<ide>
<ide> /**
<ide> protected CoordinatesHelper.Builder coords;
<ide>
<ide> protected List<VarProcess> varList = new ArrayList<>();
<del> // coordinate variables for Dimension (name)
<add> // coordinate variables for Dimension (full name)
<ide> protected Multimap<String, VarProcess> coordVarsForDimension = ArrayListMultimap.create();
<ide> // default name of Convention, override in subclass
<ide> protected String conventionName = _Coordinate.Convention;
<ide> return v;
<ide> }
<ide>
<add> @Nullable
<add> private String findDimFullName(Variable.Builder vb, String dimShortName) {
<add> String dimName = EscapeStrings.backslashEscape(dimShortName, NetcdfFiles.reservedFullName);
<add> // In order to get the "full" dimension name, we need to know what group it lives in. We will start in the group
<add> // that the variable belongs to and work our way up the group tree. If we don't find the dimension, we get null.
<add> Group.Builder gb = vb.getParentGroupBuilder();
<add> return findDimension(gb, dimShortName);
<add> }
<add>
<add> @Nullable
<add> private String findDimension(@Nullable Group.Builder gb, String dimName) {
<add> if (gb == null) {
<add> return null;
<add> } else {
<add> Optional<Dimension> dim = gb.findDimensionLocal(dimName);
<add> return dim.isPresent() ? makeDimFullName(gb, dimName) : findDimension(gb.getParentGroup(), dimName);
<add> }
<add> }
<add>
<add> private String makeDimFullName(Variable.Builder vb, Dimension d) {
<add> return makeDimFullName(vb.getParentGroupBuilder(), d);
<add> }
<add>
<add> private String makeDimFullName(Variable.Builder vb, String dimName) {
<add> return makeDimFullName(vb.getParentGroupBuilder(), dimName);
<add> }
<add>
<add> private String makeDimFullName(Group.Builder gb, Dimension d) {
<add> return makeDimFullName(gb, d.getShortName());
<add> }
<add>
<add> private String makeDimFullName(Group.Builder gb, String dimShortName) {
<add> String dimName = EscapeStrings.backslashEscape(dimShortName, NetcdfFiles.reservedFullName);
<add> return gb.makeFullName() + dimName;
<add> }
<add>
<ide> /** Classifications of Variables into axis, systems and transforms */
<ide> protected class VarProcess {
<ide> public Group.Builder gb;
<ide> isCoordinateVariable =
<ide> isCoordinateVariable(v) || (null != v.getAttributeContainer().findAttribute(_Coordinate.AliasForDimension));
<ide> if (isCoordinateVariable) {
<del> String fullDimName = v.getParentGroupBuilder().makeFullName() + v.getFirstDimensionName();
<del> coordVarsForDimension.put(fullDimName, this);
<add> String dimFullName = makeDimFullName(v, v.getFirstDimensionName());
<add> coordVarsForDimension.put(dimFullName, this);
<ide> }
<ide>
<ide> Attribute att = v.getAttributeContainer().findAttributeIgnoreCase(_Coordinate.AxisType);
<ide> coordVarAlias);
<ide> } else {
<ide> isCoordinateAxis = true;
<del> coordVarsForDimension.put(coordDim.getShortName(), this);
<add> String dimFullName = makeDimFullName(v, coordDim);
<add> coordVarsForDimension.put(dimFullName, this);
<ide> parseInfo.format(" Coordinate Variable Alias added = %s for dimension= %s%n", v.getFullName(),
<ide> coordVarAlias);
<ide> }
<ide>
<ide> if (addCoordVariables) {
<ide> for (String d : vb.getDimensionsAll()) {
<del> for (VarProcess vp : coordVarsForDimension.get(d)) {
<add> String dimFullName = findDimFullName(vb, d);
<add> for (VarProcess vp : coordVarsForDimension.get(dimFullName)) {
<ide> CoordinateAxis.Builder axis = vp.makeIntoCoordinateAxis();
<ide> if (!axesList.contains(axis)) {
<ide> axesList.add(axis);
|
|
JavaScript
|
mit
|
6f1339057ef5b7fbe79f0731c54b53220419eac5
| 0 |
mikhail-angelov/bconf,mikhail-angelov/bconf,mikhail-angelov/bconf,mikhail-angelov/bconf
|
const _ = require('lodash')
const shortid = require('shortid')
const auth = require('./auth')
const database = require('./db')
const USER_CHATS = 'userChats'
const MESSAGES = 'messages'
const online = {}
const pushNotification = require('./pushNotification')
function init(server) {
const io = require('socket.io')(server)
io.use((socket, next) => {
console.log('io socket handshake: ')
if (socket.handshake.query && socket.handshake.query.token) {
const decoded = auth.decodeToken(socket.handshake.query.token)
socket.decoded = decoded;
next();
} else {
next(new Error('Authentication error'));
}
})
io.on('connection', onConnection)
}
function onConnection(socket) {
console.log('onConnection socket: ', socket.decoded)
const user = socket.decoded
if (!user) {
socket.disconnect()
return 'invalid token'
}
online[user._id] = socket
socket.on('disconnect', () => {
console.info('user disconnected:', user._id)
online[user._id] = null
})
socket.on('message', (data) => {
console.info(`message:send data, ${JSON.stringify(data)}`)
processMessage({ user, data, online })
})
}
async function processMessage({ user, data, online }) {
console.log('data', data)
try {
const parsed = JSON.parse(data)
const db = await database.db()
const message = {
_id: shortid.generate(),
chatId: parsed.chatId,
text: parsed.message.text,
links: parsed.message.links,
audioLinks: parsed.message.audioLinks,
author: user,
timestamp: Date.now(),
}
const chatId = parsed.chatId
await db.collection(MESSAGES).insertOne(message)
await db.collection(USER_CHATS).updateMany({ chatId }, {
$set: {
lastMessageText: message.text,
lastMessageId: message._id,
lastMessageAuthor: user.name,
lastMessageAuthorId: user._id,
lastMessageTimestamp: message.timestamp
}
})
await pushNotification.send({ text: parsed.message.text, chatId })
//todo: temp common broadcast
_.each(online, socket => {
socket && socket.send(message)
})
} catch (e) {
console.error('cannot send message, ', e)
}
}
async function getChat(chatId) {
const db = await database.db()
const userChats = await db.collection(USER_CHATS).find({ chatId }).toArray()
return {
chatId: _.get(userChats, '0.chatId'),
chatName: _.get(userChats, '0.chatName'),
chatImage: _.get(userChats, '0.chatImage'),
users: _.map(userChats, item => ({ _id: item.userId, name: item.userName }))
}
}
async function getChats(user) {
const db = await database.db()
const userChats = await db.collection(USER_CHATS).find({ userId: user._id }).toArray()
return userChats
}
async function createChat({ user, request }) {
const { users, chatName } = request
const chatId = shortid.generate()
const db = await database.db()
await db.collection(USER_CHATS).insertOne({
chatId, chatName,
userId: user._id, userName: user.name
})
if (_.get(users, 'length') > 0) {
for (let contact of users) {
await db.collection(USER_CHATS).insertOne({
chatId, chatName,
userId: contact._id, userName: contact.name
})
}
}
return getChat(chatId)
}
async function updateChat({ user, request }) {
const { chatId, chatName, chatImage } = request
let response
const db = await database.db()
const isUserInChat = await db.collection(USER_CHATS).find({ userId: user._id, chatId }).toArray()
if (isUserInChat.length > 0) {
response = await db.collection(USER_CHATS).updateMany(
{ chatId },
{ $set: { chatName, chatImage } },
)
}
if (!response.result.ok) {
return Promise.reject('invalid params')
}
return getChat(chatId)
}
async function addUser({ user, request }) {
const { chat } = request
const newUser = request.user
if (!chat || !newUser) {
return Promise.reject('invalid params')
}
const db = await database.db()
const response = await db.collection(USER_CHATS)
.find({ chatId: chat.chatId, userId: newUser._id }).toArray()
if (response.length > 0) {
return Promise.reject('user already added')
}
await db.collection(USER_CHATS).insertOne({
chatId: chat.chatId, chatName: chat.chatName,
userId: newUser._id, userName: newUser.name
})
//todo: notify this user
return { ok: 'success' }
}
async function getMessages({ user, chatId, query }) {
if (chatId && user) {
const db = await database.db()
const messages = await db.collection(MESSAGES).find({ chatId, timestamp: { $gt: query.timestamp } }).toArray()
return messages
} else {
return Promise.reject('Invalid param')
}
}
module.exports = {
init,
getChat,
getChats,
createChat,
updateChat,
addUser,
getMessages,
//private method only
processMessage,
}
|
now/chat.js
|
const _ = require('lodash')
const shortid = require('shortid')
const auth = require('./auth')
const database = require('./db')
const USER_CHATS = 'userChats'
const MESSAGES = 'messages'
const online = {}
const pushNotification = require('./pushNotification')
function init(server) {
const io = require('socket.io')(server)
io.use((socket, next) => {
console.log('io socket handshake: ')
if (socket.handshake.query && socket.handshake.query.token) {
const decoded = auth.decodeToken(socket.handshake.query.token)
socket.decoded = decoded;
next();
} else {
next(new Error('Authentication error'));
}
})
io.on('connection', onConnection)
}
function onConnection(socket) {
console.log('onConnection socket: ', socket.decoded)
const user = socket.decoded
if (!user) {
socket.disconnect()
return 'invalid token'
}
online[user._id] = socket
socket.on('disconnect', () => {
console.info('user disconnected:', user._id)
online[user._id] = null
})
socket.on('message', (data) => {
console.info(`message:send data, ${JSON.stringify(data)}`)
processMessage({ user, data, online })
})
}
async function processMessage({ user, data, online }) {
console.log('data', data)
try {
const parsed = JSON.parse(data)
const db = await database.db()
const message = {
_id: shortid.generate(),
chatId: parsed.chatId,
text: parsed.message.text,
links: parsed.message.links,
author: user,
timestamp: Date.now(),
}
const chatId = parsed.chatId
await db.collection(MESSAGES).insertOne(message)
await db.collection(USER_CHATS).updateMany({ chatId }, {
$set: {
lastMessageText: message.text,
lastMessageId: message._id,
lastMessageAuthor: user.name,
lastMessageAuthorId: user._id,
lastMessageTimestamp: message.timestamp
}
})
await pushNotification.send({ text: parsed.message.text, chatId })
//todo: temp common broadcast
_.each(online, socket => {
socket && socket.send(message)
})
} catch (e) {
console.error('cannot send message, ', e)
}
}
async function getChat(chatId) {
const db = await database.db()
const userChats = await db.collection(USER_CHATS).find({ chatId }).toArray()
return {
chatId: _.get(userChats, '0.chatId'),
chatName: _.get(userChats, '0.chatName'),
chatImage: _.get(userChats, '0.chatImage'),
users: _.map(userChats, item => ({ _id: item.userId, name: item.userName }))
}
}
async function getChats(user) {
const db = await database.db()
const userChats = await db.collection(USER_CHATS).find({ userId: user._id }).toArray()
return userChats
}
async function createChat({ user, request }) {
const { users, chatName } = request
const chatId = shortid.generate()
const db = await database.db()
await db.collection(USER_CHATS).insertOne({
chatId, chatName,
userId: user._id, userName: user.name
})
if (_.get(users, 'length') > 0) {
for (let contact of users) {
await db.collection(USER_CHATS).insertOne({
chatId, chatName,
userId: contact._id, userName: contact.name
})
}
}
return getChat(chatId)
}
async function updateChat({ user, request }) {
const { chatId, chatName, chatImage } = request
let response
const db = await database.db()
const isUserInChat = await db.collection(USER_CHATS).find({ userId: user._id, chatId }).toArray()
if (isUserInChat.length > 0) {
response = await db.collection(USER_CHATS).updateMany(
{ chatId },
{ $set: { chatName, chatImage } },
)
}
if (!response.result.ok) {
return Promise.reject('invalid params')
}
return getChat(chatId)
}
async function addUser({ user, request }) {
const { chat } = request
const newUser = request.user
if (!chat || !newUser) {
return Promise.reject('invalid params')
}
const db = await database.db()
const response = await db.collection(USER_CHATS)
.find({ chatId: chat.chatId, userId: newUser._id }).toArray()
if (response.length > 0) {
return Promise.reject('user already added')
}
await db.collection(USER_CHATS).insertOne({
chatId: chat.chatId, chatName: chat.chatName,
userId: newUser._id, userName: newUser.name
})
//todo: notify this user
return { ok: 'success' }
}
async function getMessages({ user, chatId, query }) {
if (chatId && user) {
const db = await database.db()
const messages = await db.collection(MESSAGES).find({ chatId, timestamp: { $gt: query.timestamp } }).toArray()
return messages
} else {
return Promise.reject('Invalid param')
}
}
module.exports = {
init,
getChat,
getChats,
createChat,
updateChat,
addUser,
getMessages,
//private method only
processMessage,
}
|
add field "audioLinks"
|
now/chat.js
|
add field "audioLinks"
|
<ide><path>ow/chat.js
<ide> chatId: parsed.chatId,
<ide> text: parsed.message.text,
<ide> links: parsed.message.links,
<add> audioLinks: parsed.message.audioLinks,
<ide> author: user,
<ide> timestamp: Date.now(),
<ide> }
|
|
JavaScript
|
mit
|
b5ff4079a0cd184311a4f6b38c3d10349f559773
| 0 |
Klaudit/resumable.js,team-enceladus/resumable,23/resumable.js,jimdoescode/resumable.js,szelcsanyi/resumable.js,gdseller/resumable.js,gdseller/resumable.js,team-enceladus/resumable,atlassian/resumable.js,Parent5446/resumable.js,vsivsi/resumable.js,23/resumable.js,Parent5446/resumable.js,Klaudit/resumable.js,vsivsi/resumable.js,fjalex/resumable.js,wyxacc/resumable.js,23/resumable.js,atlassian/resumable.js,team-enceladus/resumable,szelcsanyi/resumable.js,wyxacc/resumable.js,fjalex/resumable.js
|
/*
* MIT Licensed
* http://www.23developer.com/opensource
* http://github.com/23/resumable.js
* Steffen Tiedemann Christensen, [email protected]
*/
(function(){
"use strict";
var Resumable = function(opts){
if ( !(this instanceof Resumable) ) {
return new Resumable(opts);
}
this.version = 1.0;
// SUPPORTED BY BROWSER?
// Check if these features are support by the browser:
// - File object type
// - Blob object type
// - FileList object type
// - slicing files
this.support = (
(typeof(File)!=='undefined')
&&
(typeof(Blob)!=='undefined')
&&
(typeof(FileList)!=='undefined')
&&
(!!Blob.prototype.webkitSlice||!!Blob.prototype.mozSlice||!!Blob.prototype.slice||false)
);
if(!this.support) return(false);
// PROPERTIES
var $ = this;
$.files = [];
$.defaults = {
chunkSize:1*1024*1024,
forceChunkSize:false,
simultaneousUploads:3,
fileParameterName:'file',
throttleProgressCallbacks:0.5,
query:{},
headers:{},
preprocess:null,
method:'multipart',
prioritizeFirstAndLastChunk:false,
target:'/',
testChunks:true,
generateUniqueIdentifier:null,
maxChunkRetries:undefined,
chunkRetryInterval:undefined,
permanentErrors:[404, 415, 500, 501],
maxFiles:undefined,
withCredentials:false,
xhrTimeout:0,
maxFilesErrorCallback:function (files, errorCount) {
var maxFiles = $.getOpt('maxFiles');
alert('Please upload ' + maxFiles + ' file' + (maxFiles === 1 ? '' : 's') + ' at a time.');
},
minFileSize:1,
minFileSizeErrorCallback:function(file, errorCount) {
alert(file.fileName||file.name +' is too small, please upload files larger than ' + $h.formatSize($.getOpt('minFileSize')) + '.');
},
maxFileSize:undefined,
maxFileSizeErrorCallback:function(file, errorCount) {
alert(file.fileName||file.name +' is too large, please upload files less than ' + $h.formatSize($.getOpt('maxFileSize')) + '.');
},
fileType: [],
fileTypeErrorCallback: function(file, errorCount) {
alert(file.fileName||file.name +' has type not allowed, please upload files of type ' + $.getOpt('fileType') + '.');
}
};
$.opts = opts||{};
$.getOpt = function(o) {
var $opt = this;
// Get multiple option if passed an array
if(o instanceof Array) {
var options = {};
$h.each(o, function(option){
options[option] = $opt.getOpt(option);
});
return options;
}
// Otherwise, just return a simple option
if ($opt instanceof ResumableChunk) {
if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; }
else { $opt = $opt.fileObj; }
}
if ($opt instanceof ResumableFile) {
if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; }
else { $opt = $opt.resumableObj; }
}
if ($opt instanceof Resumable) {
if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; }
else { return $opt.defaults[o]; }
}
};
// EVENTS
// catchAll(event, ...)
// fileSuccess(file), fileProgress(file), fileAdded(file, event), fileRetry(file), fileError(file, message),
// complete(), progress(), error(message, file), pause()
$.events = [];
$.on = function(event,callback){
$.events.push(event.toLowerCase(), callback);
};
$.fire = function(){
// `arguments` is an object, not array, in FF, so:
var args = [];
for (var i=0; i<arguments.length; i++) args.push(arguments[i]);
// Find event listeners, and support pseudo-event `catchAll`
var event = args[0].toLowerCase();
for (var i=0; i<=$.events.length; i+=2) {
if($.events[i]==event) $.events[i+1].apply($,args.slice(1));
if($.events[i]=='catchall') $.events[i+1].apply(null,args);
}
if(event=='fileerror') $.fire('error', args[2], args[1]);
if(event=='fileprogress') $.fire('progress');
};
// INTERNAL HELPER METHODS (handy, but ultimately not part of uploading)
var $h = {
stopEvent: function(e){
e.stopPropagation();
e.preventDefault();
},
each: function(o,callback){
if(typeof(o.length)!=='undefined') {
for (var i=0; i<o.length; i++) {
// Array or FileList
if(callback(o[i])===false) return;
}
} else {
for (i in o) {
// Object
if(callback(i,o[i])===false) return;
}
}
},
generateUniqueIdentifier:function(file){
var custom = $.getOpt('generateUniqueIdentifier');
if(typeof custom === 'function') {
return custom(file);
}
var relativePath = file.webkitRelativePath||file.fileName||file.name; // Some confusion in different versions of Firefox
var size = file.size;
return(size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, ''));
},
contains:function(array,test) {
var result = false;
$h.each(array, function(value) {
if (value == test) {
result = true;
return false;
}
return true;
});
return result;
},
formatSize:function(size){
if(size<1024) {
return size + ' bytes';
} else if(size<1024*1024) {
return (size/1024.0).toFixed(0) + ' KB';
} else if(size<1024*1024*1024) {
return (size/1024.0/1024.0).toFixed(1) + ' MB';
} else {
return (size/1024.0/1024.0/1024.0).toFixed(1) + ' GB';
}
},
getTarget:function(params){
var target = $.getOpt('target');
if(target.indexOf('?') < 0) {
target += '?';
} else {
target += '&';
}
return target + params.join('&');
}
};
var onDrop = function(event){
$h.stopEvent(event);
appendFilesFromFileList(event.dataTransfer.files, event);
};
var onDragOver = function(e) {
e.preventDefault();
};
// INTERNAL METHODS (both handy and responsible for the heavy load)
var appendFilesFromFileList = function(fileList, event){
// check for uploading too many files
var errorCount = 0;
var o = $.getOpt(['maxFiles', 'minFileSize', 'maxFileSize', 'maxFilesErrorCallback', 'minFileSizeErrorCallback', 'maxFileSizeErrorCallback', 'fileType', 'fileTypeErrorCallback']);
if (typeof(o.maxFiles)!=='undefined' && o.maxFiles<(fileList.length+$.files.length)) {
// if single-file upload, file is already added, and trying to add 1 new file, simply replace the already-added file
if (o.maxFiles===1 && $.files.length===1 && fileList.length===1) {
$.removeFile($.files[0]);
} else {
o.maxFilesErrorCallback(fileList, errorCount++);
return false;
}
}
var files = [], fileName = '', fileType = '';
$h.each(fileList, function(file){
fileName = file.name.split('.');
fileType = fileName[fileName.length-1].toLowerCase();
if (o.fileType.length > 0 && !$h.contains(o.fileType, fileType)) {
o.fileTypeErrorCallback(file, errorCount++);
return false;
}
if (typeof(o.minFileSize)!=='undefined' && file.size<o.minFileSize) {
o.minFileSizeErrorCallback(file, errorCount++);
return false;
}
if (typeof(o.maxFileSize)!=='undefined' && file.size>o.maxFileSize) {
o.maxFileSizeErrorCallback(file, errorCount++);
return false;
}
// directories have size == 0
if (!$.getFromUniqueIdentifier($h.generateUniqueIdentifier(file))) {
var f = new ResumableFile($, file);
$.files.push(f);
files.push(f);
$.fire('fileAdded', f, event);
}
});
$.fire('filesAdded', files);
};
// INTERNAL OBJECT TYPES
function ResumableFile(resumableObj, file){
var $ = this;
$.opts = {};
$.getOpt = resumableObj.getOpt;
$._prevProgress = 0;
$.resumableObj = resumableObj;
$.file = file;
$.fileName = file.fileName||file.name; // Some confusion in different versions of Firefox
$.size = file.size;
$.relativePath = file.webkitRelativePath || $.fileName;
$.uniqueIdentifier = $h.generateUniqueIdentifier(file);
$._pause = false;
var _error = false;
// Callback when something happens within the chunk
var chunkEvent = function(event, message){
// event can be 'progress', 'success', 'error' or 'retry'
switch(event){
case 'progress':
$.resumableObj.fire('fileProgress', $);
break;
case 'error':
$.abort();
_error = true;
$.chunks = [];
$.resumableObj.fire('fileError', $, message);
break;
case 'success':
if(_error) return;
$.resumableObj.fire('fileProgress', $); // it's at least progress
if($.isComplete()) {
$.resumableObj.fire('fileSuccess', $, message);
}
break;
case 'retry':
$.resumableObj.fire('fileRetry', $);
break;
}
};
// Main code to set up a file object with chunks,
// packaged to be able to handle retries if needed.
$.chunks = [];
$.abort = function(){
// Stop current uploads
var abortCount = 0;
$h.each($.chunks, function(c){
if(c.status()=='uploading') {
c.abort();
abortCount++;
}
});
if(abortCount>0) $.resumableObj.fire('fileProgress', $);
}
$.cancel = function(){
// Reset this file to be void
var _chunks = $.chunks;
$.chunks = [];
// Stop current uploads
$h.each(_chunks, function(c){
if(c.status()=='uploading') {
c.abort();
$.resumableObj.uploadNextChunk();
}
});
$.resumableObj.removeFile($);
$.resumableObj.fire('fileProgress', $);
};
$.retry = function(){
$.bootstrap();
$.resumableObj.upload();
};
$.bootstrap = function(){
$.abort();
_error = false;
// Rebuild stack of chunks from file
$.chunks = [];
$._prevProgress = 0;
var round = $.getOpt('forceChunkSize') ? Math.ceil : Math.floor;
for (var offset=0; offset<Math.max(round($.file.size/$.getOpt('chunkSize')),1); offset++) {
$.chunks.push(new ResumableChunk($.resumableObj, $, offset, chunkEvent));
}
};
$.progress = function(){
if(_error) return(1);
// Sum up progress across everything
var ret = 0;
var error = false;
$h.each($.chunks, function(c){
if(c.status()=='error') error = true;
ret += c.progress(true); // get chunk progress relative to entire file
});
ret = (error ? 1 : (ret>0.999 ? 1 : ret));
ret = Math.max($._prevProgress, ret); // We don't want to lose percentages when an upload is paused
$._prevProgress = ret;
return(ret);
};
$.isUploading = function(){
var uploading = false;
$h.each($.chunks, function(chunk){
if(chunk.status()=='uploading') {
uploading = true;
return(false);
}
});
return(uploading);
};
$.isComplete = function(){
var outstanding = false;
$h.each($.chunks, function(chunk){
var status = chunk.status();
if(status=='pending' || status=='uploading' || chunk.preprocessState === 1) {
outstanding = true;
return(false);
}
});
return(!outstanding);
};
$.pause = function(pause){
if(typeof(pause)==='undefined'){
$._pause = ($._pause ? false : true);
}else{
$._pause = pause;
}
};
$.isPaused = function() {
return $._pause;
};
// Bootstrap and return
$.bootstrap();
return(this);
}
function ResumableChunk(resumableObj, fileObj, offset, callback){
var $ = this;
$.opts = {};
$.getOpt = resumableObj.getOpt;
$.resumableObj = resumableObj;
$.fileObj = fileObj;
$.fileObjSize = fileObj.size;
$.fileObjType = fileObj.file.type;
$.offset = offset;
$.callback = callback;
$.lastProgressCallback = (new Date);
$.tested = false;
$.retries = 0;
$.pendingRetry = false;
$.preprocessState = 0; // 0 = unprocessed, 1 = processing, 2 = finished
// Computed properties
var chunkSize = $.getOpt('chunkSize');
$.loaded = 0;
$.startByte = $.offset*chunkSize;
$.endByte = Math.min($.fileObjSize, ($.offset+1)*chunkSize);
if ($.fileObjSize-$.endByte < chunkSize && !$.getOpt('forceChunkSize')) {
// The last chunk will be bigger than the chunk size, but less than 2*chunkSize
$.endByte = $.fileObjSize;
}
$.xhr = null;
// test() makes a GET request without any data to see if the chunk has already been uploaded in a previous session
$.test = function(){
// Set up request and listen for event
$.xhr = new XMLHttpRequest();
var testHandler = function(e){
$.tested = true;
var status = $.status();
if(status=='success') {
$.callback(status, $.message());
$.resumableObj.uploadNextChunk();
} else {
$.send();
}
};
$.xhr.addEventListener('load', testHandler, false);
$.xhr.addEventListener('error', testHandler, false);
// Add data from the query options
var params = [];
var customQuery = $.getOpt('query');
if(typeof customQuery == 'function') customQuery = customQuery($.fileObj, $);
$h.each(customQuery, function(k,v){
params.push([encodeURIComponent(k), encodeURIComponent(v)].join('='));
});
// Add extra data to identify chunk
params.push(['resumableChunkNumber', encodeURIComponent($.offset+1)].join('='));
params.push(['resumableChunkSize', encodeURIComponent($.getOpt('chunkSize'))].join('='));
params.push(['resumableCurrentChunkSize', encodeURIComponent($.endByte - $.startByte)].join('='));
params.push(['resumableTotalSize', encodeURIComponent($.fileObjSize)].join('='));
params.push(['resumableType', encodeURIComponent($.fileObjType)].join('='));
params.push(['resumableIdentifier', encodeURIComponent($.fileObj.uniqueIdentifier)].join('='));
params.push(['resumableFilename', encodeURIComponent($.fileObj.fileName)].join('='));
params.push(['resumableRelativePath', encodeURIComponent($.fileObj.relativePath)].join('='));
// Append the relevant chunk and send it
$.xhr.open('GET', $h.getTarget(params));
$.xhr.timeout = $.getOpt('xhrTimeout');
$.xhr.withCredentials = $.getOpt('withCredentials');
// Add data from header options
$h.each($.getOpt('headers'), function(k,v) {
$.xhr.setRequestHeader(k, v);
});
$.xhr.send(null);
};
$.preprocessFinished = function(){
$.preprocessState = 2;
$.send();
};
// send() uploads the actual data in a POST call
$.send = function(){
var preprocess = $.getOpt('preprocess');
if(typeof preprocess === 'function') {
switch($.preprocessState) {
case 0: preprocess($); $.preprocessState = 1; return;
case 1: return;
case 2: break;
}
}
if($.getOpt('testChunks') && !$.tested) {
$.test();
return;
}
// Set up request and listen for event
$.xhr = new XMLHttpRequest();
// Progress
$.xhr.upload.addEventListener('progress', function(e){
if( (new Date) - $.lastProgressCallback > $.getOpt('throttleProgressCallbacks') * 1000 ) {
$.callback('progress');
$.lastProgressCallback = (new Date);
}
$.loaded=e.loaded||0;
}, false);
$.loaded = 0;
$.pendingRetry = false;
$.callback('progress');
// Done (either done, failed or retry)
var doneHandler = function(e){
var status = $.status();
if(status=='success'||status=='error') {
$.callback(status, $.message());
$.resumableObj.uploadNextChunk();
} else {
$.callback('retry', $.message());
$.abort();
$.retries++;
var retryInterval = $.getOpt('chunkRetryInterval');
if(retryInterval !== undefined) {
$.pendingRetry = true;
setTimeout($.send, retryInterval);
} else {
$.send();
}
}
};
$.xhr.addEventListener('load', doneHandler, false);
$.xhr.addEventListener('error', doneHandler, false);
// Set up the basic query data from Resumable
var query = {
resumableChunkNumber: $.offset+1,
resumableChunkSize: $.getOpt('chunkSize'),
resumableCurrentChunkSize: $.endByte - $.startByte,
resumableTotalSize: $.fileObjSize,
resumableType: $.fileObjType,
resumableIdentifier: $.fileObj.uniqueIdentifier,
resumableFilename: $.fileObj.fileName,
resumableRelativePath: $.fileObj.relativePath,
resumableTotalChunks: $.fileObj.chunks.length
};
// Mix in custom data
var customQuery = $.getOpt('query');
if(typeof customQuery == 'function') customQuery = customQuery($.fileObj, $);
$h.each(customQuery, function(k,v){
query[k] = v;
});
var func = ($.fileObj.file.slice ? 'slice' : ($.fileObj.file.mozSlice ? 'mozSlice' : ($.fileObj.file.webkitSlice ? 'webkitSlice' : 'slice'))),
bytes = $.fileObj.file[func]($.startByte,$.endByte),
data = null,
target = $.getOpt('target');
if ($.getOpt('method') === 'octet') {
// Add data from the query options
data = bytes;
var params = [];
$h.each(query, function(k,v){
params.push([encodeURIComponent(k), encodeURIComponent(v)].join('='));
});
target = $h.getTarget(params);
} else {
// Add data from the query options
data = new FormData();
$h.each(query, function(k,v){
data.append(k,v);
});
data.append($.getOpt('fileParameterName'), bytes);
}
$.xhr.open('POST', target);
$.xhr.timeout = $.getOpt('xhrTimeout');
$.xhr.withCredentials = $.getOpt('withCredentials');
// Add data from header options
$h.each($.getOpt('headers'), function(k,v) {
$.xhr.setRequestHeader(k, v);
});
$.xhr.send(data);
};
$.abort = function(){
// Abort and reset
if($.xhr) $.xhr.abort();
$.xhr = null;
};
$.status = function(){
// Returns: 'pending', 'uploading', 'success', 'error'
if($.pendingRetry) {
// if pending retry then that's effectively the same as actively uploading,
// there might just be a slight delay before the retry starts
return('uploading')
} else if(!$.xhr) {
return('pending');
} else if($.xhr.readyState<4) {
// Status is really 'OPENED', 'HEADERS_RECEIVED' or 'LOADING' - meaning that stuff is happening
return('uploading');
} else {
if($.xhr.status==200) {
// HTTP 200, perfect
return('success');
} else if($h.contains($.getOpt('permanentErrors'), $.xhr.status) || $.retries >= $.getOpt('maxChunkRetries')) {
// HTTP 415/500/501, permanent error
return('error');
} else {
// this should never happen, but we'll reset and queue a retry
// a likely case for this would be 503 service unavailable
$.abort();
return('pending');
}
}
};
$.message = function(){
return($.xhr ? $.xhr.responseText : '');
};
$.progress = function(relative){
if(typeof(relative)==='undefined') relative = false;
var factor = (relative ? ($.endByte-$.startByte)/$.fileObjSize : 1);
if($.pendingRetry) return(0);
var s = $.status();
switch(s){
case 'success':
case 'error':
return(1*factor);
case 'pending':
return(0*factor);
default:
return($.loaded/($.endByte-$.startByte)*factor);
}
};
return(this);
}
// QUEUE
$.uploadNextChunk = function(){
var found = false;
// In some cases (such as videos) it's really handy to upload the first
// and last chunk of a file quickly; this let's the server check the file's
// metadata and determine if there's even a point in continuing.
if ($.getOpt('prioritizeFirstAndLastChunk')) {
$h.each($.files, function(file){
if(file.chunks.length && file.chunks[0].status()=='pending' && file.chunks[0].preprocessState === 0) {
file.chunks[0].send();
found = true;
return(false);
}
if(file.chunks.length>1 && file.chunks[file.chunks.length-1].status()=='pending' && file.chunks[0].preprocessState === 0) {
file.chunks[file.chunks.length-1].send();
found = true;
return(false);
}
});
if(found) return(true);
}
// Now, simply look for the next, best thing to upload
$h.each($.files, function(file){
if(file.isPaused()===false){
$h.each(file.chunks, function(chunk){
if(chunk.status()=='pending' && chunk.preprocessState === 0) {
chunk.send();
found = true;
return(false);
}
});
}
if(found) return(false);
});
if(found) return(true);
// The are no more outstanding chunks to upload, check is everything is done
var outstanding = false;
$h.each($.files, function(file){
if(!file.isComplete()) {
outstanding = true;
return(false);
}
});
if(!outstanding) {
// All chunks have been uploaded, complete
$.fire('complete');
}
return(false);
};
// PUBLIC METHODS FOR RESUMABLE.JS
$.assignBrowse = function(domNodes, isDirectory){
if(typeof(domNodes.length)=='undefined') domNodes = [domNodes];
$h.each(domNodes, function(domNode) {
var input;
if(domNode.tagName==='INPUT' && domNode.type==='file'){
input = domNode;
} else {
input = document.createElement('input');
input.setAttribute('type', 'file');
input.style.display = 'none';
domNode.addEventListener('click', function(){
input.click();
}, false);
domNode.appendChild(input);
}
var maxFiles = $.getOpt('maxFiles');
if (typeof(maxFiles)==='undefined'||maxFiles!=1){
input.setAttribute('multiple', 'multiple');
} else {
input.removeAttribute('multiple');
}
if(isDirectory){
input.setAttribute('webkitdirectory', 'webkitdirectory');
} else {
input.removeAttribute('webkitdirectory');
}
// When new files are added, simply append them to the overall list
input.addEventListener('change', function(e){
appendFilesFromFileList(e.target.files);
e.target.value = '';
}, false);
});
};
$.assignDrop = function(domNodes){
if(typeof(domNodes.length)=='undefined') domNodes = [domNodes];
$h.each(domNodes, function(domNode) {
domNode.addEventListener('dragover', onDragOver, false);
domNode.addEventListener('drop', onDrop, false);
});
};
$.unAssignDrop = function(domNodes) {
if (typeof(domNodes.length) == 'undefined') domNodes = [domNodes];
$h.each(domNodes, function(domNode) {
domNode.removeEventListener('dragover', onDragOver);
domNode.removeEventListener('drop', onDrop);
});
};
$.isUploading = function(){
var uploading = false;
$h.each($.files, function(file){
if (file.isUploading()) {
uploading = true;
return(false);
}
});
return(uploading);
};
$.upload = function(){
// Make sure we don't start too many uploads at once
if($.isUploading()) return;
// Kick off the queue
$.fire('uploadStart');
for (var num=1; num<=$.getOpt('simultaneousUploads'); num++) {
$.uploadNextChunk();
}
};
$.pause = function(){
// Resume all chunks currently being uploaded
$h.each($.files, function(file){
file.abort();
});
$.fire('pause');
};
$.cancel = function(){
for(var i = $.files.length - 1; i >= 0; i--) {
$.files[i].cancel();
}
$.fire('cancel');
};
$.progress = function(){
var totalDone = 0;
var totalSize = 0;
// Resume all chunks currently being uploaded
$h.each($.files, function(file){
totalDone += file.progress()*file.size;
totalSize += file.size;
});
return(totalSize>0 ? totalDone/totalSize : 0);
};
$.addFile = function(file){
appendFilesFromFileList([file]);
};
$.removeFile = function(file){
for(var i = $.files.length - 1; i >= 0; i--) {
if($.files[i] === file) {
$.files.splice(i, 1);
}
}
};
$.getFromUniqueIdentifier = function(uniqueIdentifier){
var ret = false;
$h.each($.files, function(f){
if(f.uniqueIdentifier==uniqueIdentifier) ret = f;
});
return(ret);
};
$.getSize = function(){
var totalSize = 0;
$h.each($.files, function(file){
totalSize += file.size;
});
return(totalSize);
};
return(this);
};
// Node.js-style export for Node and Component
if (typeof module != 'undefined') {
module.exports = Resumable;
} else if (typeof define === "function" && define.amd) {
// AMD/requirejs: Define the module
define(function(){
return Resumable;
});
} else {
// Browser: Expose to window
window.Resumable = Resumable;
}
})();
|
resumable.js
|
/*
* MIT Licensed
* http://www.23developer.com/opensource
* http://github.com/23/resumable.js
* Steffen Tiedemann Christensen, [email protected]
*/
(function(){
"use strict";
var Resumable = function(opts){
if ( !(this instanceof Resumable) ) {
return new Resumable(opts);
}
this.version = 1.0;
// SUPPORTED BY BROWSER?
// Check if these features are support by the browser:
// - File object type
// - Blob object type
// - FileList object type
// - slicing files
this.support = (
(typeof(File)!=='undefined')
&&
(typeof(Blob)!=='undefined')
&&
(typeof(FileList)!=='undefined')
&&
(!!Blob.prototype.webkitSlice||!!Blob.prototype.mozSlice||!!Blob.prototype.slice||false)
);
if(!this.support) return(false);
// PROPERTIES
var $ = this;
$.files = [];
$.defaults = {
chunkSize:1*1024*1024,
forceChunkSize:false,
simultaneousUploads:3,
fileParameterName:'file',
throttleProgressCallbacks:0.5,
query:{},
headers:{},
preprocess:null,
method:'multipart',
prioritizeFirstAndLastChunk:false,
target:'/',
testChunks:true,
generateUniqueIdentifier:null,
maxChunkRetries:undefined,
chunkRetryInterval:undefined,
permanentErrors:[404, 415, 500, 501],
maxFiles:undefined,
withCredentials:false,
xhrTimeout:0,
maxFilesErrorCallback:function (files, errorCount) {
var maxFiles = $.getOpt('maxFiles');
alert('Please upload ' + maxFiles + ' file' + (maxFiles === 1 ? '' : 's') + ' at a time.');
},
minFileSize:1,
minFileSizeErrorCallback:function(file, errorCount) {
alert(file.fileName||file.name +' is too small, please upload files larger than ' + $h.formatSize($.getOpt('minFileSize')) + '.');
},
maxFileSize:undefined,
maxFileSizeErrorCallback:function(file, errorCount) {
alert(file.fileName||file.name +' is too large, please upload files less than ' + $h.formatSize($.getOpt('maxFileSize')) + '.');
},
fileType: [],
fileTypeErrorCallback: function(file, errorCount) {
alert(file.fileName||file.name +' has type not allowed, please upload files of type ' + $.getOpt('fileType') + '.');
}
};
$.opts = opts||{};
$.getOpt = function(o) {
var $opt = this;
// Get multiple option if passed an array
if(o instanceof Array) {
var options = {};
$h.each(o, function(option){
options[option] = $opt.getOpt(option);
});
return options;
}
// Otherwise, just return a simple option
if ($opt instanceof ResumableChunk) {
if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; }
else { $opt = $opt.fileObj; }
}
if ($opt instanceof ResumableFile) {
if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; }
else { $opt = $opt.resumableObj; }
}
if ($opt instanceof Resumable) {
if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; }
else { return $opt.defaults[o]; }
}
};
// EVENTS
// catchAll(event, ...)
// fileSuccess(file), fileProgress(file), fileAdded(file, event), fileRetry(file), fileError(file, message),
// complete(), progress(), error(message, file), pause()
$.events = [];
$.on = function(event,callback){
$.events.push(event.toLowerCase(), callback);
};
$.fire = function(){
// `arguments` is an object, not array, in FF, so:
var args = [];
for (var i=0; i<arguments.length; i++) args.push(arguments[i]);
// Find event listeners, and support pseudo-event `catchAll`
var event = args[0].toLowerCase();
for (var i=0; i<=$.events.length; i+=2) {
if($.events[i]==event) $.events[i+1].apply($,args.slice(1));
if($.events[i]=='catchall') $.events[i+1].apply(null,args);
}
if(event=='fileerror') $.fire('error', args[2], args[1]);
if(event=='fileprogress') $.fire('progress');
};
// INTERNAL HELPER METHODS (handy, but ultimately not part of uploading)
var $h = {
stopEvent: function(e){
e.stopPropagation();
e.preventDefault();
},
each: function(o,callback){
if(typeof(o.length)!=='undefined') {
for (var i=0; i<o.length; i++) {
// Array or FileList
if(callback(o[i])===false) return;
}
} else {
for (i in o) {
// Object
if(callback(i,o[i])===false) return;
}
}
},
generateUniqueIdentifier:function(file){
var custom = $.getOpt('generateUniqueIdentifier');
if(typeof custom === 'function') {
return custom(file);
}
var relativePath = file.webkitRelativePath||file.fileName||file.name; // Some confusion in different versions of Firefox
var size = file.size;
return(size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, ''));
},
contains:function(array,test) {
var result = false;
$h.each(array, function(value) {
if (value == test) {
result = true;
return false;
}
return true;
});
return result;
},
formatSize:function(size){
if(size<1024) {
return size + ' bytes';
} else if(size<1024*1024) {
return (size/1024.0).toFixed(0) + ' KB';
} else if(size<1024*1024*1024) {
return (size/1024.0/1024.0).toFixed(1) + ' MB';
} else {
return (size/1024.0/1024.0/1024.0).toFixed(1) + ' GB';
}
},
getTarget:function(params){
var target = $.getOpt('target');
if(target.indexOf('?') < 0) {
target += '?';
} else {
target += '&';
}
return target + params.join('&');
}
};
var onDrop = function(event){
$h.stopEvent(event);
appendFilesFromFileList(event.dataTransfer.files, event);
};
var onDragOver = function(e) {
e.preventDefault();
};
// INTERNAL METHODS (both handy and responsible for the heavy load)
var appendFilesFromFileList = function(fileList, event){
// check for uploading too many files
var errorCount = 0;
var o = $.getOpt(['maxFiles', 'minFileSize', 'maxFileSize', 'maxFilesErrorCallback', 'minFileSizeErrorCallback', 'maxFileSizeErrorCallback', 'fileType', 'fileTypeErrorCallback']);
if (typeof(o.maxFiles)!=='undefined' && o.maxFiles<(fileList.length+$.files.length)) {
// if single-file upload, file is already added, and trying to add 1 new file, simply replace the already-added file
if (o.maxFiles===1 && $.files.length===1 && fileList.length===1) {
$.removeFile($.files[0]);
} else {
o.maxFilesErrorCallback(fileList, errorCount++);
return false;
}
}
var files = [], fileName = '', fileType = '';
$h.each(fileList, function(file){
fileName = file.name.split('.');
fileType = fileName[fileName.length-1].toLowerCase();
if (o.fileType.length > 0 && !$h.contains(o.fileType, fileType)) {
o.fileTypeErrorCallback(file, errorCount++);
return false;
}
if (typeof(o.minFileSize)!=='undefined' && file.size<o.minFileSize) {
o.minFileSizeErrorCallback(file, errorCount++);
return false;
}
if (typeof(o.maxFileSize)!=='undefined' && file.size>o.maxFileSize) {
o.maxFileSizeErrorCallback(file, errorCount++);
return false;
}
// directories have size == 0
if (!$.getFromUniqueIdentifier($h.generateUniqueIdentifier(file))) {
var f = new ResumableFile($, file);
$.files.push(f);
files.push(f);
$.fire('fileAdded', f, event);
}
});
$.fire('filesAdded', files);
};
// INTERNAL OBJECT TYPES
function ResumableFile(resumableObj, file){
var $ = this;
$.opts = {};
$.getOpt = resumableObj.getOpt;
$._prevProgress = 0;
$.resumableObj = resumableObj;
$.file = file;
$.fileName = file.fileName||file.name; // Some confusion in different versions of Firefox
$.size = file.size;
$.relativePath = file.webkitRelativePath || $.fileName;
$.uniqueIdentifier = $h.generateUniqueIdentifier(file);
$._pause = false;
var _error = false;
// Callback when something happens within the chunk
var chunkEvent = function(event, message){
// event can be 'progress', 'success', 'error' or 'retry'
switch(event){
case 'progress':
$.resumableObj.fire('fileProgress', $);
break;
case 'error':
$.abort();
_error = true;
$.chunks = [];
$.resumableObj.fire('fileError', $, message);
break;
case 'success':
if(_error) return;
$.resumableObj.fire('fileProgress', $); // it's at least progress
if($.isComplete()) {
$.resumableObj.fire('fileSuccess', $, message);
}
break;
case 'retry':
$.resumableObj.fire('fileRetry', $);
break;
}
};
// Main code to set up a file object with chunks,
// packaged to be able to handle retries if needed.
$.chunks = [];
$.abort = function(){
// Stop current uploads
var abortCount = 0;
$h.each($.chunks, function(c){
if(c.status()=='uploading') {
c.abort();
abortCount++;
}
});
if(abortCount>0) $.resumableObj.fire('fileProgress', $);
}
$.cancel = function(){
// Reset this file to be void
var _chunks = $.chunks;
$.chunks = [];
// Stop current uploads
$h.each(_chunks, function(c){
if(c.status()=='uploading') {
c.abort();
$.resumableObj.uploadNextChunk();
}
});
$.resumableObj.removeFile($);
$.resumableObj.fire('fileProgress', $);
};
$.retry = function(){
$.bootstrap();
$.resumableObj.upload();
};
$.bootstrap = function(){
$.abort();
_error = false;
// Rebuild stack of chunks from file
$.chunks = [];
$._prevProgress = 0;
var round = $.getOpt('forceChunkSize') ? Math.ceil : Math.floor;
for (var offset=0; offset<Math.max(round($.file.size/$.getOpt('chunkSize')),1); offset++) {
$.chunks.push(new ResumableChunk($.resumableObj, $, offset, chunkEvent));
}
};
$.progress = function(){
if(_error) return(1);
// Sum up progress across everything
var ret = 0;
var error = false;
$h.each($.chunks, function(c){
if(c.status()=='error') error = true;
ret += c.progress(true); // get chunk progress relative to entire file
});
ret = (error ? 1 : (ret>0.999 ? 1 : ret));
ret = Math.max($._prevProgress, ret); // We don't want to lose percentages when an upload is paused
$._prevProgress = ret;
return(ret);
};
$.isUploading = function(){
var uploading = false;
$h.each($.chunks, function(chunk){
if(chunk.status()=='uploading') {
uploading = true;
return(false);
}
});
return(uploading);
};
$.isComplete = function(){
var outstanding = false;
$h.each($.chunks, function(chunk){
var status = chunk.status();
if(status=='pending' || status=='uploading' || chunk.preprocessState === 1) {
outstanding = true;
return(false);
}
});
return(!outstanding);
};
$.pause = function(pause){
if(typeof(pause)==='undefined'){
$._pause = ($._pause ? false : true);
}else{
$._pause = pause;
}
};
$.isPaused = function() {
return $._pause;
};
// Bootstrap and return
$.bootstrap();
return(this);
}
function ResumableChunk(resumableObj, fileObj, offset, callback){
var $ = this;
$.opts = {};
$.getOpt = resumableObj.getOpt;
$.resumableObj = resumableObj;
$.fileObj = fileObj;
$.fileObjSize = fileObj.size;
$.fileObjType = fileObj.file.type;
$.offset = offset;
$.callback = callback;
$.lastProgressCallback = (new Date);
$.tested = false;
$.retries = 0;
$.pendingRetry = false;
$.preprocessState = 0; // 0 = unprocessed, 1 = processing, 2 = finished
// Computed properties
var chunkSize = $.getOpt('chunkSize');
$.loaded = 0;
$.startByte = $.offset*chunkSize;
$.endByte = Math.min($.fileObjSize, ($.offset+1)*chunkSize);
if ($.fileObjSize-$.endByte < chunkSize && !$.getOpt('forceChunkSize')) {
// The last chunk will be bigger than the chunk size, but less than 2*chunkSize
$.endByte = $.fileObjSize;
}
$.xhr = null;
// test() makes a GET request without any data to see if the chunk has already been uploaded in a previous session
$.test = function(){
// Set up request and listen for event
$.xhr = new XMLHttpRequest();
var testHandler = function(e){
$.tested = true;
var status = $.status();
if(status=='success') {
$.callback(status, $.message());
$.resumableObj.uploadNextChunk();
} else {
$.send();
}
};
$.xhr.addEventListener('load', testHandler, false);
$.xhr.addEventListener('error', testHandler, false);
// Add data from the query options
var params = [];
var customQuery = $.getOpt('query');
if(typeof customQuery == 'function') customQuery = customQuery($.fileObj, $);
$h.each(customQuery, function(k,v){
params.push([encodeURIComponent(k), encodeURIComponent(v)].join('='));
});
// Add extra data to identify chunk
params.push(['resumableChunkNumber', encodeURIComponent($.offset+1)].join('='));
params.push(['resumableChunkSize', encodeURIComponent($.getOpt('chunkSize'))].join('='));
params.push(['resumableCurrentChunkSize', encodeURIComponent($.endByte - $.startByte)].join('='));
params.push(['resumableTotalSize', encodeURIComponent($.fileObjSize)].join('='));
params.push(['resumableType', encodeURIComponent($.fileObjType)].join('='));
params.push(['resumableIdentifier', encodeURIComponent($.fileObj.uniqueIdentifier)].join('='));
params.push(['resumableFilename', encodeURIComponent($.fileObj.fileName)].join('='));
params.push(['resumableRelativePath', encodeURIComponent($.fileObj.relativePath)].join('='));
// Append the relevant chunk and send it
$.xhr.open('GET', $h.getTarget(params));
$.xhr.timeout = $.getOpt('xhrTimeout');
$.xhr.withCredentials = $.getOpt('withCredentials');
// Add data from header options
$h.each($.getOpt('headers'), function(k,v) {
$.xhr.setRequestHeader(k, v);
});
$.xhr.send(null);
};
$.preprocessFinished = function(){
$.preprocessState = 2;
$.send();
};
// send() uploads the actual data in a POST call
$.send = function(){
var preprocess = $.getOpt('preprocess');
if(typeof preprocess === 'function') {
switch($.preprocessState) {
case 0: preprocess($); $.preprocessState = 1; return;
case 1: return;
case 2: break;
}
}
if($.getOpt('testChunks') && !$.tested) {
$.test();
return;
}
// Set up request and listen for event
$.xhr = new XMLHttpRequest();
// Progress
$.xhr.upload.addEventListener('progress', function(e){
if( (new Date) - $.lastProgressCallback > $.getOpt('throttleProgressCallbacks') * 1000 ) {
$.callback('progress');
$.lastProgressCallback = (new Date);
}
$.loaded=e.loaded||0;
}, false);
$.loaded = 0;
$.pendingRetry = false;
$.callback('progress');
// Done (either done, failed or retry)
var doneHandler = function(e){
var status = $.status();
if(status=='success'||status=='error') {
$.callback(status, $.message());
$.resumableObj.uploadNextChunk();
} else {
$.callback('retry', $.message());
$.abort();
$.retries++;
var retryInterval = $.getOpt('chunkRetryInterval');
if(retryInterval !== undefined) {
$.pendingRetry = true;
setTimeout($.send, retryInterval);
} else {
$.send();
}
}
};
$.xhr.addEventListener('load', doneHandler, false);
$.xhr.addEventListener('error', doneHandler, false);
// Set up the basic query data from Resumable
var query = {
resumableChunkNumber: $.offset+1,
resumableChunkSize: $.getOpt('chunkSize'),
resumableCurrentChunkSize: $.endByte - $.startByte,
resumableTotalSize: $.fileObjSize,
resumableType: $.fileObjType,
resumableIdentifier: $.fileObj.uniqueIdentifier,
resumableFilename: $.fileObj.fileName,
resumableRelativePath: $.fileObj.relativePath,
resumableTotalChunks: $.fileObj.chunks.length
};
// Mix in custom data
var customQuery = $.getOpt('query');
if(typeof customQuery == 'function') customQuery = customQuery($.fileObj, $);
$h.each(customQuery, function(k,v){
query[k] = v;
});
var func = ($.fileObj.file.slice ? 'slice' : ($.fileObj.file.mozSlice ? 'mozSlice' : ($.fileObj.file.webkitSlice ? 'webkitSlice' : 'slice'))),
bytes = $.fileObj.file[func]($.startByte,$.endByte),
data = null,
target = $.getOpt('target');
if ($.getOpt('method') === 'octet') {
// Add data from the query options
data = bytes;
var params = [];
$h.each(query, function(k,v){
params.push([encodeURIComponent(k), encodeURIComponent(v)].join('='));
});
target = $h.getTarget(params);
} else {
// Add data from the query options
data = new FormData();
$h.each(query, function(k,v){
data.append(k,v);
});
data.append($.getOpt('fileParameterName'), bytes);
}
$.xhr.open('POST', target);
$.xhr.timeout = $.getOpt('xhrTimeout');
$.xhr.withCredentials = $.getOpt('withCredentials');
// Add data from header options
$h.each($.getOpt('headers'), function(k,v) {
$.xhr.setRequestHeader(k, v);
});
$.xhr.send(data);
};
$.abort = function(){
// Abort and reset
if($.xhr) $.xhr.abort();
$.xhr = null;
};
$.status = function(){
// Returns: 'pending', 'uploading', 'success', 'error'
if($.pendingRetry) {
// if pending retry then that's effectively the same as actively uploading,
// there might just be a slight delay before the retry starts
return('uploading')
} else if(!$.xhr) {
return('pending');
} else if($.xhr.readyState<4) {
// Status is really 'OPENED', 'HEADERS_RECEIVED' or 'LOADING' - meaning that stuff is happening
return('uploading');
} else {
if($.xhr.status==200) {
// HTTP 200, perfect
return('success');
} else if($h.contains($.getOpt('permanentErrors'), $.xhr.status) || $.retries >= $.getOpt('maxChunkRetries')) {
// HTTP 415/500/501, permanent error
return('error');
} else {
// this should never happen, but we'll reset and queue a retry
// a likely case for this would be 503 service unavailable
$.abort();
return('pending');
}
}
};
$.message = function(){
return($.xhr ? $.xhr.responseText : '');
};
$.progress = function(relative){
if(typeof(relative)==='undefined') relative = false;
var factor = (relative ? ($.endByte-$.startByte)/$.fileObjSize : 1);
if($.pendingRetry) return(0);
var s = $.status();
switch(s){
case 'success':
case 'error':
return(1*factor);
case 'pending':
return(0*factor);
default:
return($.loaded/($.endByte-$.startByte)*factor);
}
};
return(this);
}
// QUEUE
$.uploadNextChunk = function(){
var found = false;
// In some cases (such as videos) it's really handy to upload the first
// and last chunk of a file quickly; this let's the server check the file's
// metadata and determine if there's even a point in continuing.
if ($.getOpt('prioritizeFirstAndLastChunk')) {
$h.each($.files, function(file){
if(file.chunks.length && file.chunks[0].status()=='pending' && file.chunks[0].preprocessState === 0) {
file.chunks[0].send();
found = true;
return(false);
}
if(file.chunks.length>1 && file.chunks[file.chunks.length-1].status()=='pending' && file.chunks[0].preprocessState === 0) {
file.chunks[file.chunks.length-1].send();
found = true;
return(false);
}
});
if(found) return(true);
}
// Now, simply look for the next, best thing to upload
$h.each($.files, function(file){
if(file.isPaused()===false){
$h.each(file.chunks, function(chunk){
if(chunk.status()=='pending' && chunk.preprocessState === 0) {
chunk.send();
found = true;
return(false);
}
});
}
if(found) return(false);
});
if(found) return(true);
// The are no more outstanding chunks to upload, check is everything is done
var outstanding = false;
$h.each($.files, function(file){
if(!file.isComplete()) {
outstanding = true;
return(false);
}
});
if(!outstanding) {
// All chunks have been uploaded, complete
$.fire('complete');
}
return(false);
};
// PUBLIC METHODS FOR RESUMABLE.JS
$.assignBrowse = function(domNodes, isDirectory){
if(typeof(domNodes.length)=='undefined') domNodes = [domNodes];
// We will create an <input> and overlay it on the domNode
// (crappy, but since HTML5 doesn't have a cross-browser.browse() method we haven't a choice.
// FF4+ allows click() for this though: https://developer.mozilla.org/en/using_files_from_web_applications)
$h.each(domNodes, function(domNode) {
var input;
if(domNode.tagName==='INPUT' && domNode.type==='file'){
input = domNode;
} else {
input = document.createElement('input');
input.setAttribute('type', 'file');
// Place <input /> with the dom node an position the input to fill the entire space
domNode.style.display = 'inline-block';
domNode.style.position = 'relative';
input.style.position = 'absolute';
input.style.top = input.style.left = input.style.bottom = input.style.right = 0;
input.style.opacity = 0;
//IE10 file input buttons hover right.
//This makes the input field as wide as the assigned node for browseButton
input.style.width = domNode.clientWidth + 'px';
input.style.cursor = 'pointer';
domNode.appendChild(input);
}
var maxFiles = $.getOpt('maxFiles');
if (typeof(maxFiles)==='undefined'||maxFiles!=1){
input.setAttribute('multiple', 'multiple');
} else {
input.removeAttribute('multiple');
}
if(isDirectory){
input.setAttribute('webkitdirectory', 'webkitdirectory');
} else {
input.removeAttribute('webkitdirectory');
}
// When new files are added, simply append them to the overall list
input.addEventListener('change', function(e){
appendFilesFromFileList(e.target.files);
e.target.value = '';
}, false);
});
};
$.assignDrop = function(domNodes){
if(typeof(domNodes.length)=='undefined') domNodes = [domNodes];
$h.each(domNodes, function(domNode) {
domNode.addEventListener('dragover', onDragOver, false);
domNode.addEventListener('drop', onDrop, false);
});
};
$.unAssignDrop = function(domNodes) {
if (typeof(domNodes.length) == 'undefined') domNodes = [domNodes];
$h.each(domNodes, function(domNode) {
domNode.removeEventListener('dragover', onDragOver);
domNode.removeEventListener('drop', onDrop);
});
};
$.isUploading = function(){
var uploading = false;
$h.each($.files, function(file){
if (file.isUploading()) {
uploading = true;
return(false);
}
});
return(uploading);
};
$.upload = function(){
// Make sure we don't start too many uploads at once
if($.isUploading()) return;
// Kick off the queue
$.fire('uploadStart');
for (var num=1; num<=$.getOpt('simultaneousUploads'); num++) {
$.uploadNextChunk();
}
};
$.pause = function(){
// Resume all chunks currently being uploaded
$h.each($.files, function(file){
file.abort();
});
$.fire('pause');
};
$.cancel = function(){
for(var i = $.files.length - 1; i >= 0; i--) {
$.files[i].cancel();
}
$.fire('cancel');
};
$.progress = function(){
var totalDone = 0;
var totalSize = 0;
// Resume all chunks currently being uploaded
$h.each($.files, function(file){
totalDone += file.progress()*file.size;
totalSize += file.size;
});
return(totalSize>0 ? totalDone/totalSize : 0);
};
$.addFile = function(file){
appendFilesFromFileList([file]);
};
$.removeFile = function(file){
for(var i = $.files.length - 1; i >= 0; i--) {
if($.files[i] === file) {
$.files.splice(i, 1);
}
}
};
$.getFromUniqueIdentifier = function(uniqueIdentifier){
var ret = false;
$h.each($.files, function(f){
if(f.uniqueIdentifier==uniqueIdentifier) ret = f;
});
return(ret);
};
$.getSize = function(){
var totalSize = 0;
$h.each($.files, function(file){
totalSize += file.size;
});
return(totalSize);
};
return(this);
};
// Node.js-style export for Node and Component
if (typeof module != 'undefined') {
module.exports = Resumable;
} else if (typeof define === "function" && define.amd) {
// AMD/requirejs: Define the module
define(function(){
return Resumable;
});
} else {
// Browser: Expose to window
window.Resumable = Resumable;
}
})();
|
Make the assignBrowse implementation cleaner.
|
resumable.js
|
Make the assignBrowse implementation cleaner.
|
<ide><path>esumable.js
<ide> $.assignBrowse = function(domNodes, isDirectory){
<ide> if(typeof(domNodes.length)=='undefined') domNodes = [domNodes];
<ide>
<del> // We will create an <input> and overlay it on the domNode
<del> // (crappy, but since HTML5 doesn't have a cross-browser.browse() method we haven't a choice.
<del> // FF4+ allows click() for this though: https://developer.mozilla.org/en/using_files_from_web_applications)
<ide> $h.each(domNodes, function(domNode) {
<ide> var input;
<ide> if(domNode.tagName==='INPUT' && domNode.type==='file'){
<ide> } else {
<ide> input = document.createElement('input');
<ide> input.setAttribute('type', 'file');
<del> // Place <input /> with the dom node an position the input to fill the entire space
<del> domNode.style.display = 'inline-block';
<del> domNode.style.position = 'relative';
<del> input.style.position = 'absolute';
<del> input.style.top = input.style.left = input.style.bottom = input.style.right = 0;
<del> input.style.opacity = 0;
<del> //IE10 file input buttons hover right.
<del> //This makes the input field as wide as the assigned node for browseButton
<del> input.style.width = domNode.clientWidth + 'px';
<del> input.style.cursor = 'pointer';
<add> input.style.display = 'none';
<add> domNode.addEventListener('click', function(){
<add> input.click();
<add> }, false);
<ide> domNode.appendChild(input);
<ide> }
<ide> var maxFiles = $.getOpt('maxFiles');
|
|
Java
|
apache-2.0
|
1dd88f75b28c8e54cd31d5fe7f6b19a06727e4aa
| 0 |
Nickname0806/Test_Q4,apache/tomcat,apache/tomcat,apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4,apache/tomcat
|
/*
* 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.catalina.connector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import junit.framework.TestCase;
/**
* Test case for {@link Request}.
*/
public class TestRequest extends TestCase {
/**
* Test case for https://issues.apache.org/bugzilla/show_bug.cgi?id=37794
* POST parameters are not returned from a call to
* any of the {@link HttpServletRequest} getParameterXXX() methods if the
* request is chunked.
*/
public void testBug37794() throws Exception {
Bug37794Client client = new Bug37794Client();
// Edge cases around zero
client.doRequest(-1, false); // Unlimited
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
client.reset();
client.doRequest(0, false); // Unlimited
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
client.reset();
client.doRequest(1, false); // 1 byte - too small should fail
assertTrue(client.isResponse500());
client.reset();
// Edge cases around actual content length
client.reset();
client.doRequest(6, false); // Too small should fail
assertTrue(client.isResponse500());
client.reset();
client.doRequest(7, false); // Just enough should pass
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
client.reset();
client.doRequest(8, false); // 1 extra - should pass
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
// Much larger
client.reset();
client.doRequest(8096, false); // Plenty of space - should pass
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
// Check for case insensitivity
client.reset();
client.doRequest(8096, true); // Plenty of space - should pass
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
}
private static class Bug37794Servlet extends HttpServlet {
/**
* Only interested in the parameters and values for POST requests.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Just echo the parameters and values back as plain text
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
// Assume one value per attribute
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
out.println(name + "=" + req.getParameter(name));
}
}
}
/**
* Bug 37794 test client.
*/
private static class Bug37794Client extends SimpleHttpClient {
private Exception doRequest(int postLimit, boolean ucChunkedHead) {
Tomcat tomcat = new Tomcat();
try {
StandardContext root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet());
root.addServletMapping("/test", "Bug37794");
tomcat.getConnector().setMaxPostSize(postLimit);
tomcat.start();
// Open connection
connect();
// Send request in two parts
String[] request = new String[2];
if (ucChunkedHead) {
request[0] =
"POST http://localhost:8080/test HTTP/1.1" + CRLF +
"content-type: application/x-www-form-urlencoded" + CRLF +
"Transfer-Encoding: CHUNKED" + CRLF +
"Connection: close" + CRLF +
CRLF +
"3" + CRLF +
"a=1" + CRLF;
} else {
request[0] =
"POST http://localhost:8080/test HTTP/1.1" + CRLF +
"content-type: application/x-www-form-urlencoded" + CRLF +
"Transfer-Encoding: chunked" + CRLF +
"Connection: close" + CRLF +
CRLF +
"3" + CRLF +
"a=1" + CRLF;
}
request[1] =
"4" + CRLF +
"&b=2" + CRLF +
"0" + CRLF +
CRLF;
setRequest(request);
processRequest(); // blocks until response has been read
// Close the connection
disconnect();
} catch (Exception e) {
return e;
} finally {
try {
tomcat.stop();
} catch (Exception e) {
// Ignore
}
}
return null;
}
public boolean isResponseBodyOK() {
if (getResponseBody() == null) {
return false;
}
if (!getResponseBody().contains("a=1")) {
return false;
}
if (!getResponseBody().contains("b=2")) {
return false;
}
return true;
}
}
/**
* Simple client for unit testing. It isn't robust, it isn't secure and
* should not be used as the basis for production code. Its only purpose
* is to do the bare minimum for the unit tests.
*/
private abstract static class SimpleHttpClient {
public static final String TEMP_DIR =
System.getProperty("java.io.tmpdir");
public static final String CRLF = "\r\n";
public static final String OK_200 = "HTTP/1.1 200";
public static final String FAIL_500 = "HTTP/1.1 500";
private Socket socket;
private Writer writer;
private BufferedReader reader;
private String[] request;
private int requestPause = 1000;
private String responseLine;
private List<String> responseHeaders = new ArrayList<String>();
private String responseBody;
public void setRequest(String[] theRequest) {
request = theRequest;
}
public void setRequestPause(int theRequestPause) {
requestPause = theRequestPause;
}
public String getResponseLine() {
return responseLine;
}
public List<String> getResponseHeaders() {
return responseHeaders;
}
public String getResponseBody() {
return responseBody;
}
public void connect() throws UnknownHostException, IOException {
socket = new Socket("localhost", 8080);
OutputStream os = socket.getOutputStream();
writer = new OutputStreamWriter(os);
InputStream is = socket.getInputStream();
Reader r = new InputStreamReader(is);
reader = new BufferedReader(r);
}
public void processRequest() throws IOException, InterruptedException {
// Send the request
boolean first = true;
for (String requestPart : request) {
if (first) {
first = false;
} else {
Thread.sleep(requestPause);
}
writer.write(requestPart);
writer.flush();
}
// Read the response
responseLine = readLine();
// Put the headers into the map
String line = readLine();
while (line.length() > 0) {
responseHeaders.add(line);
line = readLine();
}
// Read the body, if any
StringBuilder builder = new StringBuilder();
line = readLine();
while (line != null && line.length() > 0) {
builder.append(line);
line = readLine();
}
responseBody = builder.toString();
}
public String readLine() throws IOException {
return reader.readLine();
}
public void disconnect() throws IOException {
writer.close();
reader.close();
socket.close();
}
public void reset() {
socket = null;
writer = null;
reader = null;
request = null;
requestPause = 1000;
responseLine = null;
responseHeaders = new ArrayList<String>();
responseBody = null;
}
public boolean isResponse200() {
return getResponseLine().startsWith(OK_200);
}
public boolean isResponse500() {
return getResponseLine().startsWith(FAIL_500);
}
public abstract boolean isResponseBodyOK();
}
}
|
test/org/apache/catalina/connector/TestRequest.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.catalina.connector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import junit.framework.TestCase;
/**
* Test case for {@link Request}.
*/
public class TestRequest extends TestCase {
/**
* Test case for https://issues.apache.org/bugzilla/show_bug.cgi?id=37794
* POST parameters are not returned from a call to
* any of the {@link HttpServletRequest} getParameterXXX() methods if the
* request is chunked.
*/
public void testBug37794() throws Exception {
Bug37794Client client = new Bug37794Client();
// Edge cases around zero
client.doRequest(-1); // Unlimited
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
client.reset();
client.doRequest(0); // Unlimited
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
client.reset();
client.doRequest(1); // 1 byte - too small should fail
assertTrue(client.isResponse500());
client.reset();
// Edge cases around actual content length
client.reset();
client.doRequest(6); // Too small should fail
assertTrue(client.isResponse500());
client.reset();
client.doRequest(7); // Just enough should pass
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
client.reset();
client.doRequest(8); // 1 extra - should pass
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
// Much larger
client.reset();
client.doRequest(8096); // Plenty of space - should pass
assertTrue(client.isResponse200());
assertTrue(client.isResponseBodyOK());
}
private static class Bug37794Servlet extends HttpServlet {
/**
* Only interested in the parameters and values for POST requests.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Just echo the parameters and values back as plain text
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
// Assume one value per attribute
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
out.println(name + "=" + req.getParameter(name));
}
}
}
/**
* Bug 37794 test client.
*/
private static class Bug37794Client extends SimpleHttpClient {
private Exception doRequest(int postLimit) {
Tomcat tomcat = new Tomcat();
try {
StandardContext root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet());
root.addServletMapping("/test", "Bug37794");
tomcat.getConnector().setMaxPostSize(postLimit);
tomcat.start();
// Open connection
connect();
// Send request in two parts
String[] request = new String[2];
request[0] =
"POST http://localhost:8080/test HTTP/1.1" + CRLF +
"content-type: application/x-www-form-urlencoded" + CRLF +
"Transfer-Encoding: chunked" + CRLF +
"Connection: close" + CRLF +
CRLF +
"3" + CRLF +
"a=1" + CRLF;
request[1] =
"4" + CRLF +
"&b=2" + CRLF +
"0" + CRLF +
CRLF;
setRequest(request);
processRequest(); // blocks until response has been read
// Close the connection
disconnect();
} catch (Exception e) {
return e;
} finally {
try {
tomcat.stop();
} catch (Exception e) {
// Ignore
}
}
return null;
}
public boolean isResponseBodyOK() {
if (getResponseBody() == null) {
return false;
}
if (!getResponseBody().contains("a=1")) {
return false;
}
if (!getResponseBody().contains("b=2")) {
return false;
}
return true;
}
}
/**
* Simple client for unit testing. It isn't robust, it isn't secure and
* should not be used as the basis for production code. Its only purpose
* is to do the bare minimum for the unit tests.
*/
private abstract static class SimpleHttpClient {
public static final String TEMP_DIR =
System.getProperty("java.io.tmpdir");
public static final String CRLF = "\r\n";
public static final String OK_200 = "HTTP/1.1 200";
public static final String FAIL_500 = "HTTP/1.1 500";
private Socket socket;
private Writer writer;
private BufferedReader reader;
private String[] request;
private int requestPause = 1000;
private String responseLine;
private List<String> responseHeaders = new ArrayList<String>();
private String responseBody;
public void setRequest(String[] theRequest) {
request = theRequest;
}
public void setRequestPause(int theRequestPause) {
requestPause = theRequestPause;
}
public String getResponseLine() {
return responseLine;
}
public List<String> getResponseHeaders() {
return responseHeaders;
}
public String getResponseBody() {
return responseBody;
}
public void connect() throws UnknownHostException, IOException {
socket = new Socket("localhost", 8080);
OutputStream os = socket.getOutputStream();
writer = new OutputStreamWriter(os);
InputStream is = socket.getInputStream();
Reader r = new InputStreamReader(is);
reader = new BufferedReader(r);
}
public void processRequest() throws IOException, InterruptedException {
// Send the request
boolean first = true;
for (String requestPart : request) {
if (first) {
first = false;
} else {
Thread.sleep(requestPause);
}
writer.write(requestPart);
writer.flush();
}
// Read the response
responseLine = readLine();
// Put the headers into the map
String line = readLine();
while (line.length() > 0) {
responseHeaders.add(line);
line = readLine();
}
// Read the body, if any
StringBuilder builder = new StringBuilder();
line = readLine();
while (line != null && line.length() > 0) {
builder.append(line);
line = readLine();
}
responseBody = builder.toString();
}
public String readLine() throws IOException {
return reader.readLine();
}
public void disconnect() throws IOException {
writer.close();
reader.close();
socket.close();
}
public void reset() {
socket = null;
writer = null;
reader = null;
request = null;
requestPause = 1000;
responseLine = null;
responseHeaders = new ArrayList<String>();
responseBody = null;
}
public boolean isResponse200() {
return getResponseLine().startsWith(OK_200);
}
public boolean isResponse500() {
return getResponseLine().startsWith(FAIL_500);
}
public abstract boolean isResponseBodyOK();
}
}
|
Add a header case-sensitivity test for 37794 test case (as reported by Tim)
git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@786486 13f79535-47bb-0310-9956-ffa450edef68
|
test/org/apache/catalina/connector/TestRequest.java
|
Add a header case-sensitivity test for 37794 test case (as reported by Tim)
|
<ide><path>est/org/apache/catalina/connector/TestRequest.java
<ide> Bug37794Client client = new Bug37794Client();
<ide>
<ide> // Edge cases around zero
<del> client.doRequest(-1); // Unlimited
<del> assertTrue(client.isResponse200());
<del> assertTrue(client.isResponseBodyOK());
<del> client.reset();
<del> client.doRequest(0); // Unlimited
<del> assertTrue(client.isResponse200());
<del> assertTrue(client.isResponseBodyOK());
<del> client.reset();
<del> client.doRequest(1); // 1 byte - too small should fail
<add> client.doRequest(-1, false); // Unlimited
<add> assertTrue(client.isResponse200());
<add> assertTrue(client.isResponseBodyOK());
<add> client.reset();
<add> client.doRequest(0, false); // Unlimited
<add> assertTrue(client.isResponse200());
<add> assertTrue(client.isResponseBodyOK());
<add> client.reset();
<add> client.doRequest(1, false); // 1 byte - too small should fail
<ide> assertTrue(client.isResponse500());
<ide>
<ide> client.reset();
<ide>
<ide> // Edge cases around actual content length
<ide> client.reset();
<del> client.doRequest(6); // Too small should fail
<add> client.doRequest(6, false); // Too small should fail
<ide> assertTrue(client.isResponse500());
<ide> client.reset();
<del> client.doRequest(7); // Just enough should pass
<del> assertTrue(client.isResponse200());
<del> assertTrue(client.isResponseBodyOK());
<del> client.reset();
<del> client.doRequest(8); // 1 extra - should pass
<add> client.doRequest(7, false); // Just enough should pass
<add> assertTrue(client.isResponse200());
<add> assertTrue(client.isResponseBodyOK());
<add> client.reset();
<add> client.doRequest(8, false); // 1 extra - should pass
<ide> assertTrue(client.isResponse200());
<ide> assertTrue(client.isResponseBodyOK());
<ide>
<ide> // Much larger
<ide> client.reset();
<del> client.doRequest(8096); // Plenty of space - should pass
<add> client.doRequest(8096, false); // Plenty of space - should pass
<add> assertTrue(client.isResponse200());
<add> assertTrue(client.isResponseBodyOK());
<add>
<add> // Check for case insensitivity
<add> client.reset();
<add> client.doRequest(8096, true); // Plenty of space - should pass
<ide> assertTrue(client.isResponse200());
<ide> assertTrue(client.isResponseBodyOK());
<ide> }
<ide> * Bug 37794 test client.
<ide> */
<ide> private static class Bug37794Client extends SimpleHttpClient {
<del> private Exception doRequest(int postLimit) {
<add> private Exception doRequest(int postLimit, boolean ucChunkedHead) {
<ide> Tomcat tomcat = new Tomcat();
<ide> try {
<ide> StandardContext root = tomcat.addContext("", TEMP_DIR);
<ide>
<ide> // Send request in two parts
<ide> String[] request = new String[2];
<del> request[0] =
<del> "POST http://localhost:8080/test HTTP/1.1" + CRLF +
<del> "content-type: application/x-www-form-urlencoded" + CRLF +
<del> "Transfer-Encoding: chunked" + CRLF +
<del> "Connection: close" + CRLF +
<del> CRLF +
<del> "3" + CRLF +
<del> "a=1" + CRLF;
<add> if (ucChunkedHead) {
<add> request[0] =
<add> "POST http://localhost:8080/test HTTP/1.1" + CRLF +
<add> "content-type: application/x-www-form-urlencoded" + CRLF +
<add> "Transfer-Encoding: CHUNKED" + CRLF +
<add> "Connection: close" + CRLF +
<add> CRLF +
<add> "3" + CRLF +
<add> "a=1" + CRLF;
<add> } else {
<add> request[0] =
<add> "POST http://localhost:8080/test HTTP/1.1" + CRLF +
<add> "content-type: application/x-www-form-urlencoded" + CRLF +
<add> "Transfer-Encoding: chunked" + CRLF +
<add> "Connection: close" + CRLF +
<add> CRLF +
<add> "3" + CRLF +
<add> "a=1" + CRLF;
<add> }
<ide> request[1] =
<ide> "4" + CRLF +
<ide> "&b=2" + CRLF +
|
|
Java
|
mit
|
6a5821e3c90ae63cba508b42c7e7b71d641b2783
| 0 |
markenwerk/java-utils-json-handler-text
|
package net.markenwerk.utils.json.common.handler.text;
import org.junit.Assert;
import org.junit.Test;
import net.markenwerk.utils.json.common.InvalidJsonValueException;
import net.markenwerk.utils.json.handler.JsonHandler;
import net.markenwerk.utils.text.indentation.LineBreak;
import net.markenwerk.utils.text.indentation.Whitespace;
import net.markenwerk.utils.text.indentation.WhitespaceIndentation;
@SuppressWarnings("javadoc")
public class JsonTextJsonHandlerTests {
private static final WhitespaceIndentation INDENTATION = new WhitespaceIndentation(Whitespace.SPACE, 0,
LineBreak.UNIX);
@Test(expected = IllegalArgumentException.class)
public void create_nullIndentation() {
new JsonTextJsonHandler(null);
}
@Test
public void onNull() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onNull();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("null", result);
}
@Test
public void onBoolean_true() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onBoolean(true);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("true", result);
}
@Test
public void onBoolean_false() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onBoolean(false);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("false", result);
}
@Test
public void onLong_zero() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onLong(0);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Long.toString(0), result);
}
@Test
public void onLong_positive() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onLong(Long.MAX_VALUE);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Long.toString(Long.MAX_VALUE), result);
}
@Test
public void onLong_negative() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onLong(Long.MIN_VALUE);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Long.toString(Long.MIN_VALUE), result);
}
@Test(expected = InvalidJsonValueException.class)
public void onDouble_infinite() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(Double.POSITIVE_INFINITY);
handler.onDocumentEnd();
}
@Test(expected = InvalidJsonValueException.class)
public void onDouble_notANumber() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(Double.NaN);
handler.onDocumentEnd();
}
@Test
public void onDouble_zero() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(0);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Double.toString(0), result);
}
@Test
public void onDouble_positive() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(Double.MAX_VALUE);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Double.toString(Double.MAX_VALUE), result);
}
@Test
public void onDouble_negative() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(Double.MIN_VALUE);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Double.toString(Double.MIN_VALUE), result);
}
@Test(expected = InvalidJsonValueException.class)
public void onString_null() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString(null);
handler.onDocumentEnd();
}
@Test
public void onString_empty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString("");
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"\"", result);
}
@Test
public void onString_nonEmpty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString("foobar");
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"foobar\"", result);
}
@Test
public void onString_escapeSequances() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString("__\"_\\_/_\b_\f_\n_\r_\t__");
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"__\\\"_\\\\_\\/_\\b_\\f_\\n_\\r_\\t__\"", result);
}
@Test
public void onString_controllEscapeSequances() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString(Character.toString((char) 0));
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"\\u0000\"", result);
}
@Test
public void onString_unicodeEscapeSequances() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString("��");
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"\uD834\uDD1E\"", result);
}
@Test
public void onArray_empty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onArrayBegin();
handler.onArrayEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("[]", result);
}
@Test
public void onArray_nonEmpty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onArrayBegin();
handler.onNull();
handler.onArrayEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("[\nnull\n]", result);
}
@Test
public void onObject_empty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onObjectBegin();
handler.onObjectEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("{}", result);
}
@Test
public void onObject_nonEmpty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onObjectBegin();
handler.onName("n");
handler.onNull();
handler.onObjectEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("{\n\"n\": null\n}", result);
}
@Test
public void onDocument_complex() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onObjectBegin();
handler.onName("n");
handler.onNull();
handler.onNext();
handler.onName("b");
handler.onBoolean(true);
handler.onNext();
handler.onName("l");
handler.onLong(-42);
handler.onNext();
handler.onName("d");
handler.onDouble(-23.42);
handler.onNext();
handler.onName("a");
handler.onArrayBegin();
handler.onString("foo");
handler.onNext();
handler.onString("bar");
handler.onArrayEnd();
handler.onObjectEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(
"{\n\"n\": null,\n\"b\": true,\n\"l\": -42,\n\"d\": -23.42,\n\"a\": [\n\"foo\",\n\"bar\"\n]\n}", result);
}
@Test
public void onDocument_defaultIndentation() {
JsonHandler<String> handler = new JsonTextJsonHandler(new WhitespaceIndentation(Whitespace.TAB, 1,
LineBreak.SYSTEM));
handler.onDocumentBegin();
handler.onObjectBegin();
handler.onName("n");
handler.onNull();
handler.onNext();
handler.onName("b");
handler.onBoolean(true);
handler.onObjectEnd();
handler.onDocumentEnd();
String result = handler.getResult();
String lineBreak = System.getProperty("line.separator");
Assert.assertEquals("{" + lineBreak + "\t\"n\": null," + lineBreak + "\t\"b\": true" + lineBreak + "}", result);
}
}
|
src/test/java/net/markenwerk/utils/json/common/handler/text/JsonTextJsonHandlerTests.java
|
package net.markenwerk.utils.json.common.handler.text;
import org.junit.Assert;
import org.junit.Test;
import net.markenwerk.utils.json.common.InvalidJsonValueException;
import net.markenwerk.utils.json.handler.JsonHandler;
import net.markenwerk.utils.text.indentation.LineBreak;
import net.markenwerk.utils.text.indentation.Whitespace;
import net.markenwerk.utils.text.indentation.WhitespaceIndentation;
@SuppressWarnings("javadoc")
public class JsonTextJsonHandlerTests {
private static final WhitespaceIndentation INDENTATION = new WhitespaceIndentation(Whitespace.SPACE, 0,
LineBreak.UNIX);
@Test(expected = IllegalArgumentException.class)
public void create_nullIndentation() {
new JsonTextJsonHandler(null);
}
@Test
public void onNull() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onNull();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("null", result);
}
@Test
public void onBoolean_true() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onBoolean(true);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("true", result);
}
@Test
public void onBoolean_false() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onBoolean(false);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("false", result);
}
@Test
public void onLong_zero() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onLong(0);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Long.toString(0), result);
}
@Test
public void onLong_positive() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onLong(Long.MAX_VALUE);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Long.toString(Long.MAX_VALUE), result);
}
@Test
public void onLong_negative() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onLong(Long.MIN_VALUE);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Long.toString(Long.MIN_VALUE), result);
}
@Test(expected = InvalidJsonValueException.class)
public void onDouble_infinite() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(Double.POSITIVE_INFINITY);
handler.onDocumentEnd();
}
@Test(expected = InvalidJsonValueException.class)
public void onDouble_notANumber() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(Double.NaN);
handler.onDocumentEnd();
}
@Test
public void onDouble_zero() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(0);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Double.toString(0), result);
}
@Test
public void onDouble_positive() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(Double.MAX_VALUE);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Double.toString(Double.MAX_VALUE), result);
}
@Test
public void onDouble_negative() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onDouble(Double.MIN_VALUE);
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals(Double.toString(Double.MIN_VALUE), result);
}
@Test(expected = InvalidJsonValueException.class)
public void onString_null() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString(null);
handler.onDocumentEnd();
}
@Test
public void onString_empty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString("");
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"\"", result);
}
@Test
public void onString_nonEmpty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString("foobar");
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"foobar\"", result);
}
@Test
public void onString_escapeSequances() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString("__\"_\\_/_\b_\f_\n_\r_\t__");
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"__\\\"_\\\\_\\/_\\b_\\f_\\n_\\r_\\t__\"", result);
}
@Test
public void onString_controllEscapeSequances() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString(Character.toString((char) 0));
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"\\u0000\"", result);
}
@Test
public void onString_unicodeEscapeSequances() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onString("��");
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("\"\uD834\uDD1E\"", result);
}
@Test
public void onArray_empty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onArrayBegin();
handler.onArrayEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("[]", result);
}
@Test
public void onArray_nonEmpty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onArrayBegin();
handler.onNull();
handler.onArrayEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("[\nnull\n]", result);
}
@Test
public void onObject_empty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onObjectBegin();
handler.onObjectEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("{}", result);
}
@Test
public void onObject_nonEmpty() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onObjectBegin();
handler.onName("n");
handler.onNull();
handler.onObjectEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("{\n\"n\": null\n}", result);
}
@Test
public void onDocument_complex() {
JsonHandler<String> handler = new JsonTextJsonHandler(INDENTATION);
handler.onDocumentBegin();
handler.onObjectBegin();
handler.onName("n");
handler.onNull();
handler.onNext();
handler.onName("b");
handler.onBoolean(true);
handler.onNext();
handler.onName("l");
handler.onLong(-42);
handler.onNext();
handler.onName("d");
handler.onDouble(-23.42);
handler.onNext();
handler.onName("a");
handler.onArrayBegin();
handler.onString("foo");
handler.onNext();
handler.onString("bar");
handler.onArrayEnd();
handler.onObjectEnd();
handler.onDocumentEnd();
String result = handler.getResult();
Assert.assertEquals("{\n\"n\": null,\n\"b\": true,\n\"l\": -42,\n\"d\": -23.42,\n\"a\": [\n\"foo\",\n\"bar\"\n]\n}", result);
}
@Test
public void onDocument_defaultIndentation() {
JsonHandler<String> handler = new JsonTextJsonHandler();
handler.onDocumentBegin();
handler.onObjectBegin();
handler.onName("n");
handler.onNull();
handler.onNext();
handler.onName("b");
handler.onBoolean(true);
handler.onObjectEnd();
handler.onDocumentEnd();
String result = handler.getResult();
String lineBreak = System.getProperty("line.separator");
Assert.assertEquals("{" + lineBreak + "\t\"n\": null," + lineBreak + "\t\"b\": true" + lineBreak + "}", result);
}
}
|
fixed test cases
|
src/test/java/net/markenwerk/utils/json/common/handler/text/JsonTextJsonHandlerTests.java
|
fixed test cases
|
<ide><path>rc/test/java/net/markenwerk/utils/json/common/handler/text/JsonTextJsonHandlerTests.java
<ide>
<ide> String result = handler.getResult();
<ide>
<del> Assert.assertEquals("{\n\"n\": null,\n\"b\": true,\n\"l\": -42,\n\"d\": -23.42,\n\"a\": [\n\"foo\",\n\"bar\"\n]\n}", result);
<add> Assert.assertEquals(
<add> "{\n\"n\": null,\n\"b\": true,\n\"l\": -42,\n\"d\": -23.42,\n\"a\": [\n\"foo\",\n\"bar\"\n]\n}", result);
<ide>
<ide> }
<ide>
<ide> @Test
<ide> public void onDocument_defaultIndentation() {
<ide>
<del> JsonHandler<String> handler = new JsonTextJsonHandler();
<add> JsonHandler<String> handler = new JsonTextJsonHandler(new WhitespaceIndentation(Whitespace.TAB, 1,
<add> LineBreak.SYSTEM));
<ide>
<ide> handler.onDocumentBegin();
<ide> handler.onObjectBegin();
|
|
Java
|
agpl-3.0
|
709afca7fa006f6e217883a4ae9f3b711ae42300
| 0 |
pivotal-nathan-sentjens/tigase-xmpp-java,cgvarela/tigase-server,f24-ag/tigase,cgvarela/tigase-server,cgvarela/tigase-server,caiyingyuan/tigase71,wangningbo/tigase-server,nate-sentjens/tigase-xmpp-java,Smartupz/tigase-server,Smartupz/tigase-server,wangningbo/tigase-server,wangningbo/tigase-server,caiyingyuan/tigase71,pivotal-nathan-sentjens/tigase-xmpp-java,pivotal-nathan-sentjens/tigase-xmpp-java,fanout/tigase-server,Smartupz/tigase-server,sourcebits-praveenkh/Tagase,caiyingyuan/tigase71,wangningbo/tigase-server,wangningbo/tigase-server,amikey/tigase-server,nate-sentjens/tigase-xmpp-java,cgvarela/tigase-server,fanout/tigase-server,amikey/tigase-server,sourcebits-praveenkh/Tagase,sourcebits-praveenkh/Tagase,cgvarela/tigase-server,fanout/tigase-server,fanout/tigase-server,fanout/tigase-server,caiyingyuan/tigase71,nate-sentjens/tigase-xmpp-java,f24-ag/tigase,f24-ag/tigase,sourcebits-praveenkh/Tagase,cgvarela/tigase-server,Smartupz/tigase-server,amikey/tigase-server,f24-ag/tigase,caiyingyuan/tigase71,f24-ag/tigase,pivotal-nathan-sentjens/tigase-xmpp-java,nate-sentjens/tigase-xmpp-java,wangningbo/tigase-server,amikey/tigase-server,nate-sentjens/tigase-xmpp-java,sourcebits-praveenkh/Tagase,amikey/tigase-server,caiyingyuan/tigase71,pivotal-nathan-sentjens/tigase-xmpp-java,f24-ag/tigase,wangningbo/tigase-server,amikey/tigase-server,nate-sentjens/tigase-xmpp-java,sourcebits-praveenkh/Tagase,pivotal-nathan-sentjens/tigase-xmpp-java,Smartupz/tigase-server,fanout/tigase-server,Smartupz/tigase-server
|
/*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2007 "Artur Hefczyc" <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package tigase.cluster;
//~--- non-JDK imports --------------------------------------------------------
import tigase.annotations.TODO;
import tigase.net.ConnectionType;
//import tigase.net.IOService;
import tigase.net.SocketType;
import tigase.server.ConnectionManager;
import tigase.server.Packet;
import tigase.server.ServiceChecker;
import tigase.stats.StatisticsList;
import tigase.util.Algorithms;
import tigase.util.DNSResolver;
import tigase.util.TigaseStringprepException;
import tigase.util.TimeUtils;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.PacketErrorTypeException;
import tigase.xmpp.XMPPIOService;
//~--- JDK imports ------------------------------------------------------------
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Deflater;
import javax.script.Bindings;
//~--- classes ----------------------------------------------------------------
/**
* Class ClusterConnectionManager
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:[email protected]">Artur Hefczyc</a>
* @version $Rev$
*/
public class ClusterConnectionManager extends ConnectionManager<XMPPIOService<Object>>
implements ClusteredComponent {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger(ClusterConnectionManager.class.getName());
/** Field description */
public static final String SECRET_PROP_KEY = "secret";
/** Field description */
public static final String PORT_LOCAL_HOST_PROP_KEY = "local-host";
/** Field description */
public static final String PORT_ROUTING_TABLE_PROP_KEY = "routing-table";
/** Field description */
public static final String RETURN_SERVICE_DISCO_KEY = "service-disco";
/** Field description */
public static final boolean RETURN_SERVICE_DISCO_VAL = true;
/** Field description */
public static final String IDENTITY_TYPE_KEY = "identity-type";
/** Field description */
public static final String IDENTITY_TYPE_VAL = "generic";
/** Field description */
public static final String CONNECT_ALL_PAR = "--cluster-connect-all";
/** Field description */
public static final String CONNECT_ALL_PROP_KEY = "connect-all";
/** Field description */
public static final String CLUSTER_CONTR_ID_PROP_KEY = "cluster-controller-id";
/** Field description */
public static final boolean CONNECT_ALL_PROP_VAL = false;
/** Field description */
public static final String COMPRESS_STREAM_PROP_KEY = "compress-stream";
/** Field description */
public static final boolean COMPRESS_STREAM_PROP_VAL = false;
/** Field description */
public static final String XMLNS = "tigase:cluster";
private static final String SERVICE_CONNECTED_TIMER = "service-connected-timer";
//~--- fields ---------------------------------------------------------------
/** Field description */
public int[] PORTS = { 5277 };
/** Field description */
public String[] PORT_IFC_PROP_VAL = { "*" };
/** Field description */
public String SECRET_PROP_VAL = "someSecret";
private ClusterController clusterController = null;
// private boolean notify_admins = NOTIFY_ADMINS_PROP_VAL;
// private String[] admins = new String[] {};
private String cluster_controller_id = null;
private IOServiceStatisticsGetter ioStatsGetter = new IOServiceStatisticsGetter();
//private ServiceEntity serviceEntity = null;
// private boolean service_disco = RETURN_SERVICE_DISCO_VAL;
private String identity_type = IDENTITY_TYPE_VAL;
private boolean connect_all = CONNECT_ALL_PROP_VAL;
private boolean compress_stream = COMPRESS_STREAM_PROP_VAL;
private long[] lastDay = new long[24];
private int lastDayIdx = 0;
private long[] lastHour = new long[60];
private int lastHourIdx = 0;
//private LinkedHashMap<String, LinkedHashMap<Long, Packet>> waiting_packs =
// new LinkedHashMap<String, LinkedHashMap<Long, Packet>>();
//private LinkedHashMap<String, Long> sent_rids = new LinkedHashMap<String, Long>();
//private LinkedHashMap<String, Long> recieved_rids =
// new LinkedHashMap<String, Long>();
//private LinkedHashMap<String, Long> recieved_acks =
// new LinkedHashMap<String, Long>();
private int nodesNo = 0;
private long servConnectedTimeouts = 0;
private long totalNodeDisconnects = 0;
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @param params
*
* @return
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> props = super.getDefaults(params);
props.put(RETURN_SERVICE_DISCO_KEY, RETURN_SERVICE_DISCO_VAL);
props.put(IDENTITY_TYPE_KEY, IDENTITY_TYPE_VAL);
if ((params.get(CONNECT_ALL_PAR) == null)
||!((String) params.get(CONNECT_ALL_PAR)).equals("true")) {
props.put(CONNECT_ALL_PROP_KEY, false);
} else {
props.put(CONNECT_ALL_PROP_KEY, true);
}
if (params.get(CLUSTER_NODES) != null) {
String[] cl_nodes = ((String) params.get(CLUSTER_NODES)).split(",");
for (int i = 0; i < cl_nodes.length; i++) {
cl_nodes[i] = BareJID.parseJID(cl_nodes[i])[1];
}
nodesNo = cl_nodes.length;
props.put(CLUSTER_NODES_PROP_KEY, cl_nodes);
} else {
props.put(CLUSTER_NODES_PROP_KEY, new String[] { getDefHostName().getDomain() });
}
props.put(CLUSTER_CONTR_ID_PROP_KEY, DEF_CLUST_CONTR_NAME + "@" + getDefHostName());
props.put(COMPRESS_STREAM_PROP_KEY, COMPRESS_STREAM_PROP_VAL);
// props.put(NOTIFY_ADMINS_PROP_KEY, NOTIFY_ADMINS_PROP_VAL);
// if (params.get(GEN_ADMINS) != null) {
// admins = ((String)params.get(GEN_ADMINS)).split(",");
// } else {
// admins = new String[] { "admin@localhost" };
// }
// props.put(ADMINS_PROP_KEY, admins);
return props;
}
/**
* Method description
*
*
* @return
*/
@Override
public String getDiscoCategoryType() {
return identity_type;
}
//private void updateServiceDiscovery(String jid, String name) {
// ServiceEntity item = new ServiceEntity(jid, null, name);
// //item.addIdentities(new ServiceIdentity("component", identity_type, name));
// log.info("Modifing service-discovery info: " + item.toString());
// serviceEntity.addItems(item);
//}
//
//@Override
//public Element getDiscoInfo(String node, String jid) {
// if (jid != null && getName().equals(JIDUtils.getNodeNick(jid))) {
// return serviceEntity.getDiscoInfo(node);
// }
// return null;
//}
//
//@Override
//public List<Element> getDiscoFeatures() { return null; }
//
//@Override
//public List<Element> getDiscoItems(String node, String jid) {
// if (getName().equals(JIDUtils.getNodeNick(jid))) {
// return serviceEntity.getDiscoItems(node, null);
// } else {
// return Arrays.asList(serviceEntity.getDiscoItem(null,
// JIDUtils.getNodeID(getName(), jid)));
// }
//}
//
/**
* Method description
*
*
* @return
*/
@Override
public String getDiscoDescription() {
return XMLNS + " " + getName();
}
/**
* Method description
*
*
* @param list
*/
@Override
public void getStatistics(StatisticsList list) {
super.getStatistics(list);
list.add(getName(), "Total disconnects", totalNodeDisconnects, Level.FINE);
list.add(getName(), "Service connected time-outs", servConnectedTimeouts, Level.FINE);
list.add(getName(), "Last day disconnects", Arrays.toString(lastDay), Level.FINE);
list.add(getName(), "Last hour disconnects", Arrays.toString(lastHour), Level.FINE);
ioStatsGetter.reset();
doForAllServices(ioStatsGetter);
list.add(getName(), "Average compression ratio", ioStatsGetter.getAverageCompressionRatio(),
Level.FINE);
list.add(getName(), "Average decompression ratio",
ioStatsGetter.getAverageDecompressionRatio(), Level.FINE);
list.add(getName(), "Waiting to send", ioStatsGetter.getWaitingToSend(), Level.FINE);
}
//~--- methods --------------------------------------------------------------
/**
* This method can be overwritten in extending classes to get a different
* packets distribution to different threads. For PubSub, probably better
* packets distribution to different threads would be based on the
* sender address rather then destination address.
* @param packet
* @return
*/
@Override
public int hashCodeForPacket(Packet packet) {
// If this is a cluster packet let's try to do a bit more smart hashing
// based on the stanza from/to addresses
if (packet.getElemName() == ClusterElement.CLUSTER_EL_NAME) {
List<Element> children = packet.getElemChildren(ClusterElement.CLUSTER_DATA_PATH);
if ((children != null) && (children.size() > 0)) {
String stanzaAdd = children.get(0).getAttribute("to");
if (stanzaAdd != null) {
return stanzaAdd.hashCode();
} else {
// This might be user's initial presence. In such a case we take stanzaFrom instead
stanzaAdd = children.get(0).getAttribute("from");
if (stanzaAdd != null) {
return stanzaAdd.hashCode();
} else {
log.log(Level.WARNING, "No stanzaTo or from for cluster packet: {0}", packet);
}
}
}
}
// There is a separate connection to each cluster node, ideally we want to
// process packets in a separate thread for each connection, so let's try
// to get the hash code by the destination node address
if (packet.getStanzaTo() != null) {
return packet.getStanzaTo().hashCode();
}
return packet.getTo().hashCode();
}
/**
* Method description
*
*
* @param binds
*/
@Override
public void initBindings(Bindings binds) {
super.initBindings(binds);
binds.put("clusterCM", this);
}
/**
* Method description
*
*
* @param node
*/
@Override
public void nodeConnected(String node) {}
/**
* Method description
*
*
* @param node
*/
@Override
public void nodeDisconnected(String node) {}
/**
* Method description
*
*
* @param packet
*/
@Override
public void processPacket(Packet packet) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing packet: {0}", packet);
}
if ((packet.getStanzaTo() != null) && packet.getStanzaTo().equals(getComponentId())) {
try {
addOutPacket(Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet,
"Not implemented", true));
} catch (PacketErrorTypeException e) {
log.log(Level.WARNING, "Packet processing exception: {0}", e);
}
return;
}
writePacketToSocket(packet.packRouted());
// if (packet.getElemName() == ClusterElement.CLUSTER_EL_NAME) {
// writePacketToSocket(packet);
// } else {
// writePacketToSocket(packet.packRouted());
// }
}
/**
* Method description
*
*
* @param serv
*
* @return
*/
@Override
public Queue<Packet> processSocketData(XMPPIOService<Object> serv) {
Packet p = null;
while ((p = serv.getReceivedPackets().poll()) != null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing socket data: {0}", p);
}
if (p.getElemName().equals("handshake")) {
processHandshake(p, serv);
} else {
Packet result = p;
if (p.isRouted()) {
// processReceivedRid(p, serv);
// processReceivedAck(p, serv);
try {
result = p.unpackRouted();
} catch (TigaseStringprepException ex) {
log.log(Level.WARNING, "Packet stringprep addressing problem, dropping packet: {0}", p);
return null;
}
} // end of if (p.isRouted())
addOutPacket(result);
}
} // end of while ()
return null;
}
/**
*
* @return
*/
@Override
@TODO(note = "The number of threads should be equal or greater to number of cluster nodes.")
public int processingThreads() {
// This should work well as far as nodesNo is initialized before this
// method is called which is true only during program startup time.
// In case of reconfiguration or new node joining this might not be
// the case. Low priority issue though.
return Math.max(Runtime.getRuntime().availableProcessors(), nodesNo) * 4;
}
/**
* Method description
*
*
* @param port_props
*/
@Override
public void reconnectionFailed(Map<String, Object> port_props) {
// TODO: handle this somehow
}
/**
* Method description
*
*
* @param serv
*/
@Override
public void serviceStarted(XMPPIOService<Object> serv) {
ServiceConnectedTimer task = new ServiceConnectedTimer(serv);
serv.getSessionData().put(SERVICE_CONNECTED_TIMER, task);
addTimerTask(task, 10, TimeUnit.SECONDS);
super.serviceStarted(serv);
log.log(Level.INFO, "cluster connection opened: {0}, type: {1}, id={2}",
new Object[] { serv.getRemoteAddress(),
serv.connectionType().toString(), serv.getUniqueId() });
if (compress_stream) {
log.log(Level.INFO, "Starting stream compression for: {0}", serv.getUniqueId());
serv.startZLib(Deflater.BEST_COMPRESSION);
}
// String addr =
// (String)service.getSessionData().get(PORT_REMOTE_HOST_PROP_KEY);
// addRouting(addr);
// addRouting(serv.getRemoteHost());
switch (serv.connectionType()) {
case connect :
// Send init xmpp stream here
// XMPPIOService serv = (XMPPIOService)service;
String remote_host = (String) serv.getSessionData().get(PORT_REMOTE_HOST_PROP_KEY);
serv.getSessionData().put(XMPPIOService.HOSTNAME_KEY, remote_host);
serv.getSessionData().put(PORT_ROUTING_TABLE_PROP_KEY, new String[] { remote_host,
".*@" + remote_host, ".*\\." + remote_host });
String data = "<stream:stream" + " xmlns='" + XMLNS + "'"
+ " xmlns:stream='http://etherx.jabber.org/streams'" + " from='" + getDefHostName() + "'"
+ " to='" + remote_host + "'" + ">";
log.log(Level.INFO, "cid: {0}, sending: {1}",
new Object[] { (String) serv.getSessionData().get("cid"),
data });
serv.xmppStreamOpen(data);
break;
default :
// Do nothing, more data should come soon...
break;
} // end of switch (service.connectionType())
}
/**
* Method description
*
*
* @param service
*
* @return
*/
@Override
public boolean serviceStopped(XMPPIOService<Object> service) {
boolean result = super.serviceStopped(service);
// Make sure it runs just once for each disconnect
if (result) {
Map<String, Object> sessionData = service.getSessionData();
String[] routings = (String[]) sessionData.get(PORT_ROUTING_TABLE_PROP_KEY);
if (routings != null) {
updateRoutings(routings, false);
}
ConnectionType type = service.connectionType();
if (type == ConnectionType.connect) {
addWaitingTask(sessionData);
// reconnectService(sessionData, connectionDelay);
} // end of if (type == ConnectionType.connect)
// removeRouting(serv.getRemoteHost());
String addr = (String) sessionData.get(PORT_REMOTE_HOST_PROP_KEY);
log.log(Level.INFO, "Disonnected from: {0}", addr);
updateServiceDiscoveryItem(addr, addr, XMLNS + " disconnected", true);
clusterController.nodeDisconnected(addr);
// Map<String, String> method_params = new LinkedHashMap<String, String>();
// method_params.put("disconnected", addr);
// addOutPacket(new Packet(ClusterElement.createClusterMethodCall(
// getComponentId(), cluster_controller_id,
// StanzaType.set, ClusterMethods.UPDATE_NODES.toString(),
// method_params).getClusterElement()));
++totalNodeDisconnects;
int hour = TimeUtils.getHourNow();
if (lastDayIdx != hour) {
lastDayIdx = hour;
lastDay[hour] = 0;
Arrays.fill(lastHour, 0);
}
++lastDay[hour];
int minute = TimeUtils.getMinuteNow();
// if (lastHourIdx != minute) {
// lastHourIdx = minute;
// lastHour[minute] = 0;
// }
++lastHour[minute];
}
return result;
}
//~--- set methods ----------------------------------------------------------
/**
* Method description
*
*
* @param cl_controller
*/
@Override
public void setClusterController(ClusterController cl_controller) {
this.clusterController = cl_controller;
}
/**
* Method description
*
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
super.setProperties(props);
// service_disco = (Boolean)props.get(RETURN_SERVICE_DISCO_KEY);
identity_type = (String) props.get(IDENTITY_TYPE_KEY);
compress_stream = (Boolean) props.get(COMPRESS_STREAM_PROP_KEY);
// serviceEntity = new ServiceEntity(getName(), "external", "XEP-0114");
// serviceEntity = new ServiceEntity(XMLNS + " " + getName(), null, XMLNS);
// serviceEntity.addIdentities(
// new ServiceIdentity("component", identity_type, XMLNS + " " + getName()));
connect_all = (Boolean) props.get(CONNECT_ALL_PROP_KEY);
cluster_controller_id = (String) props.get(CLUSTER_CONTR_ID_PROP_KEY);
// notify_admins = (Boolean)props.get(NOTIFY_ADMINS_PROP_KEY);
// admins = (String[])props.get(ADMINS_PROP_KEY);
connectionDelay = 5 * SECOND;
String[] cl_nodes = (String[]) props.get(CLUSTER_NODES_PROP_KEY);
int[] ports = (int[]) props.get(PORTS_PROP_KEY);
if (ports != null) {
PORTS = ports;
}
if (cl_nodes != null) {
nodesNo = cl_nodes.length;
for (String node : cl_nodes) {
String host = BareJID.parseJID(node)[1];
log.log(Level.CONFIG, "Found cluster node host: {0}", host);
if ( !host.equals(getDefHostName().getDomain())
&& ((host.hashCode() > getDefHostName().hashCode()) || connect_all)) {
log.log(Level.CONFIG, "Trying to connect to cluster node: {0}", host);
Map<String, Object> port_props = new LinkedHashMap<String, Object>(12);
port_props.put(SECRET_PROP_KEY, SECRET_PROP_VAL);
port_props.put(PORT_LOCAL_HOST_PROP_KEY, getDefHostName());
port_props.put(PORT_TYPE_PROP_KEY, ConnectionType.connect);
port_props.put(PORT_SOCKET_PROP_KEY, SocketType.plain);
port_props.put(PORT_REMOTE_HOST_PROP_KEY, host);
port_props.put(PORT_IFC_PROP_KEY, new String[] { host });
port_props.put(MAX_RECONNECTS_PROP_KEY, 99999999);
port_props.put(PORT_KEY, PORTS[0]);
addWaitingTask(port_props);
// reconnectService(port_props, connectionDelay);
}
}
}
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param service
*/
@Override
public void tlsHandshakeCompleted(XMPPIOService<Object> service) {}
/**
* Method description
*
*
* @param serv
*/
@Override
public void xmppStreamClosed(XMPPIOService<Object> serv) {
log.info("Stream closed.");
}
/**
* Method description
*
*
* @param service
* @param attribs
*
* @return
*/
@Override
public String xmppStreamOpened(XMPPIOService<Object> service, Map<String, String> attribs) {
log.log(Level.INFO, "Stream opened: {0}", attribs);
switch (service.connectionType()) {
case connect : {
String id = attribs.get("id");
service.getSessionData().put(XMPPIOService.SESSION_ID_KEY, id);
String secret = (String) service.getSessionData().get(SECRET_PROP_KEY);
try {
String digest = Algorithms.hexDigest(id, secret, "SHA");
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Calculating digest: id={0}, secret={1}, digest={2}",
new Object[] { id,
secret, digest });
}
return "<handshake>" + digest + "</handshake>";
} catch (NoSuchAlgorithmException e) {
log.log(Level.SEVERE, "Can not generate digest for pass phrase.", e);
return null;
}
}
case accept : {
String remote_host = attribs.get("from");
service.getSessionData().put(XMPPIOService.HOSTNAME_KEY, remote_host);
service.getSessionData().put(PORT_REMOTE_HOST_PROP_KEY, remote_host);
service.getSessionData().put(PORT_ROUTING_TABLE_PROP_KEY, new String[] { remote_host,
".*@" + remote_host, ".*\\." + remote_host });
String id = UUID.randomUUID().toString();
service.getSessionData().put(XMPPIOService.SESSION_ID_KEY, id);
return "<stream:stream" + " xmlns='" + XMLNS + "'"
+ " xmlns:stream='http://etherx.jabber.org/streams'" + " from='" + getDefHostName()
+ "'" + " to='" + remote_host + "'" + " id='" + id + "'" + ">";
}
default :
// Do nothing, more data should come soon...
break;
} // end of switch (service.connectionType())
return null;
}
//~--- get methods ----------------------------------------------------------
@Override
protected int[] getDefPlainPorts() {
return PORTS;
}
/**
* Method <code>getMaxInactiveTime</code> returns max keep-alive time
* for inactive connection. we shoulnd not really close external component
* connection at all, so let's say something like: 1000 days...
*
* @return a <code>long</code> value
*/
@Override
protected long getMaxInactiveTime() {
return 1000 * 24 * HOUR;
}
@Override
protected Integer getMaxQueueSize(int def) {
return def * 10;
}
@Override
protected Map<String, Object> getParamsForPort(int port) {
Map<String, Object> defs = new LinkedHashMap<String, Object>(10);
defs.put(SECRET_PROP_KEY, SECRET_PROP_VAL);
defs.put(PORT_TYPE_PROP_KEY, ConnectionType.accept);
defs.put(PORT_SOCKET_PROP_KEY, SocketType.plain);
defs.put(PORT_IFC_PROP_KEY, PORT_IFC_PROP_VAL);
return defs;
}
@Override
protected String getServiceId(Packet packet) {
try {
return DNSResolver.getHostIP(packet.getTo().getDomain());
} catch (UnknownHostException e) {
log.log(Level.WARNING, "Uknown host exception for address: {0}", packet.getTo().getDomain());
return packet.getTo().getDomain();
}
}
@Override
protected String getUniqueId(XMPPIOService<Object> serv) {
// return (String)serv.getSessionData().get(PORT_REMOTE_HOST_PROP_KEY);
return serv.getRemoteAddress();
}
@Override
protected XMPPIOService<Object> getXMPPIOServiceInstance() {
return new XMPPIOService<Object>();
}
@Override
protected boolean isHighThroughput() {
return true;
}
//~--- methods --------------------------------------------------------------
protected void serviceConnected(XMPPIOService<Object> serv) {
String[] routings = (String[]) serv.getSessionData().get(PORT_ROUTING_TABLE_PROP_KEY);
updateRoutings(routings, true);
String addr = (String) serv.getSessionData().get(PORT_REMOTE_HOST_PROP_KEY);
log.log(Level.INFO, "Connected to: {0}", addr);
updateServiceDiscoveryItem(addr, addr, XMLNS + " connected", true);
clusterController.nodeConnected(addr);
ServiceConnectedTimer task =
(ServiceConnectedTimer) serv.getSessionData().get(SERVICE_CONNECTED_TIMER);
if (task == null) {
log.log(Level.WARNING, "Missing service connected timer task: {0}", serv);
} else {
task.cancel();
}
// Map<String, String> method_params = new LinkedHashMap<String, String>();
// method_params.put("connected", addr);
// addOutPacket(new Packet(ClusterElement.createClusterMethodCall(
// getComponentId(), cluster_controller_id,
// StanzaType.set, ClusterMethods.UPDATE_NODES.toString(),
// method_params).getClusterElement()));
// synchronized (waiting_packs) {
// LinkedHashMap<Long, Packet> waiting_packets =
// waiting_packs.get(serv.getRemoteAddress());
// if (waiting_packets == null) {
// waiting_packets = new LinkedHashMap<Long, Packet>();
// waiting_ack.put(serv.getRemoteAddress(), waiting_packets);
// }
// }
}
@Override
protected boolean writePacketToSocket(Packet p) {
// long rid = ++send_rid;
// p.getElement().setAttribute("rid", ""+rid);
// synchronized (waiting_packs) {
// LinkedHashMap<Long, Packet> waiting_packets =
// waiting_packs.get(getServiceId(p));
// if (waiting_packets == null) {
// waiting_packets = new LinkedHashMap<Long, Packet>();
// waiting_ack.put(getServiceId(p), waiting_packets);
// }
// waiting_packets.put(rid, p);
// }
return super.writePacketToSocket(p);
}
//private void processReceivedAck(Packet packet, XMPPIOService serv) {
// String ack_str = packet.getAttribute("ack");
// if (ack_str == null) {
// log.warning("ack attribute is null for packet: " + packet.toString()
// + ", please update all cluster nodes.");
// } else {
// try {
// long r_ack = Long.parseLong(ack_str);
// synchronized (waiting_packs) {
// LinkedHashMap<Long, Packet> waiting_packets =
// waiting_packs.get(serv.getRemoteAddress());
// if (waiting_packets == null) {
// log.warning("Checking ACK and waiting_packets is null for packet: " +
// packet);
// return;
// }
// long last_ack = received_acks.get(serv.getRemoteAddress());
// if (r_ack == (++last_ack)) {
// received_acks.put(serv.getRemoteAddress(), r_ack);
// Packet p = waiting_packets.remove(r_ack);
// if (p == null) {
// log.warning("Packet for r_ack = " + r_ack + " not found...");
// }
// } else {
// }
// }
// } catch (NumberFormatException e) {
// log.warning("Incorrect ack value in packet: " + packet.toString());
// }
// }
//}
//private void processReceivedRid(Packet packet, XMPPIOService serv) {
// String rid_str = packet.getAttribute("rid");
// if (rid_str == null) {
// log.warning("rid attribute is null for packet: " + packet.toString()
// + ", please update all cluster nodes.");
// } else {
// try {
// long r_rid = Long.parseLong(rid_str);
// } catch (NumberFormatException e) {
// log.warning("Incorrect rid value in packet: " + packet.toString());
// }
// }
//}
private void processHandshake(Packet p, XMPPIOService<Object> serv) {
switch (serv.connectionType()) {
case connect : {
String data = p.getElemCData();
if (data == null) {
serviceConnected(serv);
} else {
log.log(Level.WARNING, "Incorrect packet received: {0}", p);
}
break;
}
case accept : {
String digest = p.getElemCData();
String id = (String) serv.getSessionData().get(XMPPIOService.SESSION_ID_KEY);
String secret = (String) serv.getSessionData().get(SECRET_PROP_KEY);
try {
String loc_digest = Algorithms.hexDigest(id, secret, "SHA");
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Calculating digest: id={0}, secret={1}, digest={2}",
new Object[] { id,
secret, loc_digest });
}
if ((digest != null) && digest.equals(loc_digest)) {
Packet resp = Packet.packetInstance(new Element("handshake"), null, null);
writePacketToSocket(serv, resp);
serviceConnected(serv);
} else {
log.warning("Handshaking password doesn't match, disconnecting...");
serv.stop();
}
} catch (Exception e) {
log.log(Level.SEVERE, "Handshaking error.", e);
}
break;
}
default :
// Do nothing, more data should come soon...
break;
} // end of switch (service.connectionType())
}
private void updateRoutings(String[] routings, boolean add) {
if (add) {
for (String route : routings) {
try {
addRegexRouting(route);
} catch (Exception e) {
log.log(Level.WARNING, "Can not add regex routing ''{0}'' : {1}", new Object[] { route,
e });
}
}
} else {
for (String route : routings) {
try {
removeRegexRouting(route);
} catch (Exception e) {
log.log(Level.WARNING, "Can not remove regex routing ''{0}'' : {1}", new Object[] { route,
e });
}
}
}
}
//~--- inner classes --------------------------------------------------------
private class IOServiceStatisticsGetter implements ServiceChecker<XMPPIOService<Object>> {
private int clIOQueue = 0;
private float compressionRatio = 0f;
private int counter = 0;
private float decompressionRatio = 0f;
private StatisticsList list = new StatisticsList(Level.ALL);
//~--- methods ------------------------------------------------------------
/**
* Method description
*
*
* @param service
*/
@Override
public void check(XMPPIOService<Object> service) {
service.getStatistics(list, true);
compressionRatio += list.getValue("zlibio", "Average compression rate", -1f);
decompressionRatio += list.getValue("zlibio", "Average decompression rate", -1f);
++counter;
clIOQueue += service.waitingToSendSize();
}
//~--- get methods --------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public float getAverageCompressionRatio() {
return compressionRatio / counter;
}
/**
* Method description
*
*
* @return
*/
public float getAverageDecompressionRatio() {
return decompressionRatio / counter;
}
/**
* Method description
*
*
* @return
*/
public int getWaitingToSend() {
return clIOQueue;
}
//~--- methods ------------------------------------------------------------
/**
* Method description
*
*/
public void reset() {
// Statistics are reset on the low socket level instead. This way we do not loose
// any stats in case of the disconnection.
// bytesReceived = 0;
// bytesSent = 0;
clIOQueue = 0;
counter = 0;
compressionRatio = 0f;
decompressionRatio = 0f;
}
}
private class ServiceConnectedTimer extends TimerTask {
private XMPPIOService<Object> serv = null;
//~--- constructors -------------------------------------------------------
private ServiceConnectedTimer(XMPPIOService<Object> serv) {
this.serv = serv;
}
//~--- methods ------------------------------------------------------------
/**
* Method description
*
*/
@Override
public void run() {
++servConnectedTimeouts;
log.log(Level.INFO, "ServiceConnectedTimer timeout expired, closing connection: {0}", serv);
serv.forceStop();
}
}
}
//~ Formatted in Sun Code Convention
//~ Formatted by Jindent --- http://www.jindent.com
|
src/main/java/tigase/cluster/ClusterConnectionManager.java
|
/*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2007 "Artur Hefczyc" <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package tigase.cluster;
//~--- non-JDK imports --------------------------------------------------------
import tigase.annotations.TODO;
import tigase.net.ConnectionType;
//import tigase.net.IOService;
import tigase.net.SocketType;
import tigase.server.ConnectionManager;
import tigase.server.Packet;
import tigase.server.ServiceChecker;
import tigase.stats.StatisticsList;
import tigase.util.Algorithms;
import tigase.util.DNSResolver;
import tigase.util.TigaseStringprepException;
import tigase.util.TimeUtils;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.PacketErrorTypeException;
import tigase.xmpp.XMPPIOService;
//~--- JDK imports ------------------------------------------------------------
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Deflater;
import javax.script.Bindings;
//~--- classes ----------------------------------------------------------------
/**
* Class ClusterConnectionManager
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:[email protected]">Artur Hefczyc</a>
* @version $Rev$
*/
public class ClusterConnectionManager extends ConnectionManager<XMPPIOService<Object>>
implements ClusteredComponent {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger(ClusterConnectionManager.class.getName());
/** Field description */
public static final String SECRET_PROP_KEY = "secret";
/** Field description */
public static final String PORT_LOCAL_HOST_PROP_KEY = "local-host";
/** Field description */
public static final String PORT_ROUTING_TABLE_PROP_KEY = "routing-table";
/** Field description */
public static final String RETURN_SERVICE_DISCO_KEY = "service-disco";
/** Field description */
public static final boolean RETURN_SERVICE_DISCO_VAL = true;
/** Field description */
public static final String IDENTITY_TYPE_KEY = "identity-type";
/** Field description */
public static final String IDENTITY_TYPE_VAL = "generic";
/** Field description */
public static final String CONNECT_ALL_PAR = "--cluster-connect-all";
/** Field description */
public static final String CONNECT_ALL_PROP_KEY = "connect-all";
/** Field description */
public static final String CLUSTER_CONTR_ID_PROP_KEY = "cluster-controller-id";
/** Field description */
public static final boolean CONNECT_ALL_PROP_VAL = false;
/** Field description */
public static final String COMPRESS_STREAM_PROP_KEY = "compress-stream";
/** Field description */
public static final boolean COMPRESS_STREAM_PROP_VAL = false;
/** Field description */
public static final String XMLNS = "tigase:cluster";
private static final String SERVICE_CONNECTED_TIMER = "service-connected-timer";
//~--- fields ---------------------------------------------------------------
/** Field description */
public int[] PORTS = { 5277 };
/** Field description */
public String[] PORT_IFC_PROP_VAL = { "*" };
/** Field description */
public String SECRET_PROP_VAL = "someSecret";
private ClusterController clusterController = null;
// private boolean notify_admins = NOTIFY_ADMINS_PROP_VAL;
// private String[] admins = new String[] {};
private String cluster_controller_id = null;
private IOServiceStatisticsGetter ioStatsGetter = new IOServiceStatisticsGetter();
//private ServiceEntity serviceEntity = null;
// private boolean service_disco = RETURN_SERVICE_DISCO_VAL;
private String identity_type = IDENTITY_TYPE_VAL;
private boolean connect_all = CONNECT_ALL_PROP_VAL;
private boolean compress_stream = COMPRESS_STREAM_PROP_VAL;
private long[] lastDay = new long[24];
private int lastDayIdx = 0;
private long[] lastHour = new long[60];
private int lastHourIdx = 0;
//private LinkedHashMap<String, LinkedHashMap<Long, Packet>> waiting_packs =
// new LinkedHashMap<String, LinkedHashMap<Long, Packet>>();
//private LinkedHashMap<String, Long> sent_rids = new LinkedHashMap<String, Long>();
//private LinkedHashMap<String, Long> recieved_rids =
// new LinkedHashMap<String, Long>();
//private LinkedHashMap<String, Long> recieved_acks =
// new LinkedHashMap<String, Long>();
private int nodesNo = 0;
private long servConnectedTimeouts = 0;
private long totalNodeDisconnects = 0;
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @param params
*
* @return
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> props = super.getDefaults(params);
props.put(RETURN_SERVICE_DISCO_KEY, RETURN_SERVICE_DISCO_VAL);
props.put(IDENTITY_TYPE_KEY, IDENTITY_TYPE_VAL);
if ((params.get(CONNECT_ALL_PAR) == null)
||!((String) params.get(CONNECT_ALL_PAR)).equals("true")) {
props.put(CONNECT_ALL_PROP_KEY, false);
} else {
props.put(CONNECT_ALL_PROP_KEY, true);
}
if (params.get(CLUSTER_NODES) != null) {
String[] cl_nodes = ((String) params.get(CLUSTER_NODES)).split(",");
for (int i = 0; i < cl_nodes.length; i++) {
cl_nodes[i] = BareJID.parseJID(cl_nodes[i])[1];
}
nodesNo = cl_nodes.length;
props.put(CLUSTER_NODES_PROP_KEY, cl_nodes);
} else {
props.put(CLUSTER_NODES_PROP_KEY, new String[] { getDefHostName().getDomain() });
}
props.put(CLUSTER_CONTR_ID_PROP_KEY, DEF_CLUST_CONTR_NAME + "@" + getDefHostName());
props.put(COMPRESS_STREAM_PROP_KEY, COMPRESS_STREAM_PROP_VAL);
// props.put(NOTIFY_ADMINS_PROP_KEY, NOTIFY_ADMINS_PROP_VAL);
// if (params.get(GEN_ADMINS) != null) {
// admins = ((String)params.get(GEN_ADMINS)).split(",");
// } else {
// admins = new String[] { "admin@localhost" };
// }
// props.put(ADMINS_PROP_KEY, admins);
return props;
}
/**
* Method description
*
*
* @return
*/
@Override
public String getDiscoCategoryType() {
return identity_type;
}
//private void updateServiceDiscovery(String jid, String name) {
// ServiceEntity item = new ServiceEntity(jid, null, name);
// //item.addIdentities(new ServiceIdentity("component", identity_type, name));
// log.info("Modifing service-discovery info: " + item.toString());
// serviceEntity.addItems(item);
//}
//
//@Override
//public Element getDiscoInfo(String node, String jid) {
// if (jid != null && getName().equals(JIDUtils.getNodeNick(jid))) {
// return serviceEntity.getDiscoInfo(node);
// }
// return null;
//}
//
//@Override
//public List<Element> getDiscoFeatures() { return null; }
//
//@Override
//public List<Element> getDiscoItems(String node, String jid) {
// if (getName().equals(JIDUtils.getNodeNick(jid))) {
// return serviceEntity.getDiscoItems(node, null);
// } else {
// return Arrays.asList(serviceEntity.getDiscoItem(null,
// JIDUtils.getNodeID(getName(), jid)));
// }
//}
//
/**
* Method description
*
*
* @return
*/
@Override
public String getDiscoDescription() {
return XMLNS + " " + getName();
}
/**
* Method description
*
*
* @param list
*/
@Override
public void getStatistics(StatisticsList list) {
super.getStatistics(list);
list.add(getName(), "Total disconnects", totalNodeDisconnects, Level.FINE);
list.add(getName(), "Service connected time-outs", servConnectedTimeouts, Level.FINE);
list.add(getName(), "Last day disconnects", Arrays.toString(lastDay), Level.FINE);
list.add(getName(), "Last hour disconnects", Arrays.toString(lastHour), Level.FINE);
ioStatsGetter.reset();
doForAllServices(ioStatsGetter);
list.add(getName(), "Average compression ratio", ioStatsGetter.getAverageCompressionRatio(),
Level.FINE);
list.add(getName(), "Average decompression ratio",
ioStatsGetter.getAverageDecompressionRatio(), Level.FINE);
list.add(getName(), "Waiting to send", ioStatsGetter.getWaitingToSend(), Level.FINE);
}
//~--- methods --------------------------------------------------------------
/**
* This method can be overwritten in extending classes to get a different
* packets distribution to different threads. For PubSub, probably better
* packets distribution to different threads would be based on the
* sender address rather then destination address.
* @param packet
* @return
*/
@Override
public int hashCodeForPacket(Packet packet) {
// If this is a cluster packet let's try to do a bit more smart hashing
// based on the stanza from/to addresses
if (packet.getElemName() == ClusterElement.CLUSTER_EL_NAME) {
List<Element> children = packet.getElemChildren(ClusterElement.CLUSTER_DATA_PATH);
if ((children != null) && (children.size() > 0)) {
String stanzaAdd = children.get(0).getAttribute("to");
if (stanzaAdd != null) {
return stanzaAdd.hashCode();
} else {
// This might be user's initial presence. In such a case we take stanzaFrom instead
stanzaAdd = children.get(0).getAttribute("from");
if (stanzaAdd != null) {
return stanzaAdd.hashCode();
} else {
log.log(Level.WARNING, "No stanzaTo or from for cluster packet: {0}", packet);
}
}
}
}
// There is a separate connection to each cluster node, ideally we want to
// process packets in a separate thread for each connection, so let's try
// to get the hash code by the destination node address
if (packet.getStanzaTo() != null) {
return packet.getStanzaTo().hashCode();
}
return packet.getTo().hashCode();
}
/**
* Method description
*
*
* @param binds
*/
@Override
public void initBindings(Bindings binds) {
super.initBindings(binds);
binds.put("clusterCM", this);
}
/**
* Method description
*
*
* @param node
*/
@Override
public void nodeConnected(String node) {}
/**
* Method description
*
*
* @param node
*/
@Override
public void nodeDisconnected(String node) {}
/**
* Method description
*
*
* @param packet
*/
@Override
public void processPacket(Packet packet) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing packet: {0}", packet);
}
if ((packet.getStanzaTo() != null) && packet.getStanzaTo().equals(getComponentId())) {
try {
addOutPacket(Authorization.FEATURE_NOT_IMPLEMENTED.getResponseMessage(packet,
"Not implemented", true));
} catch (PacketErrorTypeException e) {
log.log(Level.WARNING, "Packet processing exception: {0}", e);
}
return;
}
writePacketToSocket(packet.packRouted());
// if (packet.getElemName() == ClusterElement.CLUSTER_EL_NAME) {
// writePacketToSocket(packet);
// } else {
// writePacketToSocket(packet.packRouted());
// }
}
/**
* Method description
*
*
* @param serv
*
* @return
*/
@Override
public Queue<Packet> processSocketData(XMPPIOService<Object> serv) {
Packet p = null;
while ((p = serv.getReceivedPackets().poll()) != null) {
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Processing socket data: {0}", p);
}
if (p.getElemName().equals("handshake")) {
processHandshake(p, serv);
} else {
Packet result = p;
if (p.isRouted()) {
// processReceivedRid(p, serv);
// processReceivedAck(p, serv);
try {
result = p.unpackRouted();
} catch (TigaseStringprepException ex) {
log.log(Level.WARNING, "Packet stringprep addressing problem, dropping packet: {0}", p);
return null;
}
} // end of if (p.isRouted())
addOutPacket(result);
}
} // end of while ()
return null;
}
/**
*
* @return
*/
@Override
@TODO(note = "The number of threads should be equal or greater to number of cluster nodes.")
public int processingThreads() {
// This should work well as far as nodesNo is initialized before this
// method is called which is true only during program startup time.
// In case of reconfiguration or new node joining this might not be
// the case. Low priority issue though.
return Math.max(Runtime.getRuntime().availableProcessors(), nodesNo);
}
/**
* Method description
*
*
* @param port_props
*/
@Override
public void reconnectionFailed(Map<String, Object> port_props) {
// TODO: handle this somehow
}
/**
* Method description
*
*
* @param serv
*/
@Override
public void serviceStarted(XMPPIOService<Object> serv) {
ServiceConnectedTimer task = new ServiceConnectedTimer(serv);
serv.getSessionData().put(SERVICE_CONNECTED_TIMER, task);
addTimerTask(task, 10, TimeUnit.SECONDS);
super.serviceStarted(serv);
log.log(Level.INFO, "cluster connection opened: {0}, type: {1}, id={2}",
new Object[] { serv.getRemoteAddress(),
serv.connectionType().toString(), serv.getUniqueId() });
if (compress_stream) {
log.log(Level.INFO, "Starting stream compression for: {0}", serv.getUniqueId());
serv.startZLib(Deflater.BEST_COMPRESSION);
}
// String addr =
// (String)service.getSessionData().get(PORT_REMOTE_HOST_PROP_KEY);
// addRouting(addr);
// addRouting(serv.getRemoteHost());
switch (serv.connectionType()) {
case connect :
// Send init xmpp stream here
// XMPPIOService serv = (XMPPIOService)service;
String remote_host = (String) serv.getSessionData().get(PORT_REMOTE_HOST_PROP_KEY);
serv.getSessionData().put(XMPPIOService.HOSTNAME_KEY, remote_host);
serv.getSessionData().put(PORT_ROUTING_TABLE_PROP_KEY, new String[] { remote_host,
".*@" + remote_host, ".*\\." + remote_host });
String data = "<stream:stream" + " xmlns='" + XMLNS + "'"
+ " xmlns:stream='http://etherx.jabber.org/streams'" + " from='" + getDefHostName() + "'"
+ " to='" + remote_host + "'" + ">";
log.log(Level.INFO, "cid: {0}, sending: {1}",
new Object[] { (String) serv.getSessionData().get("cid"),
data });
serv.xmppStreamOpen(data);
break;
default :
// Do nothing, more data should come soon...
break;
} // end of switch (service.connectionType())
}
/**
* Method description
*
*
* @param service
*
* @return
*/
@Override
public boolean serviceStopped(XMPPIOService<Object> service) {
boolean result = super.serviceStopped(service);
// Make sure it runs just once for each disconnect
if (result) {
Map<String, Object> sessionData = service.getSessionData();
String[] routings = (String[]) sessionData.get(PORT_ROUTING_TABLE_PROP_KEY);
if (routings != null) {
updateRoutings(routings, false);
}
ConnectionType type = service.connectionType();
if (type == ConnectionType.connect) {
addWaitingTask(sessionData);
// reconnectService(sessionData, connectionDelay);
} // end of if (type == ConnectionType.connect)
// removeRouting(serv.getRemoteHost());
String addr = (String) sessionData.get(PORT_REMOTE_HOST_PROP_KEY);
log.log(Level.INFO, "Disonnected from: {0}", addr);
updateServiceDiscoveryItem(addr, addr, XMLNS + " disconnected", true);
clusterController.nodeDisconnected(addr);
// Map<String, String> method_params = new LinkedHashMap<String, String>();
// method_params.put("disconnected", addr);
// addOutPacket(new Packet(ClusterElement.createClusterMethodCall(
// getComponentId(), cluster_controller_id,
// StanzaType.set, ClusterMethods.UPDATE_NODES.toString(),
// method_params).getClusterElement()));
++totalNodeDisconnects;
int hour = TimeUtils.getHourNow();
if (lastDayIdx != hour) {
lastDayIdx = hour;
lastDay[hour] = 0;
Arrays.fill(lastHour, 0);
}
++lastDay[hour];
int minute = TimeUtils.getMinuteNow();
// if (lastHourIdx != minute) {
// lastHourIdx = minute;
// lastHour[minute] = 0;
// }
++lastHour[minute];
}
return result;
}
//~--- set methods ----------------------------------------------------------
/**
* Method description
*
*
* @param cl_controller
*/
@Override
public void setClusterController(ClusterController cl_controller) {
this.clusterController = cl_controller;
}
/**
* Method description
*
*
* @param props
*/
@Override
public void setProperties(Map<String, Object> props) {
super.setProperties(props);
// service_disco = (Boolean)props.get(RETURN_SERVICE_DISCO_KEY);
identity_type = (String) props.get(IDENTITY_TYPE_KEY);
compress_stream = (Boolean) props.get(COMPRESS_STREAM_PROP_KEY);
// serviceEntity = new ServiceEntity(getName(), "external", "XEP-0114");
// serviceEntity = new ServiceEntity(XMLNS + " " + getName(), null, XMLNS);
// serviceEntity.addIdentities(
// new ServiceIdentity("component", identity_type, XMLNS + " " + getName()));
connect_all = (Boolean) props.get(CONNECT_ALL_PROP_KEY);
cluster_controller_id = (String) props.get(CLUSTER_CONTR_ID_PROP_KEY);
// notify_admins = (Boolean)props.get(NOTIFY_ADMINS_PROP_KEY);
// admins = (String[])props.get(ADMINS_PROP_KEY);
connectionDelay = 5 * SECOND;
String[] cl_nodes = (String[]) props.get(CLUSTER_NODES_PROP_KEY);
int[] ports = (int[]) props.get(PORTS_PROP_KEY);
if (ports != null) {
PORTS = ports;
}
if (cl_nodes != null) {
nodesNo = cl_nodes.length;
for (String node : cl_nodes) {
String host = BareJID.parseJID(node)[1];
log.log(Level.CONFIG, "Found cluster node host: {0}", host);
if ( !host.equals(getDefHostName().getDomain())
&& ((host.hashCode() > getDefHostName().hashCode()) || connect_all)) {
log.log(Level.CONFIG, "Trying to connect to cluster node: {0}", host);
Map<String, Object> port_props = new LinkedHashMap<String, Object>(12);
port_props.put(SECRET_PROP_KEY, SECRET_PROP_VAL);
port_props.put(PORT_LOCAL_HOST_PROP_KEY, getDefHostName());
port_props.put(PORT_TYPE_PROP_KEY, ConnectionType.connect);
port_props.put(PORT_SOCKET_PROP_KEY, SocketType.plain);
port_props.put(PORT_REMOTE_HOST_PROP_KEY, host);
port_props.put(PORT_IFC_PROP_KEY, new String[] { host });
port_props.put(MAX_RECONNECTS_PROP_KEY, 99999999);
port_props.put(PORT_KEY, PORTS[0]);
addWaitingTask(port_props);
// reconnectService(port_props, connectionDelay);
}
}
}
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param service
*/
@Override
public void tlsHandshakeCompleted(XMPPIOService<Object> service) {}
/**
* Method description
*
*
* @param serv
*/
@Override
public void xmppStreamClosed(XMPPIOService<Object> serv) {
log.info("Stream closed.");
}
/**
* Method description
*
*
* @param service
* @param attribs
*
* @return
*/
@Override
public String xmppStreamOpened(XMPPIOService<Object> service, Map<String, String> attribs) {
log.log(Level.INFO, "Stream opened: {0}", attribs);
switch (service.connectionType()) {
case connect : {
String id = attribs.get("id");
service.getSessionData().put(XMPPIOService.SESSION_ID_KEY, id);
String secret = (String) service.getSessionData().get(SECRET_PROP_KEY);
try {
String digest = Algorithms.hexDigest(id, secret, "SHA");
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Calculating digest: id={0}, secret={1}, digest={2}",
new Object[] { id,
secret, digest });
}
return "<handshake>" + digest + "</handshake>";
} catch (NoSuchAlgorithmException e) {
log.log(Level.SEVERE, "Can not generate digest for pass phrase.", e);
return null;
}
}
case accept : {
String remote_host = attribs.get("from");
service.getSessionData().put(XMPPIOService.HOSTNAME_KEY, remote_host);
service.getSessionData().put(PORT_REMOTE_HOST_PROP_KEY, remote_host);
service.getSessionData().put(PORT_ROUTING_TABLE_PROP_KEY, new String[] { remote_host,
".*@" + remote_host, ".*\\." + remote_host });
String id = UUID.randomUUID().toString();
service.getSessionData().put(XMPPIOService.SESSION_ID_KEY, id);
return "<stream:stream" + " xmlns='" + XMLNS + "'"
+ " xmlns:stream='http://etherx.jabber.org/streams'" + " from='" + getDefHostName()
+ "'" + " to='" + remote_host + "'" + " id='" + id + "'" + ">";
}
default :
// Do nothing, more data should come soon...
break;
} // end of switch (service.connectionType())
return null;
}
//~--- get methods ----------------------------------------------------------
@Override
protected int[] getDefPlainPorts() {
return PORTS;
}
/**
* Method <code>getMaxInactiveTime</code> returns max keep-alive time
* for inactive connection. we shoulnd not really close external component
* connection at all, so let's say something like: 1000 days...
*
* @return a <code>long</code> value
*/
@Override
protected long getMaxInactiveTime() {
return 1000 * 24 * HOUR;
}
@Override
protected Integer getMaxQueueSize(int def) {
return def * 10;
}
@Override
protected Map<String, Object> getParamsForPort(int port) {
Map<String, Object> defs = new LinkedHashMap<String, Object>(10);
defs.put(SECRET_PROP_KEY, SECRET_PROP_VAL);
defs.put(PORT_TYPE_PROP_KEY, ConnectionType.accept);
defs.put(PORT_SOCKET_PROP_KEY, SocketType.plain);
defs.put(PORT_IFC_PROP_KEY, PORT_IFC_PROP_VAL);
return defs;
}
@Override
protected String getServiceId(Packet packet) {
try {
return DNSResolver.getHostIP(packet.getTo().getDomain());
} catch (UnknownHostException e) {
log.log(Level.WARNING, "Uknown host exception for address: {0}", packet.getTo().getDomain());
return packet.getTo().getDomain();
}
}
@Override
protected String getUniqueId(XMPPIOService<Object> serv) {
// return (String)serv.getSessionData().get(PORT_REMOTE_HOST_PROP_KEY);
return serv.getRemoteAddress();
}
@Override
protected XMPPIOService<Object> getXMPPIOServiceInstance() {
return new XMPPIOService<Object>();
}
@Override
protected boolean isHighThroughput() {
return true;
}
//~--- methods --------------------------------------------------------------
protected void serviceConnected(XMPPIOService<Object> serv) {
String[] routings = (String[]) serv.getSessionData().get(PORT_ROUTING_TABLE_PROP_KEY);
updateRoutings(routings, true);
String addr = (String) serv.getSessionData().get(PORT_REMOTE_HOST_PROP_KEY);
log.log(Level.INFO, "Connected to: {0}", addr);
updateServiceDiscoveryItem(addr, addr, XMLNS + " connected", true);
clusterController.nodeConnected(addr);
ServiceConnectedTimer task =
(ServiceConnectedTimer) serv.getSessionData().get(SERVICE_CONNECTED_TIMER);
if (task == null) {
log.log(Level.WARNING, "Missing service connected timer task: {0}", serv);
} else {
task.cancel();
}
// Map<String, String> method_params = new LinkedHashMap<String, String>();
// method_params.put("connected", addr);
// addOutPacket(new Packet(ClusterElement.createClusterMethodCall(
// getComponentId(), cluster_controller_id,
// StanzaType.set, ClusterMethods.UPDATE_NODES.toString(),
// method_params).getClusterElement()));
// synchronized (waiting_packs) {
// LinkedHashMap<Long, Packet> waiting_packets =
// waiting_packs.get(serv.getRemoteAddress());
// if (waiting_packets == null) {
// waiting_packets = new LinkedHashMap<Long, Packet>();
// waiting_ack.put(serv.getRemoteAddress(), waiting_packets);
// }
// }
}
@Override
protected boolean writePacketToSocket(Packet p) {
// long rid = ++send_rid;
// p.getElement().setAttribute("rid", ""+rid);
// synchronized (waiting_packs) {
// LinkedHashMap<Long, Packet> waiting_packets =
// waiting_packs.get(getServiceId(p));
// if (waiting_packets == null) {
// waiting_packets = new LinkedHashMap<Long, Packet>();
// waiting_ack.put(getServiceId(p), waiting_packets);
// }
// waiting_packets.put(rid, p);
// }
return super.writePacketToSocket(p);
}
//private void processReceivedAck(Packet packet, XMPPIOService serv) {
// String ack_str = packet.getAttribute("ack");
// if (ack_str == null) {
// log.warning("ack attribute is null for packet: " + packet.toString()
// + ", please update all cluster nodes.");
// } else {
// try {
// long r_ack = Long.parseLong(ack_str);
// synchronized (waiting_packs) {
// LinkedHashMap<Long, Packet> waiting_packets =
// waiting_packs.get(serv.getRemoteAddress());
// if (waiting_packets == null) {
// log.warning("Checking ACK and waiting_packets is null for packet: " +
// packet);
// return;
// }
// long last_ack = received_acks.get(serv.getRemoteAddress());
// if (r_ack == (++last_ack)) {
// received_acks.put(serv.getRemoteAddress(), r_ack);
// Packet p = waiting_packets.remove(r_ack);
// if (p == null) {
// log.warning("Packet for r_ack = " + r_ack + " not found...");
// }
// } else {
// }
// }
// } catch (NumberFormatException e) {
// log.warning("Incorrect ack value in packet: " + packet.toString());
// }
// }
//}
//private void processReceivedRid(Packet packet, XMPPIOService serv) {
// String rid_str = packet.getAttribute("rid");
// if (rid_str == null) {
// log.warning("rid attribute is null for packet: " + packet.toString()
// + ", please update all cluster nodes.");
// } else {
// try {
// long r_rid = Long.parseLong(rid_str);
// } catch (NumberFormatException e) {
// log.warning("Incorrect rid value in packet: " + packet.toString());
// }
// }
//}
private void processHandshake(Packet p, XMPPIOService<Object> serv) {
switch (serv.connectionType()) {
case connect : {
String data = p.getElemCData();
if (data == null) {
serviceConnected(serv);
} else {
log.log(Level.WARNING, "Incorrect packet received: {0}", p);
}
break;
}
case accept : {
String digest = p.getElemCData();
String id = (String) serv.getSessionData().get(XMPPIOService.SESSION_ID_KEY);
String secret = (String) serv.getSessionData().get(SECRET_PROP_KEY);
try {
String loc_digest = Algorithms.hexDigest(id, secret, "SHA");
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Calculating digest: id={0}, secret={1}, digest={2}",
new Object[] { id,
secret, loc_digest });
}
if ((digest != null) && digest.equals(loc_digest)) {
Packet resp = Packet.packetInstance(new Element("handshake"), null, null);
writePacketToSocket(serv, resp);
serviceConnected(serv);
} else {
log.warning("Handshaking password doesn't match, disconnecting...");
serv.stop();
}
} catch (Exception e) {
log.log(Level.SEVERE, "Handshaking error.", e);
}
break;
}
default :
// Do nothing, more data should come soon...
break;
} // end of switch (service.connectionType())
}
private void updateRoutings(String[] routings, boolean add) {
if (add) {
for (String route : routings) {
try {
addRegexRouting(route);
} catch (Exception e) {
log.log(Level.WARNING, "Can not add regex routing ''{0}'' : {1}", new Object[] { route,
e });
}
}
} else {
for (String route : routings) {
try {
removeRegexRouting(route);
} catch (Exception e) {
log.log(Level.WARNING, "Can not remove regex routing ''{0}'' : {1}", new Object[] { route,
e });
}
}
}
}
//~--- inner classes --------------------------------------------------------
private class IOServiceStatisticsGetter implements ServiceChecker<XMPPIOService<Object>> {
private int clIOQueue = 0;
private float compressionRatio = 0f;
private int counter = 0;
private float decompressionRatio = 0f;
private StatisticsList list = new StatisticsList(Level.ALL);
//~--- methods ------------------------------------------------------------
/**
* Method description
*
*
* @param service
*/
@Override
public void check(XMPPIOService<Object> service) {
service.getStatistics(list, true);
compressionRatio += list.getValue("zlibio", "Average compression rate", -1f);
decompressionRatio += list.getValue("zlibio", "Average decompression rate", -1f);
++counter;
clIOQueue += service.waitingToSendSize();
}
//~--- get methods --------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public float getAverageCompressionRatio() {
return compressionRatio / counter;
}
/**
* Method description
*
*
* @return
*/
public float getAverageDecompressionRatio() {
return decompressionRatio / counter;
}
/**
* Method description
*
*
* @return
*/
public int getWaitingToSend() {
return clIOQueue;
}
//~--- methods ------------------------------------------------------------
/**
* Method description
*
*/
public void reset() {
// Statistics are reset on the low socket level instead. This way we do not loose
// any stats in case of the disconnection.
// bytesReceived = 0;
// bytesSent = 0;
clIOQueue = 0;
counter = 0;
compressionRatio = 0f;
decompressionRatio = 0f;
}
}
private class ServiceConnectedTimer extends TimerTask {
private XMPPIOService<Object> serv = null;
//~--- constructors -------------------------------------------------------
private ServiceConnectedTimer(XMPPIOService<Object> serv) {
this.serv = serv;
}
//~--- methods ------------------------------------------------------------
/**
* Method description
*
*/
@Override
public void run() {
++servConnectedTimeouts;
log.log(Level.INFO, "ServiceConnectedTimer timeout expired, closing connection: {0}", serv);
serv.forceStop();
}
}
}
//~ Formatted in Sun Code Convention
//~ Formatted by Jindent --- http://www.jindent.com
|
More threads for cluster connection manager.
git-svn-id: 4a0daf30c0bbd291b3bc5fe8f058bf11ee523347@2494 7d282ba1-3ae6-0310-8f9b-c9008a0864d2
|
src/main/java/tigase/cluster/ClusterConnectionManager.java
|
More threads for cluster connection manager.
|
<ide><path>rc/main/java/tigase/cluster/ClusterConnectionManager.java
<ide> // method is called which is true only during program startup time.
<ide> // In case of reconfiguration or new node joining this might not be
<ide> // the case. Low priority issue though.
<del> return Math.max(Runtime.getRuntime().availableProcessors(), nodesNo);
<add> return Math.max(Runtime.getRuntime().availableProcessors(), nodesNo) * 4;
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
558822d68a5fba09d4203dc67a7d3136f487d4ef
| 0 |
OpenUniversity/ovirt-engine,halober/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,halober/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine
|
package org.ovirt.engine.ui.uicommonweb.dataprovider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.MissingResourceException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.EventNotificationEntity;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.VdcEventNotificationUtils;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.gluster.GlusterVolumeRemoveBricksQueriesParameters;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.DbGroup;
import org.ovirt.engine.core.common.businessentities.DbUser;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskInterface;
import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.common.businessentities.ExternalComputeResource;
import org.ovirt.engine.core.common.businessentities.ExternalDiscoveredHost;
import org.ovirt.engine.core.common.businessentities.ExternalHostGroup;
import org.ovirt.engine.core.common.businessentities.IVdcQueryable;
import org.ovirt.engine.core.common.businessentities.ImageFileType;
import org.ovirt.engine.core.common.businessentities.LUNs;
import org.ovirt.engine.core.common.businessentities.Permissions;
import org.ovirt.engine.core.common.businessentities.Provider;
import org.ovirt.engine.core.common.businessentities.ProviderType;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.businessentities.QuotaEnforcementTypeEnum;
import org.ovirt.engine.core.common.businessentities.RepoImage;
import org.ovirt.engine.core.common.businessentities.Role;
import org.ovirt.engine.core.common.businessentities.ServerCpu;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.Tags;
import org.ovirt.engine.core.common.businessentities.TagsType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmGuestAgentInterface;
import org.ovirt.engine.core.common.businessentities.VmPool;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VmTemplateStatus;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.comparators.LexoNumericComparator;
import org.ovirt.engine.core.common.businessentities.comparators.NameableComparator;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterBrickEntity;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterClusterService;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterHookEntity;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterServerService;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeEntity;
import org.ovirt.engine.core.common.businessentities.gluster.ServiceType;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkQoS;
import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VmInterfaceType;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VnicProfile;
import org.ovirt.engine.core.common.businessentities.network.VnicProfileView;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.queries.ArchCapabilitiesParameters;
import org.ovirt.engine.core.common.queries.ArchCapabilitiesParameters.ArchCapabilitiesVerb;
import org.ovirt.engine.core.common.queries.CommandVersionsInfo;
import org.ovirt.engine.core.common.queries.ConfigurationValues;
import org.ovirt.engine.core.common.queries.GetAgentFenceOptionsQueryParameters;
import org.ovirt.engine.core.common.queries.GetAllAttachableDisks;
import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters;
import org.ovirt.engine.core.common.queries.GetAllProvidersParameters;
import org.ovirt.engine.core.common.queries.GetAllServerCpuListParameters;
import org.ovirt.engine.core.common.queries.GetConfigurationValueParameters;
import org.ovirt.engine.core.common.queries.GetConnectionsByDataCenterAndStorageTypeParameters;
import org.ovirt.engine.core.common.queries.GetDataCentersWithPermittedActionOnClustersParameters;
import org.ovirt.engine.core.common.queries.GetEntitiesWithPermittedActionParameters;
import org.ovirt.engine.core.common.queries.GetExistingStorageDomainListParameters;
import org.ovirt.engine.core.common.queries.GetHostListFromExternalProviderParameters;
import org.ovirt.engine.core.common.queries.GetHostsForStorageOperationParameters;
import org.ovirt.engine.core.common.queries.GetImagesListByStoragePoolIdParameters;
import org.ovirt.engine.core.common.queries.GetLunsByVgIdParameters;
import org.ovirt.engine.core.common.queries.GetPermittedStorageDomainsByStoragePoolIdParameters;
import org.ovirt.engine.core.common.queries.GetStorageDomainsByConnectionParameters;
import org.ovirt.engine.core.common.queries.GetStoragePoolsByClusterServiceParameters;
import org.ovirt.engine.core.common.queries.GetTagsByUserGroupIdParameters;
import org.ovirt.engine.core.common.queries.GetTagsByUserIdParameters;
import org.ovirt.engine.core.common.queries.GetTagsByVdsIdParameters;
import org.ovirt.engine.core.common.queries.GetTagsByVmIdParameters;
import org.ovirt.engine.core.common.queries.GetVmTemplateParameters;
import org.ovirt.engine.core.common.queries.GetVmUpdatesOnNextRunExistsParameters;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.InterfaceAndIdQueryParameters;
import org.ovirt.engine.core.common.queries.MultilevelAdministrationsQueriesParameters;
import org.ovirt.engine.core.common.queries.NameQueryParameters;
import org.ovirt.engine.core.common.queries.OsQueryParameters;
import org.ovirt.engine.core.common.queries.OsQueryParameters.OsRepositoryVerb;
import org.ovirt.engine.core.common.queries.ProviderQueryParameters;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.ServerParameters;
import org.ovirt.engine.core.common.queries.StorageServerConnectionQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.queries.VdsIdParametersBase;
import org.ovirt.engine.core.common.queries.gluster.AddedGlusterServersParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterHookContentQueryParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterHookQueryParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterServersQueryParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterServiceQueryParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterVolumeAdvancedDetailsParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterVolumeProfileParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterVolumeQueriesParameters;
import org.ovirt.engine.core.common.utils.ObjectUtils;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.utils.SimpleDependecyInjector;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.IntegerCompat;
import org.ovirt.engine.core.compat.KeyValuePairCompat;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.RpmVersion;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.searchbackend.OsValueAutoCompleter;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.IAsyncConverter;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.models.ApplicationModeHelper;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.LoginModel;
import org.ovirt.engine.ui.uicommonweb.models.datacenters.NetworkQoSModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.FcpStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.GlusterStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.IStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.ImportFcpStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.ImportIscsiStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.IscsiStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.LocalStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.NfsStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.PosixStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.WANDisableEffects;
import org.ovirt.engine.ui.uicommonweb.models.vms.WanColorDepth;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.EventArgs;
import org.ovirt.engine.ui.uicompat.FrontendMultipleQueryAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleQueryAsyncCallback;
import org.ovirt.engine.ui.uicompat.SpiceConstantsManager;
public class AsyncDataProvider {
private static AsyncDataProvider instance;
public static AsyncDataProvider getInstance() {
if (instance == null) {
instance = new AsyncDataProvider();
}
return instance;
}
public static void setInstance(AsyncDataProvider provider) {
instance = provider;
}
private static final String GENERAL = "general"; //$NON-NLS-1$
// dictionary to hold cache of all config values (per version) queried by client, if the request for them succeeded.
private HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object> cachedConfigValues =
new HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object>();
private HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object> cachedConfigValuesPreConvert =
new HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object>();
private String _defaultConfigurationVersion = null;
// cached OS names
private HashMap<Integer, String> osNames;
// cached list of os ids
private List<Integer> osIds;
// cached unique OS names
private HashMap<Integer, String> uniqueOsNames;
// cached linux OS
private List<Integer> linuxOsIds;
// cached NIC hotplug support map
private Map<Pair<Integer, Version>, Boolean> nicHotplugSupportMap;
// cached disk hotpluggable interfaces map
private Map<Pair<Integer, Version>, Set<String>> diskHotpluggableInterfacesMap;
// cached os's balloon enabled by default map (given compatibility version)
private Map<Integer, Map<Version, Boolean>> balloonSupportMap;
// cached windows OS
private List<Integer> windowsOsIds;
// cached OS Architecture
private HashMap<Integer, ArchitectureType> osArchitectures;
// default OS per architecture
private HashMap<ArchitectureType, Integer> defaultOSes;
// cached os's support for display types (given compatibility version)
private HashMap<Integer, Map<Version, List<DisplayType>>> displayTypes;
// cached architecture support for live migration
private Map<ArchitectureType, Map<Version, Boolean>> migrationSupport;
// cached architecture support for memory snapshot
private Map<ArchitectureType, Map<Version, Boolean>> memorySnapshotSupport;
// cached architecture support for VM suspend
private Map<ArchitectureType, Map<Version, Boolean>> suspendSupport;
// cached custom properties
private Map<Version, Map<String, String>> customPropertiesList;
public String getDefaultConfigurationVersion() {
return _defaultConfigurationVersion;
}
private void getDefaultConfigurationVersion(Object target) {
AsyncQuery callback = new AsyncQuery(target, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
if (returnValue != null) {
_defaultConfigurationVersion =
((VdcQueryReturnValue) returnValue).getReturnValue();
} else {
_defaultConfigurationVersion = GENERAL;
}
LoginModel loginModel = (LoginModel) model;
loginModel.getLoggedInEvent().raise(loginModel, EventArgs.EMPTY);
}
});
callback.setHandleFailure(true);
Frontend.getInstance().runQuery(VdcQueryType.GetDefaultConfigurationVersion,
new VdcQueryParametersBase(),
callback);
}
public void initCache(LoginModel loginModel) {
cacheConfigValues(new AsyncQuery(loginModel, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
getDefaultConfigurationVersion(target);
}
}));
initOsNames();
initUniqueOsNames();
initLinuxOsTypes();
initWindowsOsTypes();
initDisplayTypes();
initBalloonSupportMap();
initNicHotplugSupportMap();
initDiskHotpluggableInterfacesMap();
initOsArchitecture();
initDefaultOSes();
initMigrationSupportMap();
initMemorySnapshotSupportMap();
initSuspendSupportMap();
initCustomPropertiesList();
}
private void initCustomPropertiesList() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
customPropertiesList = (Map<Version, Map<String, String>>) returnValue;
}
};
callback.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return (source != null) ? (Map<Version, Map<String, String>>) source
: new HashMap<Version, Map<String, String>>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmCustomProperties,
new VdcQueryParametersBase().withoutRefresh(), callback);
}
public void initDefaultOSes() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
defaultOSes = ((VdcQueryReturnValue) returnValue)
.getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetDefaultOSes), callback);
}
public Boolean isMigrationSupported(ArchitectureType architecture, Version version) {
return migrationSupport.get(architecture).get(version);
}
public Boolean isMemorySnapshotSupportedByArchitecture(ArchitectureType architecture, Version version) {
return memorySnapshotSupport.get(architecture).get(version);
}
public Boolean isSuspendSupportedByArchitecture(ArchitectureType architecture, Version version) {
return suspendSupport.get(architecture).get(version);
}
private void initMigrationSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
migrationSupport = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetArchitectureCapabilities,
new ArchCapabilitiesParameters(ArchCapabilitiesVerb.GetMigrationSupport),
callback);
}
private void initMemorySnapshotSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
memorySnapshotSupport = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetArchitectureCapabilities,
new ArchCapabilitiesParameters(ArchCapabilitiesVerb.GetMemorySnapshotSupport),
callback);
}
private void initSuspendSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
suspendSupport = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetArchitectureCapabilities,
new ArchCapabilitiesParameters(ArchCapabilitiesVerb.GetSuspendSupport),
callback);
}
/**
* Check if memory snapshot is supported
* @param vm
* @return
*/
public boolean isMemorySnapshotSupported(VM vm) {
if (vm == null) {
return false;
}
boolean archMemorySnapshotSupported = isMemorySnapshotSupportedByArchitecture(
vm.getClusterArch(),
vm.getVdsGroupCompatibilityVersion());
return ((Boolean) getConfigValuePreConverted(
ConfigurationValues.MemorySnapshotSupported,
vm.getVdsGroupCompatibilityVersion().toString()))
&& archMemorySnapshotSupported;
}
public boolean canVmsBePaused(List<VM> items) {
for (VM vm : items) {
if (!isSuspendSupportedByArchitecture(vm.getClusterArch(),
vm.getVdsGroupCompatibilityVersion())) {
return false;
}
}
return true;
}
public boolean isLiveMergeSupported(VM vm) {
return (vm != null && (Boolean) getConfigValuePreConverted(
ConfigurationValues.LiveMergeSupported,
vm.getVdsGroupCompatibilityVersion().toString()));
}
public void initNicHotplugSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
nicHotplugSupportMap = ((VdcQueryReturnValue) returnValue)
.getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetNicHotplugSupportMap), callback);
}
public Map<Pair<Integer, Version>, Boolean> getNicHotplugSupportMap() {
return nicHotplugSupportMap;
}
public Boolean getNicHotplugSupport(Integer osId, Version version) {
Pair<Integer, Version> pair = new Pair<Integer, Version>(osId, version);
if (getNicHotplugSupportMap().containsKey(pair)) {
return getNicHotplugSupportMap().get(pair);
}
return false;
}
public Boolean isBalloonEnabled(int osId, Version version) {
return balloonSupportMap.get(osId).get(version);
}
public void initBalloonSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
balloonSupportMap = (Map<Integer, Map<Version, Boolean>>) ((VdcQueryReturnValue) returnValue)
.getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetBalloonSupportMap), callback);
}
public void initDiskHotpluggableInterfacesMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
diskHotpluggableInterfacesMap = ((VdcQueryReturnValue) returnValue)
.getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetDiskHotpluggableInterfacesMap), callback);
}
public Map<Pair<Integer, Version>, Set<String>> getDiskHotpluggableInterfacesMap() {
return diskHotpluggableInterfacesMap;
}
public Collection<DiskInterface> getDiskHotpluggableInterfaces(Integer osId, Version version) {
Set<String> diskHotpluggableInterfaces = getDiskHotpluggableInterfacesMap()
.get(new Pair<Integer, Version>(osId, version));
if (diskHotpluggableInterfaces == null) {
return Collections.emptySet();
}
Collection<DiskInterface> diskInterfaces = new HashSet<DiskInterface>();
for (String diskHotpluggableInterface : diskHotpluggableInterfaces) {
diskInterfaces.add(DiskInterface.valueOf(diskHotpluggableInterface));
}
return diskInterfaces;
}
public void getAAAProfilesListViaPublic(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<String>((ArrayList<String>) source)
: new ArrayList<String>();
}
};
Frontend.getInstance().runPublicQuery(VdcQueryType.GetAAAProfileList, new VdcQueryParametersBase(), aQuery);
}
public void getIsoDomainByDataCenterId(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<StorageDomain> storageDomains = (ArrayList<StorageDomain>) source;
for (StorageDomain domain : storageDomains)
{
if (domain.getStorageDomainType() == StorageDomainType.ISO)
{
return domain;
}
}
}
return null;
}
};
IdQueryParameters getIsoParams = new IdQueryParameters(dataCenterId);
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByStoragePoolId, getIsoParams, aQuery);
}
public void getExportDomainByDataCenterId(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<StorageDomain> storageDomains = (ArrayList<StorageDomain>) source;
for (StorageDomain domain : storageDomains)
{
if (domain.getStorageDomainType() == StorageDomainType.ImportExport)
{
return domain;
}
}
return null;
}
};
IdQueryParameters getExportParams = new IdQueryParameters(dataCenterId);
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByStoragePoolId, getExportParams, aQuery);
}
public void getIrsImageList(AsyncQuery aQuery, Guid storagePoolId) {
getIrsImageList(aQuery, storagePoolId, false);
}
public void getIrsImageList(AsyncQuery aQuery, Guid storagePoolId, boolean forceRefresh) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<RepoImage> repoList = (ArrayList<RepoImage>) source;
ArrayList<String> fileNameList = new ArrayList<String>();
for (RepoImage repoImage : repoList)
{
fileNameList.add(repoImage.getRepoImageId());
}
Collections.sort(fileNameList, String.CASE_INSENSITIVE_ORDER);
return fileNameList;
}
return new ArrayList<String>();
}
};
GetImagesListByStoragePoolIdParameters parameters =
new GetImagesListByStoragePoolIdParameters(storagePoolId, ImageFileType.ISO);
parameters.setForceRefresh(forceRefresh);
Frontend.getInstance().runQuery(VdcQueryType.GetImagesListByStoragePoolId, parameters, aQuery);
}
public void getFloppyImageList(AsyncQuery aQuery, Guid storagePoolId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<RepoImage> repoList = (ArrayList<RepoImage>) source;
ArrayList<String> fileNameList = new ArrayList<String>();
for (RepoImage repoImage : repoList)
{
fileNameList.add(repoImage.getRepoImageId());
}
Collections.sort(fileNameList, String.CASE_INSENSITIVE_ORDER);
return fileNameList;
}
return new ArrayList<String>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetImagesListByStoragePoolId,
new GetImagesListByStoragePoolIdParameters(storagePoolId, ImageFileType.Floppy),
aQuery);
}
public void isClusterEmpty(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter<Boolean>() {
@Override
public Boolean Convert(Object source, AsyncQuery _asyncQuery)
{
return (Boolean) source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.IsClusterEmpty, new IdQueryParameters(id), aQuery);
}
public void getHostArchitecture(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter<ArchitectureType>() {
@Override
public ArchitectureType Convert(Object source, AsyncQuery _asyncQuery)
{
return (ArchitectureType) source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetHostArchitecture, new IdQueryParameters(id), aQuery);
}
public void getClusterById(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVdsGroupById, new IdQueryParameters(id), aQuery);
}
public void getClusterListByName(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<VDSGroup>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters("Cluster: name=" + name + " sortby name", SearchType.Cluster), //$NON-NLS-1$ //$NON-NLS-2$
aQuery);
}
public void getPoolById(AsyncQuery aQuery, Guid poolId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmPoolById, new IdQueryParameters(poolId), aQuery);
}
public void getVmById(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmByVmId, new IdQueryParameters(vmId), aQuery);
}
public void getVmNextRunConfiguration(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmNextRunConfiguration, new IdQueryParameters(vmId), aQuery);
}
public void isNextRunConfigurationChanged(VM original, VM updated, AsyncQuery aQuery) {
Frontend.getInstance().runQuery(VdcQueryType.GetVmUpdatesOnNextRunExists,
new GetVmUpdatesOnNextRunExistsParameters(original, updated), aQuery);
}
public void getDataCenterList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<StoragePool>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters("DataCenter: sortby name", SearchType.StoragePool), //$NON-NLS-1$
aQuery);
}
public void getDataCenterByClusterServiceList(AsyncQuery aQuery,
boolean supportsVirtService,
boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source == null) {
return new ArrayList<StoragePool>();
}
// sort data centers
final ArrayList<StoragePool> storagePoolList = (ArrayList<StoragePool>) source;
Collections.sort(storagePoolList, new NameableComparator());
return source;
}
};
final GetStoragePoolsByClusterServiceParameters parameters = new GetStoragePoolsByClusterServiceParameters();
parameters.setSupportsVirtService(supportsVirtService);
parameters.setSupportsGlusterService(supportsGlusterService);
Frontend.getInstance().runQuery(VdcQueryType.GetStoragePoolsByClusterService, parameters, aQuery);
}
public void getDataCenterListByName(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<StoragePool>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters("DataCenter: name=" + name + " sortby name", SearchType.StoragePool), //$NON-NLS-1$ //$NON-NLS-2$
aQuery);
}
public void getSpiceUsbAutoShare(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Boolean) source).booleanValue() : true;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.SpiceUsbAutoShare,
getDefaultConfigurationVersion()),
aQuery);
}
public void getWANColorDepth(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? WanColorDepth.fromInt(((Integer) source).intValue()) : WanColorDepth.depth16;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.WANColorDepth, getDefaultConfigurationVersion()),
aQuery);
}
public void getWANDisableEffects(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<WANDisableEffects>();
}
List<WANDisableEffects> res = new ArrayList<WANDisableEffects>();
String fromDb = (String) source;
for (String value : fromDb.split(",")) {//$NON-NLS-1$
if (value == null) {
continue;
}
String trimmedValue = value.trim();
if ("".equals(trimmedValue)) {
continue;
}
res.add(WANDisableEffects.fromString(trimmedValue));
}
return res;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.WANDisableEffects,
getDefaultConfigurationVersion()),
aQuery);
}
public void getMaxVmsInPool(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1000;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.MaxVmsInPool, getDefaultConfigurationVersion()),
aQuery);
}
public void getMaxNumOfVmSockets(AsyncQuery aQuery, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.MaxNumOfVmSockets);
tempVar.setVersion(version);
getConfigFromCache(tempVar, aQuery);
}
public void getMaxNumOfVmCpus(AsyncQuery aQuery, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.MaxNumOfVmCpus);
tempVar.setVersion(version);
getConfigFromCache(tempVar, aQuery);
}
public void getMaxNumOfCPUsPerSocket(AsyncQuery aQuery, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.MaxNumOfCpuPerSocket);
tempVar.setVersion(version);
getConfigFromCache(tempVar, aQuery);
}
public void getClusterList(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDSGroup> list = (ArrayList<VDSGroup>) source;
Collections.sort(list, new NameableComparator());
return list;
}
return new ArrayList<VDSGroup>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVdsGroupsByStoragePoolId,
new IdQueryParameters(dataCenterId),
aQuery);
}
public List<VDSGroup> filterByArchitecture(List<VDSGroup> clusters, ArchitectureType targetArchitecture) {
List<VDSGroup> filteredClusters = new ArrayList<VDSGroup>();
for (VDSGroup cluster : clusters) {
if (cluster.getArchitecture().equals(targetArchitecture)) {
filteredClusters.add(cluster);
}
}
return filteredClusters;
}
public List<VDSGroup> filterClustersWithoutArchitecture(List<VDSGroup> clusters) {
List<VDSGroup> filteredClusters = new ArrayList<VDSGroup>();
for (VDSGroup cluster : clusters) {
if (cluster.getArchitecture() != ArchitectureType.undefined) {
filteredClusters.add(cluster);
}
}
return filteredClusters;
}
public void getClusterByServiceList(AsyncQuery aQuery, Guid dataCenterId,
final boolean supportsVirtService, final boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source == null) {
return new ArrayList<VDSGroup>();
}
final ArrayList<VDSGroup> list = (ArrayList<VDSGroup>) source;
return getClusterByServiceList(list, supportsVirtService, supportsGlusterService);
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVdsGroupsByStoragePoolId,
new IdQueryParameters(dataCenterId),
aQuery);
}
public void isSoundcardEnabled(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source != null) {
return !((List<?>) source).isEmpty();
}
return false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetSoundDevices, new IdQueryParameters(vmId), aQuery);
}
public void isVirtioScsiEnabledForVm(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source != null) {
return !((List<?>) source).isEmpty();
}
return false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVirtioScsiControllers, new IdQueryParameters(vmId), aQuery);
}
public void getClusterListByService(AsyncQuery aQuery, final boolean supportsVirtService,
final boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDSGroup> list =
getClusterByServiceList((ArrayList<VDSGroup>) source,
supportsVirtService,
supportsGlusterService);
Collections.sort(list, new NameableComparator());
return list;
}
return new ArrayList<VDSGroup>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllVdsGroups, new VdcQueryParametersBase(), aQuery);
}
public void getClusterList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDSGroup> list = (ArrayList<VDSGroup>) source;
Collections.sort(list, new NameableComparator());
return list;
}
return new ArrayList<VDSGroup>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllVdsGroups, new VdcQueryParametersBase(), aQuery);
}
public void getTemplateDiskList(AsyncQuery aQuery, Guid templateId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<DiskImage>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplatesDisks, new IdQueryParameters(templateId), aQuery);
}
/**
* Round the priority to the closest value from n (3 for now) values
*
* i.e.: if priority entered is 30 and the predefined values are 1,50,100
*
* then the return value will be 50 (closest to 50).
*
* @param priority
* - the current priority of the vm
* @param maxPriority
* - the max priority
* @return the rounded priority
*/
public int getRoundedPriority(int priority, int maxPriority) {
int medium = maxPriority / 2;
int[] levels = new int[] { 1, medium, maxPriority };
for (int i = 0; i < levels.length; i++)
{
int lengthToLess = levels[i] - priority;
int lengthToMore = levels[i + 1] - priority;
if (lengthToMore < 0)
{
continue;
}
return Math.abs(lengthToLess) < lengthToMore ? levels[i] : levels[i + 1];
}
return 0;
}
public void getTemplateListByDataCenter(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new TemplateConverter();
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplatesByStoragePoolId,
new IdQueryParameters(dataCenterId),
aQuery);
}
public void getTemplateListByStorage(AsyncQuery aQuery, Guid storageId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<VmTemplate> list = new ArrayList<VmTemplate>();
if (source != null)
{
for (VmTemplate template : (ArrayList<VmTemplate>) source)
{
if (template.getStatus() == VmTemplateStatus.OK)
{
list.add(template);
}
}
Collections.sort(list, new NameableComparator());
}
return list;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplatesFromStorageDomain,
new IdQueryParameters(storageId),
aQuery);
}
public ArrayList<VmTemplate> filterTemplatesByArchitecture(List<VmTemplate> list,
ArchitectureType architecture) {
ArrayList<VmTemplate> filteredList = new ArrayList<VmTemplate>();
for (VmTemplate template : list) {
if (template.getId().equals(Guid.Empty) ||
template.getClusterArch().equals(architecture)) {
filteredList.add(template);
}
}
return filteredList;
}
public void getNumOfMonitorList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<Integer> nums = new ArrayList<Integer>();
if (source != null)
{
Iterable numEnumerable = (Iterable) source;
Iterator numIterator = numEnumerable.iterator();
while (numIterator.hasNext())
{
nums.add(Integer.parseInt(numIterator.next().toString()));
}
}
return nums;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.ValidNumOfMonitors,
getDefaultConfigurationVersion()),
aQuery);
}
public void getStorageDomainList(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<StorageDomain>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByStoragePoolId,
new IdQueryParameters(dataCenterId),
aQuery);
}
public void getMaxVmPriority(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return 100;
}
return source;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.VmPriorityMaxValue,
getDefaultConfigurationVersion()),
aQuery);
}
public void getHostById(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(id), aQuery);
}
public void getHostListByCluster(AsyncQuery aQuery, String clusterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDS> list = Linq.<VDS> cast((ArrayList<IVdcQueryable>) source);
return list;
}
return new ArrayList<VDS>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search, new SearchParameters("Host: cluster = " + clusterName + " sortby name", //$NON-NLS-1$ //$NON-NLS-2$
SearchType.VDS), aQuery);
}
public void getHostListByDataCenter(AsyncQuery aQuery, Guid spId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDS> list = Linq.<VDS> cast((ArrayList<IVdcQueryable>) source);
return list;
}
return new ArrayList<VDS>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllVdsByStoragePool, new IdQueryParameters(spId), aQuery);
}
public void getVmDiskList(AsyncQuery aQuery, Guid vmId, boolean isRefresh) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
return source;
}
return new ArrayList<DiskImage>();
}
};
IdQueryParameters params = new IdQueryParameters(vmId);
params.setRefresh(isRefresh);
Frontend.getInstance().runQuery(VdcQueryType.GetAllDisksByVmId, params, aQuery);
}
public HashMap<Integer, String> getOsUniqueOsNames() {
return uniqueOsNames;
}
public void getAAAProfilesList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<String>((ArrayList<String>) source)
: new ArrayList<String>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAAAProfileList, new VdcQueryParametersBase(), aQuery);
}
public void getRoleList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Role>) source : new ArrayList<Role>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllRoles, new MultilevelAdministrationsQueriesParameters(), aQuery);
}
public void getStorageDomainById(AsyncQuery aQuery, Guid storageDomainId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (StorageDomain) source : null;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainById,
new IdQueryParameters(storageDomainId),
aQuery);
}
public VolumeFormat getDiskVolumeFormat(VolumeType volumeType, StorageType storageType) {
if (storageType.isFileDomain()) {
return VolumeFormat.RAW;
} else if (storageType.isBlockDomain()) {
switch (volumeType) {
case Sparse:
return VolumeFormat.COW;
case Preallocated:
return VolumeFormat.RAW;
default:
return VolumeFormat.Unassigned;
}
} else {
return VolumeFormat.Unassigned;
}
}
public void getClusterNetworkList(AsyncQuery aQuery, Guid clusterId) {
// do not replace a converter = just add if none provided
if (aQuery.converterCallback == null) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<Network>();
}
return source;
}
};
}
Frontend.getInstance().runQuery(VdcQueryType.GetAllNetworksByClusterId, new IdQueryParameters(clusterId), aQuery);
}
public void getAllNetworkQos(Guid dcId, AsyncQuery query) {
query.converterCallback = new IAsyncConverter<List<NetworkQoS>>() {
@Override
public List<NetworkQoS> Convert(Object returnValue, AsyncQuery asyncQuery) {
List<NetworkQoS> qosList = returnValue == null ? new ArrayList<NetworkQoS>() : (List<NetworkQoS>) returnValue;
qosList.add(0, NetworkQoSModel.EMPTY_QOS);
return qosList;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllNetworkQosByStoragePoolId, new IdQueryParameters(dcId), query);
}
public void getDataCenterById(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetStoragePoolById,
new IdQueryParameters(dataCenterId).withoutRefresh(), aQuery);
}
public void getNetworkLabelsByDataCenterId(Guid dataCenterId, AsyncQuery query) {
query.converterCallback = new IAsyncConverter<SortedSet<String>>() {
@Override
public SortedSet<String> Convert(Object returnValue, AsyncQuery asyncQuery) {
SortedSet<String> sortedSet = new TreeSet<String>(new LexoNumericComparator());
sortedSet.addAll((Collection<String>) returnValue);
return sortedSet;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetNetworkLabelsByDataCenterId,
new IdQueryParameters(dataCenterId),
query);
}
public void getWatchdogByVmId(AsyncQuery aQuery, Guid vmId) {
Frontend.getInstance().runQuery(VdcQueryType.GetWatchdog, new IdQueryParameters(vmId), aQuery);
}
public void getTemplateById(AsyncQuery aQuery, Guid templateId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplate, new GetVmTemplateParameters(templateId), aQuery);
}
public void countAllTemplates(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplateCount, new VdcQueryParametersBase(), aQuery);
}
public void getHostList(AsyncQuery aQuery) {
getHostListByStatus(aQuery, null);
}
public void getHostListByStatus(AsyncQuery aQuery, VDSStatus status) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDS> list = Linq.<VDS> cast((Iterable) source);
return list;
}
return new ArrayList<VDS>();
}
};
SearchParameters searchParameters =
new SearchParameters("Host: " + (status == null ? "" : ("status=" + status.name())), SearchType.VDS); //$NON-NLS-1$ //$NON-NLS-2$
searchParameters.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParameters, aQuery);
}
public void getHostsForStorageOperation(AsyncQuery aQuery, Guid storagePoolId, boolean localFsOnly) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source != null) {
return source;
}
return new ArrayList<VDS>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetHostsForStorageOperation,
new GetHostsForStorageOperationParameters(storagePoolId, localFsOnly),
aQuery);
}
public void getVolumeList(AsyncQuery aQuery, String clusterName) {
if ((ApplicationModeHelper.getUiMode().getValue() & ApplicationMode.GlusterOnly.getValue()) == 0) {
aQuery.asyncCallback.onSuccess(aQuery.model, new ArrayList<GlusterVolumeEntity>());
return;
}
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<GlusterVolumeEntity> list =
(ArrayList<GlusterVolumeEntity>) source;
return list;
}
return new ArrayList<GlusterVolumeEntity>();
}
};
SearchParameters searchParameters;
searchParameters =
clusterName == null ? new SearchParameters("Volumes:", SearchType.GlusterVolume) //$NON-NLS-1$
: new SearchParameters("Volumes: cluster.name=" + clusterName, SearchType.GlusterVolume); //$NON-NLS-1$
searchParameters.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParameters, aQuery);
}
public void getGlusterVolumeOptionInfoList(AsyncQuery aQuery, Guid clusterId) {
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeOptionsInfo, new GlusterParameters(clusterId), aQuery);
}
public void getHostFingerprint(AsyncQuery aQuery, String hostAddress) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetServerSSHKeyFingerprint, new ServerParameters(hostAddress), aQuery);
}
public void getHostPublicKey(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetServerSSHPublicKey, new VdcQueryParametersBase(), aQuery);
}
public void getGlusterHosts(AsyncQuery aQuery, String hostAddress, String rootPassword, String fingerprint) {
GlusterServersQueryParameters parameters = new GlusterServersQueryParameters(hostAddress, rootPassword);
parameters.setFingerprint(fingerprint);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterServersForImport,
parameters,
aQuery);
}
public void getClusterGlusterServices(AsyncQuery aQuery, Guid clusterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
// Passing empty values for Volume and Brick to get the services of all the volumes/hosts in the cluster
GlusterVolumeAdvancedDetailsParameters parameters =
new GlusterVolumeAdvancedDetailsParameters(clusterId, null, null, false); //$NON-NLS-1$ //$NON-NLS-2$
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeAdvancedDetails,
parameters,
aQuery);
}
public void getGlusterVolumeBrickDetails(AsyncQuery aQuery, Guid clusterId, Guid volumeId, Guid brickId) {
GlusterVolumeAdvancedDetailsParameters parameters =
new GlusterVolumeAdvancedDetailsParameters(clusterId, volumeId, brickId, true);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeAdvancedDetails,
parameters,
aQuery);
}
public void getGlusterHostsNewlyAdded(AsyncQuery aQuery, Guid clusterId, boolean isFingerprintRequired) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAddedGlusterServers,
new AddedGlusterServersParameters(clusterId, isFingerprintRequired),
aQuery);
}
public void isAnyHostUpInCluster(AsyncQuery aQuery, String clusterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null && !((List<?>) source).isEmpty()) {
return true;
}
return false;
}
};
getUpHostListByCluster(aQuery, clusterName, 1);
}
public void getGlusterHooks(AsyncQuery aQuery, Guid clusterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : new ArrayList<GlusterHookEntity>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterHooks, new GlusterParameters(clusterId), aQuery);
}
public void getGlusterBricksForServer(AsyncQuery aQuery, Guid serverId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : new ArrayList<GlusterBrickEntity>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeBricksByServerId, new IdQueryParameters(serverId), aQuery);
}
public void getGlusterHook(AsyncQuery aQuery, Guid hookId, boolean includeServerHooks) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterHookById,
new GlusterHookQueryParameters(hookId, includeServerHooks),
aQuery);
}
public void getGlusterHookContent(AsyncQuery aQuery, Guid hookId, Guid serverId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? source : ""; //$NON-NLS-1$
}
};
GlusterHookContentQueryParameters parameters = new GlusterHookContentQueryParameters(hookId);
parameters.setGlusterServerId(serverId);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterHookContent, parameters, aQuery);
}
public void getGlusterSwiftServices(AsyncQuery aQuery, Guid serverId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : new ArrayList<GlusterServerService>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterServerServicesByServerId, new GlusterServiceQueryParameters(serverId,
ServiceType.GLUSTER_SWIFT), aQuery);
}
public void getClusterGlusterSwiftService(AsyncQuery aQuery, Guid clusterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source != null) {
List<GlusterClusterService> serviceList = (List<GlusterClusterService>) source;
if (!serviceList.isEmpty()) {
return serviceList.get(0);
}
return null;
}
else {
return source;
}
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterClusterServiceByClusterId,
new GlusterServiceQueryParameters(clusterId,
ServiceType.GLUSTER_SWIFT), aQuery);
}
public void getGlusterSwiftServerServices(AsyncQuery aQuery, Guid clusterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? source : new ArrayList<GlusterServerService>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterServerServicesByClusterId,
new GlusterServiceQueryParameters(clusterId,
ServiceType.GLUSTER_SWIFT), aQuery);
}
public void getGlusterRebalanceStatus(AsyncQuery aQuery, Guid clusterId, Guid volumeId) {
aQuery.setHandleFailure(true);
GlusterVolumeQueriesParameters parameters = new GlusterVolumeQueriesParameters(clusterId, volumeId);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeRebalanceStatus, parameters, aQuery);
}
public void getGlusterVolumeProfilingStatistics(AsyncQuery aQuery, Guid clusterId, Guid volumeId, boolean nfs) {
aQuery.setHandleFailure(true);
GlusterVolumeProfileParameters parameters = new GlusterVolumeProfileParameters(clusterId, volumeId, nfs);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeProfileInfo, parameters, aQuery);
}
public void getGlusterRemoveBricksStatus(AsyncQuery aQuery,
Guid clusterId,
Guid volumeId,
List<GlusterBrickEntity> bricks) {
aQuery.setHandleFailure(true);
GlusterVolumeRemoveBricksQueriesParameters parameters =
new GlusterVolumeRemoveBricksQueriesParameters(clusterId, volumeId, bricks);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeRemoveBricksStatus, parameters, aQuery);
}
public void getRpmVersion(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.ProductRPMVersion);
tempVar.setVersion(getDefaultConfigurationVersion());
getConfigFromCache(tempVar, aQuery);
}
public void getUserMessageOfTheDayViaPublic(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
Frontend.getInstance().runPublicQuery(VdcQueryType.GetConfigurationValue,
new GetConfigurationValueParameters(ConfigurationValues.UserMessageOfTheDay,
getDefaultConfigurationVersion()),
aQuery);
}
public void getSearchResultsLimit(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 100;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.SearchResultsLimit,
getDefaultConfigurationVersion()),
aQuery);
}
public Map<Version, Map<String, String>> getCustomPropertiesList() {
return customPropertiesList;
}
public void getPermissionsByAdElementId(AsyncQuery aQuery, Guid userId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Permissions>) source
: new ArrayList<Permissions>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetPermissionsByAdElementId,
new IdQueryParameters(userId),
aQuery);
}
public void getRoleActionGroupsByRoleId(AsyncQuery aQuery, Guid roleId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<ActionGroup>) source
: new ArrayList<ActionGroup>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetRoleActionGroupsByRoleId,
new IdQueryParameters(roleId),
aQuery);
}
public void isTemplateNameUnique(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? !((Boolean) source).booleanValue() : false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.IsVmTemlateWithSameNameExist,
new NameQueryParameters(name),
aQuery);
}
public void isVmNameUnique(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? !((Boolean) source).booleanValue() : false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.IsVmWithSameNameExist, new NameQueryParameters(name), aQuery);
}
public void getDataCentersWithPermittedActionOnClusters(AsyncQuery aQuery, ActionGroup actionGroup,
final boolean supportsVirtService, final boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<StoragePool>();
}
return source;
}
};
GetDataCentersWithPermittedActionOnClustersParameters getDataCentersWithPermittedActionOnClustersParameters =
new GetDataCentersWithPermittedActionOnClustersParameters();
getDataCentersWithPermittedActionOnClustersParameters.setActionGroup(actionGroup);
getDataCentersWithPermittedActionOnClustersParameters.setSupportsVirtService(supportsVirtService);
getDataCentersWithPermittedActionOnClustersParameters.setSupportsGlusterService(supportsGlusterService);
Frontend.getInstance().runQuery(VdcQueryType.GetDataCentersWithPermittedActionOnClusters,
getDataCentersWithPermittedActionOnClustersParameters,
aQuery);
}
public void getClustersWithPermittedAction(AsyncQuery aQuery, ActionGroup actionGroup,
final boolean supportsVirtService, final boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDSGroup> list = (ArrayList<VDSGroup>) source;
return getClusterByServiceList(list, supportsVirtService, supportsGlusterService);
}
return new ArrayList<VDSGroup>();
}
};
GetEntitiesWithPermittedActionParameters getEntitiesWithPermittedActionParameters =
new GetEntitiesWithPermittedActionParameters();
getEntitiesWithPermittedActionParameters.setActionGroup(actionGroup);
Frontend.getInstance().runQuery(VdcQueryType.GetClustersWithPermittedAction, getEntitiesWithPermittedActionParameters, aQuery);
}
public void getAllVmTemplates(AsyncQuery aQuery, final boolean refresh) {
aQuery.converterCallback = new TemplateConverter();
VdcQueryParametersBase params = new VdcQueryParametersBase();
params.setRefresh(refresh);
Frontend.getInstance().runQuery(VdcQueryType.GetAllVmTemplates, params, aQuery);
}
public void isUSBEnabledByDefault(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Boolean) source).booleanValue() : false;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.EnableUSBAsDefault,
getDefaultConfigurationVersion()),
aQuery);
}
public void getStorageConnectionById(AsyncQuery aQuery, String id, boolean isRefresh) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (StorageServerConnections) source : null;
}
};
StorageServerConnectionQueryParametersBase params = new StorageServerConnectionQueryParametersBase(id);
params.setRefresh(isRefresh);
Frontend.getInstance().runQuery(VdcQueryType.GetStorageServerConnectionById, params, aQuery);
}
public void getDataCentersByStorageDomain(AsyncQuery aQuery, Guid storageDomainId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<StoragePool>) source : null;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetStoragePoolsByStorageDomainId,
new IdQueryParameters(storageDomainId),
aQuery);
}
public void getDataCenterVersions(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<Version>();
}
else
{
ArrayList<Version> list = (ArrayList<Version>) source;
Collections.sort(list);
return list;
}
}
};
IdQueryParameters tempVar = new IdQueryParameters(dataCenterId);
Frontend.getInstance().runQuery(VdcQueryType.GetAvailableClusterVersionsByStoragePool, tempVar, aQuery);
}
public void getDataCenterMaxNameLength(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.StoragePoolNameSizeLimit,
getDefaultConfigurationVersion()),
aQuery);
}
public void getClusterServerMemoryOverCommit(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 0;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.MaxVdsMemOverCommitForServers,
getDefaultConfigurationVersion()),
aQuery);
}
public void getClusterDesktopMemoryOverCommit(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 0;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.MaxVdsMemOverCommit,
getDefaultConfigurationVersion()),
aQuery);
}
public void getAllowClusterWithVirtGlusterEnabled(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : Boolean.TRUE;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.AllowClusterWithVirtGlusterEnabled,
getDefaultConfigurationVersion()),
aQuery);
}
public void getCPUList(AsyncQuery aQuery, Version version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<ServerCpu>) source : new ArrayList<ServerCpu>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllServerCpuList, new GetAllServerCpuListParameters(version), aQuery);
}
public void getPmTypeList(AsyncQuery aQuery, Version version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<String> list = new ArrayList<String>();
if (source != null)
{
String[] array = ((String) source).split("[,]", -1); //$NON-NLS-1$
for (String item : array)
{
list.add(item);
}
}
return list;
}
};
GetConfigurationValueParameters param = new GetConfigurationValueParameters(ConfigurationValues.VdsFenceType);
param.setVersion(version != null ? version.toString() : getDefaultConfigurationVersion());
Frontend.getInstance().runQuery(VdcQueryType.GetFenceConfigurationValue, param, aQuery);
}
public void getPmOptions(AsyncQuery aQuery, String pmType, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
String pmtype = (String) _asyncQuery.data[0];
HashMap<String, ArrayList<String>> cachedPmMap =
new HashMap<String, ArrayList<String>>();
HashMap<String, HashMap<String, Object>> dict =
(HashMap<String, HashMap<String, Object>>) source;
for (Map.Entry<String, HashMap<String, Object>> pair : dict.entrySet())
{
ArrayList<String> list = new ArrayList<String>();
for (Map.Entry<String, Object> p : pair.getValue().entrySet())
{
list.add(p.getKey());
}
cachedPmMap.put(pair.getKey(), list);
}
return cachedPmMap.get(pmtype);
}
};
aQuery.setData(new Object[] { pmType });
Frontend.getInstance().runQuery(VdcQueryType.GetAgentFenceOptions, new GetAgentFenceOptionsQueryParameters(version), aQuery);
}
public void getNetworkList(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Network>) source : new ArrayList<Network>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllNetworks, new IdQueryParameters(dataCenterId), aQuery);
}
public void getISOStorageDomainList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<StorageDomain> allStorageDomains =
(ArrayList<StorageDomain>) source;
ArrayList<StorageDomain> isoStorageDomains = new ArrayList<StorageDomain>();
for (StorageDomain storageDomain : allStorageDomains)
{
if (storageDomain.getStorageDomainType() == StorageDomainType.ISO)
{
isoStorageDomains.add(storageDomain);
}
}
return isoStorageDomains;
}
return new ArrayList<StorageDomain>();
}
};
SearchParameters searchParams = new SearchParameters("Storage:", SearchType.StorageDomain); //$NON-NLS-1$
searchParams.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParams, aQuery);
}
public void getStorageDomainList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<StorageDomain>) source
: new ArrayList<StorageDomain>();
}
};
SearchParameters searchParams = new SearchParameters("Storage:", SearchType.StorageDomain); //$NON-NLS-1$
searchParams.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParams, aQuery);
}
public void getLocalStorageHost(AsyncQuery aQuery, String dataCenterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
for (IVdcQueryable item : (ArrayList<IVdcQueryable>) source)
{
return item;
}
}
return null;
}
};
SearchParameters sp = new SearchParameters("hosts: datacenter=" + dataCenterName, SearchType.VDS); //$NON-NLS-1$
Frontend.getInstance().runQuery(VdcQueryType.Search, sp, aQuery);
}
public void getStorageDomainsByConnection(AsyncQuery aQuery, Guid storagePoolId, String connectionPath) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<StorageDomain>) source : null;
}
};
GetStorageDomainsByConnectionParameters param = new GetStorageDomainsByConnectionParameters();
param.setConnection(connectionPath);
if (storagePoolId != null) {
param.setStoragePoolId(storagePoolId);
}
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByConnection, param, aQuery);
}
public void getExistingStorageDomainList(AsyncQuery aQuery,
Guid hostId,
StorageDomainType domainType,
StorageType storageType,
String path) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<StorageDomain>) source : null;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetExistingStorageDomainList, new GetExistingStorageDomainListParameters(hostId,
storageType,
domainType,
path), aQuery);
}
public void getStorageDomainMaxNameLength(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.StorageDomainNameSizeLimit,
getDefaultConfigurationVersion()),
aQuery);
}
public void isStorageDomainNameUnique(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<StorageDomain> storageDomains = (ArrayList<StorageDomain>) source;
return storageDomains.isEmpty();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search, new SearchParameters("Storage: name=" + name, //$NON-NLS-1$
SearchType.StorageDomain), aQuery);
}
public void getNetworkConnectivityCheckTimeoutInSeconds(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 120;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.NetworkConnectivityCheckTimeoutInSeconds,
getDefaultConfigurationVersion()),
aQuery);
}
public void getMaxSpmPriority(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? ((Integer) source).intValue() : 0;
}
};
// GetConfigFromCache(
// new GetConfigurationValueParameters(ConfigurationValues.HighUtilizationForPowerSave,
// getDefaultConfigurationVersion()),
// aQuery);
aQuery.asyncCallback.onSuccess(aQuery.getModel(), 10);
}
public void getDefaultSpmPriority(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? ((Integer) source).intValue() : 0;
}
};
// GetConfigFromCache(
// new GetConfigurationValueParameters(ConfigurationValues.HighUtilizationForPowerSave,
// getDefaultConfigurationVersion()),
// aQuery);
aQuery.asyncCallback.onSuccess(aQuery.getModel(), 5);
}
public void getDefaultPmProxyPreferences(AsyncQuery query) {
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.FenceProxyDefaultPreferences,
getDefaultConfigurationVersion()),
query);
}
public void getRootTag(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
Tags tag = (Tags) source;
Tags root =
new Tags(tag.getdescription(),
tag.getparent_id(),
tag.getIsReadonly(),
tag.gettag_id(),
tag.gettag_name());
if (tag.getChildren() != null)
{
fillTagsRecursive(root, tag.getChildren());
}
return root;
}
return new Tags();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetRootTag, new VdcQueryParametersBase(), aQuery);
}
private void setAttachedTagsConverter(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<Tags> ret = new ArrayList<Tags>();
for (Tags tags : (ArrayList<Tags>) source)
{
if (tags.gettype() == TagsType.GeneralTag)
{
ret.add(tags);
}
}
return ret;
}
return new Tags();
}
};
}
public void getAttachedTagsToVm(AsyncQuery aQuery, Guid id) {
setAttachedTagsConverter(aQuery);
Frontend.getInstance().runQuery(VdcQueryType.GetTagsByVmId, new GetTagsByVmIdParameters(id.toString()), aQuery);
}
public void getAttachedTagsToUser(AsyncQuery aQuery, Guid id) {
setAttachedTagsConverter(aQuery);
Frontend.getInstance().runQuery(VdcQueryType.GetTagsByUserId, new GetTagsByUserIdParameters(id.toString()), aQuery);
}
public void getAttachedTagsToUserGroup(AsyncQuery aQuery, Guid id) {
setAttachedTagsConverter(aQuery);
Frontend.getInstance().runQuery(VdcQueryType.GetTagsByUserGroupId, new GetTagsByUserGroupIdParameters(id.toString()), aQuery);
}
public void getAttachedTagsToHost(AsyncQuery aQuery, Guid id) {
setAttachedTagsConverter(aQuery);
Frontend.getInstance().runQuery(VdcQueryType.GetTagsByVdsId, new GetTagsByVdsIdParameters(id.toString()), aQuery);
}
public void getoVirtISOsList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<RpmVersion>((ArrayList<RpmVersion>) source)
: new ArrayList<RpmVersion>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetoVirtISOs, new VdsIdParametersBase(id), aQuery);
}
public void getLunsByVgId(AsyncQuery aQuery, String vgId, Guid vdsId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<LUNs>) source : new ArrayList<LUNs>();
}
};
GetLunsByVgIdParameters params = new GetLunsByVgIdParameters(vgId, vdsId);
Frontend.getInstance().runQuery(VdcQueryType.GetLunsByVgId, params, aQuery);
}
public void getAllTemplatesFromExportDomain(AsyncQuery aQuery, Guid storagePoolId, Guid storageDomainId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : new HashMap<VmTemplate, ArrayList<DiskImage>>();
}
};
GetAllFromExportDomainQueryParameters getAllFromExportDomainQueryParamenters =
new GetAllFromExportDomainQueryParameters(storagePoolId, storageDomainId);
Frontend.getInstance().runQuery(VdcQueryType.GetTemplatesFromExportDomain, getAllFromExportDomainQueryParamenters, aQuery);
}
public void getUpHostListByCluster(AsyncQuery aQuery, String clusterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDS> list = Linq.<VDS> cast((ArrayList<IVdcQueryable>) source);
return list;
}
return new ArrayList<VDS>();
}
};
getUpHostListByCluster(aQuery, clusterName, null);
}
public void getUpHostListByCluster(AsyncQuery aQuery, String clusterName, Integer maxCount) {
SearchParameters searchParameters =
new SearchParameters("Host: cluster = " + clusterName + " and status = up", SearchType.VDS); //$NON-NLS-1$ //$NON-NLS-2$
if (maxCount != null) {
searchParameters.setMaxCount(maxCount);
}
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParameters, aQuery);
}
public void getVmNicList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<VmNetworkInterface>((ArrayList<VmNetworkInterface>) source)
: new ArrayList<VmNetworkInterface>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmInterfacesByVmId, new IdQueryParameters(id), aQuery);
}
public void getTemplateNicList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<VmNetworkInterface>((ArrayList<VmNetworkInterface>) source)
: new ArrayList<VmNetworkInterface>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetTemplateInterfacesByTemplateId, new IdQueryParameters(id), aQuery);
}
public void getVmSnapshotList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Snapshot>) source : new ArrayList<Snapshot>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllVmSnapshotsByVmId, new IdQueryParameters(id), aQuery);
}
public void getVmsRunningOnOrMigratingToVds(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source == null) {
return new ArrayList<VM>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmsRunningOnOrMigratingToVds,
new IdQueryParameters(id),
aQuery);
}
public void getVmDiskList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<Disk> list = new ArrayList<Disk>();
if (source != null)
{
Iterable listEnumerable = (Iterable) source;
Iterator listIterator = listEnumerable.iterator();
while (listIterator.hasNext())
{
list.add((Disk) listIterator.next());
}
}
return list;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllDisksByVmId, new IdQueryParameters(id), aQuery);
}
public void getVmList(AsyncQuery aQuery, String poolName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<VM> vms = Linq.<VM> cast((ArrayList<IVdcQueryable>) source);
return vms;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search, new SearchParameters("Vms: pool=" + poolName, SearchType.VM), aQuery); //$NON-NLS-1$
}
public void getVmListByClusterName(AsyncQuery aQuery, String clusterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<VM> vms = Linq.<VM> cast((ArrayList<IVdcQueryable>) source);
return vms;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters("Vms: cluster=" + clusterName, SearchType.VM), aQuery); //$NON-NLS-1$
}
public void getDiskList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<DiskImage>) source : new ArrayList<DiskImage>();
}
};
SearchParameters searchParams = new SearchParameters("Disks:", SearchType.Disk); //$NON-NLS-1$
searchParams.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParams, aQuery);
}
public void getNextAvailableDiskAliasNameByVMId(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetNextAvailableDiskAliasNameByVMId,
new IdQueryParameters(vmId),
aQuery);
}
public void isPoolNameUnique(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
return !(Boolean) source;
}
return false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.IsVmPoolWithSameNameExists,
new NameQueryParameters(name),
aQuery);
}
public void getVmConfigurationBySnapshot(AsyncQuery aQuery, Guid snapshotSourceId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (VM) source : null;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmConfigurationBySnapshot,
new IdQueryParameters(snapshotSourceId).withoutRefresh(),
aQuery);
}
public void getAllAttachableDisks(AsyncQuery aQuery, Guid storagePoolId, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Disk>) source : new ArrayList<Disk>();
}
};
GetAllAttachableDisks params = new GetAllAttachableDisks(storagePoolId);
params.setVmId(vmId);
Frontend.getInstance().runQuery(VdcQueryType.GetAllAttachableDisks, params, aQuery);
}
public void getPermittedStorageDomainsByStoragePoolId(AsyncQuery aQuery,
Guid dataCenterId,
ActionGroup actionGroup) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new java.util.ArrayList<StorageDomain>();
}
return source;
}
};
GetPermittedStorageDomainsByStoragePoolIdParameters params =
new GetPermittedStorageDomainsByStoragePoolIdParameters();
params.setStoragePoolId(dataCenterId);
params.setActionGroup(actionGroup);
Frontend.getInstance().runQuery(VdcQueryType.GetPermittedStorageDomainsByStoragePoolId, params, aQuery);
}
public void getAllDataCenterNetworks(AsyncQuery aQuery, Guid storagePoolId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Network>) source : new ArrayList<Network>();
}
};
IdQueryParameters params = new IdQueryParameters(storagePoolId);
Frontend.getInstance().runQuery(VdcQueryType.GetNetworksByDataCenterId, params, aQuery);
}
public void getStorageConnectionsByDataCenterIdAndStorageType(AsyncQuery aQuery,
Guid storagePoolId,
StorageType storageType) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
GetConnectionsByDataCenterAndStorageTypeParameters params = new GetConnectionsByDataCenterAndStorageTypeParameters(storagePoolId, storageType);
Frontend.getInstance().runQuery(VdcQueryType.GetConnectionsByDataCenterAndStorageType, params, aQuery);
}
public void getRedirectServletReportsPage(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.RedirectServletReportsPage,
getDefaultConfigurationVersion()),
aQuery);
}
private HashMap<VdcActionType, CommandVersionsInfo> cachedCommandsCompatibilityVersions;
public void isCommandCompatible(AsyncQuery aQuery, final VdcActionType vdcActionType,
final Version cluster, final Version dc) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
cachedCommandsCompatibilityVersions = (HashMap<VdcActionType, CommandVersionsInfo>) source;
return isCommandCompatible(vdcActionType, cluster, dc);
}
};
if (cachedCommandsCompatibilityVersions != null) {
aQuery.asyncCallback.onSuccess(aQuery.getModel(), isCommandCompatible(vdcActionType, cluster, dc));
} else {
Frontend.getInstance().runQuery(VdcQueryType.GetCommandsCompatibilityVersions,
new VdcQueryParametersBase().withoutRefresh(), aQuery);
}
}
private boolean isCommandCompatible(VdcActionType vdcActionType, Version cluster, Version dc) {
if (cachedCommandsCompatibilityVersions == null || cluster == null || dc == null) {
return false;
}
CommandVersionsInfo commandVersionsInfo = cachedCommandsCompatibilityVersions.get(vdcActionType);
if (commandVersionsInfo == null) {
return false;
}
Version clusterCompatibility = commandVersionsInfo.getClusterVersion();
Version dcCompatibility = commandVersionsInfo.getStoragePoolVersion();
return (clusterCompatibility.compareTo(cluster) <= 0)
&& (dcCompatibility.compareTo(dc) <= 0);
}
public CommandVersionsInfo getCommandVersionsInfo(VdcActionType vdcActionType) {
if (cachedCommandsCompatibilityVersions == null) {
return null;
}
return cachedCommandsCompatibilityVersions.get(vdcActionType);
}
/**
* Get the Management Network Name
*
* @param aQuery
* result callback
*/
public void getManagementNetworkName(AsyncQuery aQuery) {
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.ManagementNetwork,
getDefaultConfigurationVersion()),
aQuery);
}
/**
* Cache configuration values [raw (not converted) values from vdc_options table].
*/
private void cacheConfigValues(AsyncQuery aQuery) {
getDefaultConfigurationVersion();
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object returnValue, AsyncQuery _asyncQuery)
{
if (returnValue != null) {
cachedConfigValuesPreConvert.putAll((HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object>) returnValue);
}
return cachedConfigValuesPreConvert;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetConfigurationValues, new VdcQueryParametersBase(), aQuery);
}
/**
* Get configuration value from 'cachedConfigValuesPreConvert' (raw values from vdc_options table).
*
* @param version
*/
public Object getConfigValuePreConverted(ConfigurationValues configValue, String version) {
KeyValuePairCompat<ConfigurationValues, String> key =
new KeyValuePairCompat<ConfigurationValues, String>(configValue, version);
return cachedConfigValuesPreConvert.get(key);
}
/**
* Get configuration value from 'cachedConfigValuesPreConvert' (raw values from vdc_options table).
*/
public Object getConfigValuePreConverted(ConfigurationValues configValue) {
KeyValuePairCompat<ConfigurationValues, String> key =
new KeyValuePairCompat<ConfigurationValues, String>(configValue, getDefaultConfigurationVersion());
return cachedConfigValuesPreConvert.get(key);
}
/**
* Get configuration value from using a specified converter.
*/
public Object getConfigValue(ConfigurationValues configValue, String version, IAsyncConverter converter) {
if (converter == null) {
return null;
}
KeyValuePairCompat<ConfigurationValues, String> key =
new KeyValuePairCompat<ConfigurationValues, String>(configValue, version);
return converter.Convert(cachedConfigValuesPreConvert.get(key), null);
}
/**
* method to get an item from config while caching it (config is not supposed to change during a session)
*
* @param aQuery
* an async query
* @param parameters
* a converter for the async query
*/
public void getConfigFromCache(GetConfigurationValueParameters parameters, AsyncQuery aQuery) {
// cache key
final KeyValuePairCompat<ConfigurationValues, String> config_key =
new KeyValuePairCompat<ConfigurationValues, String>(parameters.getConfigValue(),
parameters.getVersion());
Object returnValue = null;
if (cachedConfigValues.containsKey(config_key)) {
// cache hit
returnValue = cachedConfigValues.get(config_key);
}
// cache miss: convert configuration value using query's converter
// and call asyncCallback's onSuccess
else if (cachedConfigValuesPreConvert.containsKey(config_key)) {
returnValue = cachedConfigValuesPreConvert.get(config_key);
// run converter
if (aQuery.converterCallback != null) {
returnValue = aQuery.converterCallback.Convert(returnValue, aQuery);
}
if (returnValue != null) {
cachedConfigValues.put(config_key, returnValue);
}
}
aQuery.asyncCallback.onSuccess(aQuery.getModel(), returnValue);
}
/**
* method to get an item from config while caching it (config is not supposed to change during a session)
*
* @param configValue
* the config value to query
* @param version
* the compatibility version to query
* @param aQuery
* an async query
*/
public void getConfigFromCache(ConfigurationValues configValue, String version, AsyncQuery aQuery) {
GetConfigurationValueParameters parameters = new GetConfigurationValueParameters(configValue, version);
getConfigFromCache(parameters, aQuery);
}
public ArrayList<QuotaEnforcementTypeEnum> getQuotaEnforcmentTypes() {
return new ArrayList<QuotaEnforcementTypeEnum>(Arrays.asList(new QuotaEnforcementTypeEnum[] {
QuotaEnforcementTypeEnum.DISABLED,
QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT,
QuotaEnforcementTypeEnum.HARD_ENFORCEMENT }));
}
public void clearCache() {
cachedConfigValues.clear();
}
private static class TemplateConverter implements IAsyncConverter {
@Override
public Object Convert(Object source, AsyncQuery asyncQuery) {
List<VmTemplate> list = new ArrayList<VmTemplate>();
if (source != null) {
VmTemplate blankTemplate = null;
for (VmTemplate template : (List<VmTemplate>) source) {
if (template.getId().equals(Guid.Empty)) {
blankTemplate = template;
} else if (template.getStatus() == VmTemplateStatus.OK) {
list.add(template);
}
}
Collections.sort(list, new NameableComparator());
if (blankTemplate != null) {
list.add(0, blankTemplate);
}
}
return list;
}
}
public void getInterfaceOptionsForEditNetwork(final AsyncQuery asyncQuery,
final ArrayList<VdsNetworkInterface> interfaceList,
final VdsNetworkInterface originalInterface,
Network networkToEdit,
final Guid vdsID,
final StringBuilder defaultInterfaceName)
{
final ArrayList<VdsNetworkInterface> ifacesOptions = new ArrayList<VdsNetworkInterface>();
for (VdsNetworkInterface i : interfaceList)
{
if (StringHelper.isNullOrEmpty(i.getNetworkName()) && StringHelper.isNullOrEmpty(i.getBondName()))
{
ifacesOptions.add(i);
}
}
if (originalInterface.getVlanId() == null) // no vlan:
{
// Filter out the Interfaces that have child vlan Interfaces
getAllChildVlanInterfaces(vdsID, ifacesOptions, new IFrontendMultipleQueryAsyncCallback() {
@Override
public void executed(FrontendMultipleQueryAsyncResult result) {
ArrayList<VdsNetworkInterface> ifacesOptionsTemp = new ArrayList<VdsNetworkInterface>();
List<VdcQueryReturnValue> returnValueList = result.getReturnValues();
for (int i = 0; i < returnValueList.size(); i++)
{
VdcQueryReturnValue returnValue = returnValueList.get(i);
if (returnValue != null && returnValue.getSucceeded() && returnValue.getReturnValue() != null)
{
ArrayList<VdsNetworkInterface> childVlanInterfaces =
returnValue.getReturnValue();
if (childVlanInterfaces.size() == 0)
{
ifacesOptionsTemp.add(ifacesOptions.get(i));
}
}
}
ifacesOptions.clear();
ifacesOptions.addAll(ifacesOptionsTemp);
if (originalInterface.getBonded() != null && originalInterface.getBonded())
{
// eth0 -- \
// |---> bond0 -> <networkToEdit>
// eth1 -- /
// ---------------------------------------
// - originalInterface: 'bond0'
// --> We want to add 'eth0' and and 'eth1' as optional Interfaces
// (note that choosing one of them will break the bond):
for (VdsNetworkInterface i : interfaceList)
{
if (ObjectUtils.objectsEqual(i.getBondName(), originalInterface.getName()))
{
ifacesOptions.add(i);
}
}
}
// add the original interface as an option and set it as the default option:
ifacesOptions.add(originalInterface);
defaultInterfaceName.append(originalInterface.getName());
asyncQuery.asyncCallback.onSuccess(asyncQuery.model, ifacesOptions);
}
});
}
else // vlan:
{
getVlanParentInterface(vdsID, originalInterface, new AsyncQuery(asyncQuery, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
final VdsNetworkInterface vlanParent = (VdsNetworkInterface) returnValue;
if (vlanParent != null && vlanParent.getBonded() != null && vlanParent.getBonded()) {
interfaceHasSiblingVlanInterfaces(vdsID, originalInterface, new AsyncQuery(asyncQuery,
new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
Boolean interfaceHasSiblingVlanInterfaces = (Boolean) returnValue;
if (!interfaceHasSiblingVlanInterfaces) {
// eth0 -- \
// |--- bond0 ---> bond0.3 -> <networkToEdit>
// eth1 -- /
// ---------------------------------------------------
// - originalInterface: 'bond0.3'
// - vlanParent: 'bond0'
// - 'bond0.3' has no vlan siblings
// --> We want to add 'eth0' and and 'eth1' as optional Interfaces.
// (note that choosing one of them will break the bond):
// ifacesOptions.AddRange(interfaceList.Where(a => a.bond_name ==
// vlanParent.name).ToList());
for (VdsNetworkInterface i : interfaceList) {
if (ObjectUtils.objectsEqual(i.getBondName(), vlanParent.getName())) {
ifacesOptions.add(i);
}
}
}
// the vlanParent should already be in ifacesOptions
// (since it has no network_name or bond_name).
defaultInterfaceName.append(vlanParent.getName());
asyncQuery.asyncCallback.onSuccess(asyncQuery.model, ifacesOptions);
}
}));
} else {
// the vlanParent should already be in ifacesOptions
// (since it has no network_name or bond_name).
if (vlanParent != null)
defaultInterfaceName.append(vlanParent.getName());
asyncQuery.asyncCallback.onSuccess(asyncQuery.model, ifacesOptions);
}
}
}));
}
}
private void getVlanParentInterface(Guid vdsID, VdsNetworkInterface iface, AsyncQuery aQuery)
{
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVlanParent, new InterfaceAndIdQueryParameters(vdsID,
iface), aQuery);
}
private void interfaceHasSiblingVlanInterfaces(Guid vdsID, VdsNetworkInterface iface, AsyncQuery aQuery)
{
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<VdsNetworkInterface> siblingVlanInterfaces = (ArrayList<VdsNetworkInterface>) source;
return !siblingVlanInterfaces.isEmpty();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllSiblingVlanInterfaces,
new InterfaceAndIdQueryParameters(vdsID, iface), aQuery);
}
public void getExternalProviderHostList(AsyncQuery aQuery,
Guid providerId,
boolean filterOutExistingHosts,
String searchFilter) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<VDS>();
}
return source;
}
};
GetHostListFromExternalProviderParameters params = new GetHostListFromExternalProviderParameters();
params.setFilterOutExistingHosts(filterOutExistingHosts);
params.setProviderId(providerId);
params.setSearchFilter(searchFilter);
Frontend.getInstance().runQuery(VdcQueryType.GetHostListFromExternalProvider,
params,
aQuery);
}
public void getExternalProviderDiscoveredHostList(AsyncQuery aQuery, Provider provider) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<ExternalDiscoveredHost>();
}
return source;
}
};
ProviderQueryParameters params = new ProviderQueryParameters();
params.setProvider(provider);
Frontend.getInstance().runQuery(VdcQueryType.GetDiscoveredHostListFromExternalProvider, params, aQuery);
}
public void getExternalProviderHostGroupList(AsyncQuery aQuery, Provider provider) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<ExternalHostGroup>();
}
return source;
}
};
ProviderQueryParameters params = new ProviderQueryParameters();
params.setProvider(provider);
Frontend.getInstance().runQuery(VdcQueryType.GetHostGroupsFromExternalProvider, params, aQuery);
}
public void getExternalProviderComputeResourceList(AsyncQuery aQuery, Provider provider) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<ExternalComputeResource>();
}
return source;
}
};
ProviderQueryParameters params = new ProviderQueryParameters();
params.setProvider(provider);
Frontend.getInstance().runQuery(VdcQueryType.GetComputeResourceFromExternalProvider, params, aQuery);
}
public void getAllProviders(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<Provider>();
}
Collections.sort((List<Provider>) source, new NameableComparator());
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllProviders, new GetAllProvidersParameters(), aQuery);
}
public void getAllProvidersByProvidedEntity(AsyncQuery query, final VdcObjectType providedEntity) {
query.converterCallback = new IAsyncConverter<List<Provider>>() {
@Override
public List<Provider> Convert(Object returnValue, AsyncQuery asyncQuery) {
if (returnValue == null) {
return new ArrayList<Provider>();
}
List<Provider> providers =
Linq.toList(Linq.filterProvidersByProvidedType((Collection<Provider>) returnValue, providedEntity));
Collections.sort(providers, new NameableComparator());
return providers;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllProviders, new GetAllProvidersParameters(), query);
}
public void getAllNetworkProviders(AsyncQuery query) {
getAllProvidersByProvidedEntity(query, VdcObjectType.Network);
}
public void getAllProvidersByType(AsyncQuery aQuery, ProviderType providerType) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<Provider>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllProviders, new GetAllProvidersParameters(providerType), aQuery);
}
public void getProviderCertificateChain(AsyncQuery aQuery, Provider provider) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetProviderCertificateChain, new ProviderQueryParameters(provider), aQuery);
}
private void getAllChildVlanInterfaces(Guid vdsID,
List<VdsNetworkInterface> ifaces,
IFrontendMultipleQueryAsyncCallback callback)
{
ArrayList<VdcQueryParametersBase> parametersList = new ArrayList<VdcQueryParametersBase>();
ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>();
for (final VdsNetworkInterface iface : ifaces)
{
queryTypeList.add(VdcQueryType.GetAllChildVlanInterfaces);
parametersList.add(new InterfaceAndIdQueryParameters(vdsID, iface));
}
Frontend.getInstance().runMultipleQueries(queryTypeList, parametersList, callback);
}
public void isSupportBridgesReportByVDSM(AsyncQuery aQuery, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Boolean) source).booleanValue() : true;
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.SupportBridgesReportByVDSM);
tempVar.setVersion(version);
getConfigFromCache(tempVar, aQuery);
}
public void fillTagsRecursive(Tags tagToFill, List<Tags> children)
{
ArrayList<Tags> list = new ArrayList<Tags>();
for (Tags tag : children)
{
// tags child = new tags(tag.description, tag.parent_id, tag.IsReadonly, tag.tag_id, tag.tag_name);
if (tag.gettype() == TagsType.GeneralTag)
{
list.add(tag);
if (tag.getChildren() != null)
{
fillTagsRecursive(tag, tag.getChildren());
}
}
}
tagToFill.setChildren(list);
}
public ArrayList<EventNotificationEntity> getEventNotificationTypeList()
{
ArrayList<EventNotificationEntity> ret = new ArrayList<EventNotificationEntity>();
// TODO: We can translate it here too
for (EventNotificationEntity entity : EventNotificationEntity.values()) {
if (entity != EventNotificationEntity.UNKNOWN) {
ret.add(entity);
}
}
return ret;
}
public Map<EventNotificationEntity, HashSet<AuditLogType>> getAvailableNotificationEvents() {
return VdcEventNotificationUtils.getNotificationEvents();
}
public void getNicTypeList(final int osId, Version version, AsyncQuery asyncQuery) {
final INewAsyncCallback chainedCallback = asyncQuery.asyncCallback;
asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ArrayList<String> nics = ((VdcQueryReturnValue) returnValue).getReturnValue();
List<VmInterfaceType> interfaceTypes = new ArrayList<VmInterfaceType>();
for (String nic : nics) {
try {
interfaceTypes.add(VmInterfaceType.valueOf(nic));
} catch (IllegalArgumentException e) {
// ignore if we can't find the enum value.
}
}
chainedCallback.onSuccess(model, interfaceTypes);
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository,
new OsQueryParameters(OsRepositoryVerb.GetNetworkDevices, osId, version),
asyncQuery);
}
public VmInterfaceType getDefaultNicType(Collection<VmInterfaceType> items)
{
if (items == null || items.isEmpty()) {
return null;
} else if (items.contains(VmInterfaceType.pv)) {
return VmInterfaceType.pv;
} else {
return items.iterator().next();
}
}
public boolean isVersionMatchStorageType(Version version, boolean isLocalType) {
return version.compareTo(new Version(3, 0)) >= 0;
}
public int getClusterDefaultMemoryOverCommit() {
return 100;
}
public boolean getClusterDefaultCountThreadsAsCores() {
return false;
}
public ArrayList<VolumeType> getVolumeTypeList() {
return new ArrayList<VolumeType>(Arrays.asList(new VolumeType[] {
VolumeType.Preallocated,
VolumeType.Sparse
}));
}
public ArrayList<StorageType> getStorageTypeList()
{
return new ArrayList<StorageType>(Arrays.asList(new StorageType[] {
StorageType.ISCSI,
StorageType.FCP
}));
}
public void getDiskInterfaceList(int osId, Version clusterVersion, AsyncQuery asyncQuery)
{
final INewAsyncCallback chainedCallback = asyncQuery.asyncCallback;
asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ArrayList<String> interfaces = ((VdcQueryReturnValue) returnValue).getReturnValue();
List<DiskInterface> interfaceTypes = new ArrayList<DiskInterface>();
for (String diskIfs : interfaces) {
try {
interfaceTypes.add(DiskInterface.valueOf(diskIfs));
} catch (IllegalArgumentException e) {
// ignore if we can't find the enum value.
}
}
chainedCallback.onSuccess(model, interfaceTypes);
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository,
new OsQueryParameters(OsRepositoryVerb.GetDiskInterfaces, osId, clusterVersion),
asyncQuery);
}
public ArrayList<DiskInterface> getDiskInterfaceList()
{
ArrayList<DiskInterface> diskInterfaces = new ArrayList<DiskInterface>(
Arrays.asList(new DiskInterface[] {
DiskInterface.IDE,
DiskInterface.VirtIO,
DiskInterface.VirtIO_SCSI,
DiskInterface.SPAPR_VSCSI
}));
return diskInterfaces;
}
public String getNewNicName(Collection<VmNetworkInterface> existingInterfaces)
{
int maxIfaceNumber = 0;
if (existingInterfaces != null)
{
for (VmNetworkInterface iface : existingInterfaces)
{
// name of Interface is "eth<n>" (<n>: integer).
if (iface.getName().length() > 3) {
final Integer ifaceNumber = IntegerCompat.tryParse(iface.getName().substring(3));
if (ifaceNumber != null && ifaceNumber > maxIfaceNumber) {
maxIfaceNumber = ifaceNumber;
}
}
}
}
return "nic" + (maxIfaceNumber + 1); //$NON-NLS-1$
}
/**
* Gets a value composed of "[string1]+[string2]+..." and returns "[string1Translated]+[string2Translated]+..."
*
* @param complexValue
* string in the form of "[string1]+[string2]+..."
* @return string in the form of "[string1Translated]+[string2Translated]+..."
*/
public String getComplexValueFromSpiceRedKeysResource(String complexValue) {
if (StringHelper.isNullOrEmpty(complexValue)) {
return ""; //$NON-NLS-1$
}
ArrayList<String> values = new ArrayList<String>();
for (String s : complexValue.split("[+]", -1)) { //$NON-NLS-1$
try {
String value =
SpiceConstantsManager.getInstance()
.getSpiceRedKeys()
.getString(s.replaceAll("-", "_")); //$NON-NLS-1$ //$NON-NLS-2$
values.add(value);
} catch (MissingResourceException e) {
values.add(s);
}
}
return StringHelper.join("+", values.toArray(new String[] {})); //$NON-NLS-1$
}
public Guid getEntityGuid(Object entity)
{
if (entity instanceof VM)
{
return ((VM) entity).getId();
}
else if (entity instanceof StoragePool)
{
return ((StoragePool) entity).getId();
}
else if (entity instanceof VDSGroup)
{
return ((VDSGroup) entity).getId();
}
else if (entity instanceof VDS)
{
return ((VDS) entity).getId();
}
else if (entity instanceof StorageDomain)
{
return ((StorageDomain) entity).getId();
}
else if (entity instanceof VmTemplate)
{
return ((VmTemplate) entity).getId();
}
else if (entity instanceof VmPool)
{
return ((VmPool) entity).getVmPoolId();
}
else if (entity instanceof DbUser)
{
return ((DbUser) entity).getId();
}
else if (entity instanceof DbGroup)
{
return ((DbGroup) entity).getId();
}
else if (entity instanceof Quota)
{
return ((Quota) entity).getId();
}
else if (entity instanceof DiskImage)
{
return ((DiskImage) entity).getId();
}
else if (entity instanceof GlusterVolumeEntity)
{
return ((GlusterVolumeEntity) entity).getId();
}
else if (entity instanceof Network)
{
return ((Network) entity).getId();
}
else if (entity instanceof VnicProfile)
{
return ((VnicProfile) entity).getId();
}
return Guid.Empty;
}
public boolean isWindowsOsType(Integer osType) {
// can be null as a consequence of setItems on ListModel
if (osType == null) {
return false;
}
return windowsOsIds.contains(osType);
}
public boolean isLinuxOsType(Integer osId) {
// can be null as a consequence of setItems on ListModel
if (osId == null) {
return false;
}
return linuxOsIds.contains(osId);
}
public void initWindowsOsTypes() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
windowsOsIds = (ArrayList<Integer>) ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetWindowsOss), callback);
}
public void initLinuxOsTypes() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
linuxOsIds = (ArrayList<Integer>) ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetLinuxOss), callback);
}
public void initUniqueOsNames() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
uniqueOsNames = ((VdcQueryReturnValue) returnValue).getReturnValue();
// Initialize specific UI dependencies for search
SimpleDependecyInjector.getInstance().bind(new OsValueAutoCompleter(uniqueOsNames));
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetUniqueOsNames), callback);
}
public void initOsNames() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
osNames = ((VdcQueryReturnValue) returnValue).getReturnValue();
initOsIds();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetOsNames), callback);
}
private void initOsIds() {
osIds = new ArrayList<Integer>(osNames.keySet());
Collections.sort(osIds, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return osNames.get(o1).compareTo(osNames.get(o2));
}
});
}
public void initOsArchitecture() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
osArchitectures = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetOsArchitectures), callback);
}
public boolean osNameExists(Integer osId) {
return osNames.keySet().contains(osId);
}
public String getOsName(Integer osId) {
// can be null as a consequence of setItems on ListModel
if (osId == null) {
return "";
}
return osNames.get(osId);
}
public boolean hasSpiceSupport(int osId, Version version) {
return getDisplayTypes(osId, version).contains(DisplayType.qxl);
}
public List<DisplayType> getDisplayTypes(int osId, Version version) {
return displayTypes.get(osId).get(version);
}
private void initDisplayTypes() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
displayTypes = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetDisplayTypes), callback);
}
public List<Integer> getOsIds(ArchitectureType architectureType) {
List<Integer> osIds = new ArrayList<Integer>();
for (Entry<Integer, ArchitectureType> entry : osArchitectures.entrySet()) {
if (entry.getValue() == architectureType) {
osIds.add(entry.getKey());
}
}
Collections.sort(osIds, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return osNames.get(o1).compareTo(osNames.get(o2));
}
});
return osIds;
}
public void getOsMaxRam(int osId, Version version, AsyncQuery asyncQuery) {
Frontend.getInstance().runQuery(VdcQueryType.OsRepository,
new OsQueryParameters(OsRepositoryVerb.GetMaxOsRam, osId, version),
asyncQuery);
}
public void getVmWatchdogTypes(int osId, Version version,
AsyncQuery asyncQuery) {
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetVmWatchdogTypes, osId, version), asyncQuery);
}
public ArrayList<Map.Entry<String, EntityModel<String>>> getBondingOptionList(RefObject<Map.Entry<String, EntityModel<String>>> defaultItem)
{
ArrayList<Map.Entry<String, EntityModel<String>>> list =
new ArrayList<Map.Entry<String, EntityModel<String>>>();
EntityModel<String> entityModel = new EntityModel<String>();
entityModel.setEntity("(Mode 1) Active-Backup"); //$NON-NLS-1$
list.add(new KeyValuePairCompat<String, EntityModel<String>>("mode=1 miimon=100", entityModel)); //$NON-NLS-1$
entityModel = new EntityModel<String>();
entityModel.setEntity("(Mode 2) Load balance (balance-xor)"); //$NON-NLS-1$
list.add(new KeyValuePairCompat<String, EntityModel<String>>("mode=2 miimon=100", entityModel)); //$NON-NLS-1$
entityModel = new EntityModel<String>();
entityModel.setEntity("(Mode 4) Dynamic link aggregation (802.3ad)"); //$NON-NLS-1$
defaultItem.argvalue = new KeyValuePairCompat<String, EntityModel<String>>("mode=4 miimon=100", entityModel); //$NON-NLS-1$
list.add(defaultItem.argvalue);
entityModel = new EntityModel<String>();
entityModel.setEntity("(Mode 5) Adaptive transmit load balancing (balance-tlb)"); //$NON-NLS-1$
list.add(new KeyValuePairCompat<String, EntityModel<String>>("mode=5 miimon=100", entityModel)); //$NON-NLS-1$
entityModel = new EntityModel<String>();
entityModel.setEntity(""); //$NON-NLS-1$
list.add(new KeyValuePairCompat<String, EntityModel<String>>("custom", entityModel)); //$NON-NLS-1$
return list;
}
public String getDefaultBondingOption()
{
return "mode=802.3ad miimon=150"; //$NON-NLS-1$
}
public int getMaxVmPriority()
{
return (Integer) getConfigValuePreConverted(ConfigurationValues.VmPriorityMaxValue,
getDefaultConfigurationVersion());
}
public int roundPriority(int priority)
{
int max = getMaxVmPriority();
int medium = max / 2;
int[] levels = new int[] { 1, medium, max };
for (int i = 0; i < levels.length; i++)
{
int lengthToLess = levels[i] - priority;
int lengthToMore = levels[i + 1] - priority;
if (lengthToMore < 0)
{
continue;
}
return Math.abs(lengthToLess) < lengthToMore ? levels[i] : levels[i + 1];
}
return 0;
}
public void getVmGuestAgentInterfacesByVmId(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<VmGuestAgentInterface>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmGuestAgentInterfacesByVmId, new IdQueryParameters(vmId), aQuery);
}
public void getVnicProfilesByNetworkId(AsyncQuery aQuery, Guid networkId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<VnicProfileView>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVnicProfilesByNetworkId, new IdQueryParameters(networkId), aQuery);
}
public void getVnicProfilesByDcId(AsyncQuery aQuery, Guid dcId) {
// do not replace a converter = just add if none provided
if (aQuery.converterCallback == null) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<VnicProfileView>();
}
return source;
}
};
}
Frontend.getInstance().runQuery(VdcQueryType.GetVnicProfilesByDataCenterId, new IdQueryParameters(dcId), aQuery);
}
public void getNumberOfActiveVmsInCluster(AsyncQuery aQuery, Guid clusterId) {
// do not replace a converter = just add if none provided
if (aQuery.converterCallback == null) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return Integer.valueOf(0);
}
return source;
}
};
}
Frontend.getInstance().runQuery(VdcQueryType.GetNumberOfActiveVmsInVdsGroupByVdsGroupId, new IdQueryParameters(clusterId), aQuery);
}
public void getNumberOfVmsInCluster(AsyncQuery aQuery, Guid clusterId) {
Frontend.getInstance().runQuery(VdcQueryType.GetNumberOfVmsInVdsGroupByVdsGroupId, new IdQueryParameters(clusterId),
aQuery);
}
public boolean isMixedStorageDomainsSupported(Version version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.MixedDomainTypesInDataCenter, version.toString());
}
private ArrayList<VDSGroup> getClusterByServiceList(ArrayList<VDSGroup> list,
boolean supportsVirtService,
boolean supportsGlusterService) {
final ArrayList<VDSGroup> filteredList = new ArrayList<VDSGroup>();
for (VDSGroup cluster : list) {
if ((supportsVirtService && cluster.supportsVirtService())
|| (supportsGlusterService && cluster.supportsGlusterService())) {
filteredList.add(cluster);
}
}
// sort by cluster name
Collections.sort(filteredList, new NameableComparator());
return filteredList;
}
public String priorityToString(int value) {
int roundedPriority = roundPriority(value);
if (roundedPriority == 1) {
return ConstantsManager.getInstance().getConstants().vmLowPriority();
}
else if (roundedPriority == getMaxVmPriority() / 2) {
return ConstantsManager.getInstance().getConstants().vmMediumPriority();
}
else if (roundedPriority == getMaxVmPriority()) {
return ConstantsManager.getInstance().getConstants().vmHighPriority();
}
else {
return ConstantsManager.getInstance().getConstants().vmUnknownPriority();
}
}
public void getExternalNetworkMap(AsyncQuery aQuery, Guid providerId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source == null) {
return new HashMap<Network, Set<Guid>>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllExternalNetworksOnProvider,
new IdQueryParameters(providerId),
aQuery);
}
public Integer getMaxVmNameLengthWin() {
Integer maxVmNameLengthWindows = (Integer) getConfigValuePreConverted(ConfigurationValues.MaxVmNameLengthWindows);
if (maxVmNameLengthWindows == null) {
return 15;
}
return maxVmNameLengthWindows;
}
public Integer getMaxVmNameLengthNonWin() {
Integer maxVmNameLengthNonWindows = (Integer) getConfigValuePreConverted(ConfigurationValues.MaxVmNameLengthNonWindows);
if (maxVmNameLengthNonWindows == null) {
return 64;
}
return maxVmNameLengthNonWindows;
}
public int getOptimizeSchedulerForSpeedPendingRequests() {
return (Integer) getConfigValuePreConverted(ConfigurationValues.SpeedOptimizationSchedulingThreshold,
getDefaultConfigurationVersion());
}
public boolean getScheudulingAllowOverbookingSupported() {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.SchedulerAllowOverBooking,
getDefaultConfigurationVersion());
}
public int getSchedulerAllowOverbookingPendingRequestsThreshold() {
return (Integer) getConfigValuePreConverted(ConfigurationValues.SchedulerOverBookingThreshold,
getDefaultConfigurationVersion());
}
public Integer getDefaultOs (ArchitectureType architectureType) {
return defaultOSes.get(architectureType);
}
public boolean isRebootCommandExecutionAllowed(List<VM> vms) {
if (vms.isEmpty() || !VdcActionUtils.canExecute(vms, VM.class, VdcActionType.RebootVm)) {
return false;
}
for (VM vm : vms) {
Version version = vm.getVdsGroupCompatibilityVersion();
Version anyDcVersion = new Version();
// currently on VDSM side reboot is supported only when the guest agent is present and responsive so we need to check for that
if (!isCommandCompatible(VdcActionType.RebootVm, version, anyDcVersion) || StringHelper.isNullOrEmpty(vm.getVmIp())) {
return false;
}
}
return true;
}
public boolean isSerialNumberPolicySupported(String version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.SerialNumberPolicySupported, version);
}
public boolean isBootMenuSupported(String version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.BootMenuSupported, version);
}
public boolean isSpiceFileTransferToggleSupported(String version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.SpiceFileTransferToggleSupported, version);
}
public boolean isSpiceCopyPasteToggleSupported(String version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.SpiceCopyPasteToggleSupported, version);
}
public List<IStorageModel> getDataStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
models.addAll(getFileDataStorageModels());
models.addAll(getBlockDataStorageModels());
return models;
}
public List<IStorageModel> getFileDataStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
NfsStorageModel nfsDataModel = new NfsStorageModel();
models.add(nfsDataModel);
PosixStorageModel posixDataModel = new PosixStorageModel();
models.add(posixDataModel);
GlusterStorageModel GlusterDataModel = new GlusterStorageModel();
models.add(GlusterDataModel);
LocalStorageModel localDataModel = new LocalStorageModel();
models.add(localDataModel);
addTypeToStorageModels(StorageDomainType.Data, models);
return models;
}
public List<IStorageModel> getBlockDataStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
IscsiStorageModel iscsiDataModel = new IscsiStorageModel();
iscsiDataModel.setIsGrouppedByTarget(true);
models.add(iscsiDataModel);
FcpStorageModel fcpDataModel = new FcpStorageModel();
models.add(fcpDataModel);
addTypeToStorageModels(StorageDomainType.Data, models);
return models;
}
public List<IStorageModel> getImportBlockDataStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
ImportIscsiStorageModel iscsiDataModel = new ImportIscsiStorageModel();
models.add(iscsiDataModel);
ImportFcpStorageModel fcpDataModel = new ImportFcpStorageModel();
models.add(fcpDataModel);
addTypeToStorageModels(StorageDomainType.Data, models);
return models;
}
public List<IStorageModel> getIsoStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
NfsStorageModel nfsIsoModel = new NfsStorageModel();
models.add(nfsIsoModel);
PosixStorageModel posixIsoModel = new PosixStorageModel();
models.add(posixIsoModel);
LocalStorageModel localIsoModel = new LocalStorageModel();
models.add(localIsoModel);
addTypeToStorageModels(StorageDomainType.ISO, models);
return models;
}
public List<IStorageModel> getExportStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
NfsStorageModel nfsExportModel = new NfsStorageModel();
models.add(nfsExportModel);
PosixStorageModel posixExportModel = new PosixStorageModel();
models.add(posixExportModel);
GlusterStorageModel glusterExportModel = new GlusterStorageModel();
models.add(glusterExportModel);
addTypeToStorageModels(StorageDomainType.ImportExport, models);
return models;
}
private void addTypeToStorageModels(StorageDomainType storageDomainType, List<IStorageModel> models) {
for (IStorageModel model : models) {
model.setRole(storageDomainType);
}
}
}
|
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/dataprovider/AsyncDataProvider.java
|
package org.ovirt.engine.ui.uicommonweb.dataprovider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.MissingResourceException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.EventNotificationEntity;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.VdcEventNotificationUtils;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.gluster.GlusterVolumeRemoveBricksQueriesParameters;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.DbGroup;
import org.ovirt.engine.core.common.businessentities.DbUser;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskInterface;
import org.ovirt.engine.core.common.businessentities.DisplayType;
import org.ovirt.engine.core.common.businessentities.ExternalComputeResource;
import org.ovirt.engine.core.common.businessentities.ExternalDiscoveredHost;
import org.ovirt.engine.core.common.businessentities.ExternalHostGroup;
import org.ovirt.engine.core.common.businessentities.IVdcQueryable;
import org.ovirt.engine.core.common.businessentities.ImageFileType;
import org.ovirt.engine.core.common.businessentities.LUNs;
import org.ovirt.engine.core.common.businessentities.Permissions;
import org.ovirt.engine.core.common.businessentities.Provider;
import org.ovirt.engine.core.common.businessentities.ProviderType;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.businessentities.QuotaEnforcementTypeEnum;
import org.ovirt.engine.core.common.businessentities.RepoImage;
import org.ovirt.engine.core.common.businessentities.Role;
import org.ovirt.engine.core.common.businessentities.ServerCpu;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.Tags;
import org.ovirt.engine.core.common.businessentities.TagsType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmGuestAgentInterface;
import org.ovirt.engine.core.common.businessentities.VmPool;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.VmTemplateStatus;
import org.ovirt.engine.core.common.businessentities.VolumeFormat;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.comparators.LexoNumericComparator;
import org.ovirt.engine.core.common.businessentities.comparators.NameableComparator;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterBrickEntity;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterClusterService;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterHookEntity;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterServerService;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterVolumeEntity;
import org.ovirt.engine.core.common.businessentities.gluster.ServiceType;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkQoS;
import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VmInterfaceType;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VnicProfile;
import org.ovirt.engine.core.common.businessentities.network.VnicProfileView;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.queries.ArchCapabilitiesParameters;
import org.ovirt.engine.core.common.queries.ArchCapabilitiesParameters.ArchCapabilitiesVerb;
import org.ovirt.engine.core.common.queries.CommandVersionsInfo;
import org.ovirt.engine.core.common.queries.ConfigurationValues;
import org.ovirt.engine.core.common.queries.GetAgentFenceOptionsQueryParameters;
import org.ovirt.engine.core.common.queries.GetAllAttachableDisks;
import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters;
import org.ovirt.engine.core.common.queries.GetAllProvidersParameters;
import org.ovirt.engine.core.common.queries.GetAllServerCpuListParameters;
import org.ovirt.engine.core.common.queries.GetConfigurationValueParameters;
import org.ovirt.engine.core.common.queries.GetConnectionsByDataCenterAndStorageTypeParameters;
import org.ovirt.engine.core.common.queries.GetDataCentersWithPermittedActionOnClustersParameters;
import org.ovirt.engine.core.common.queries.GetEntitiesWithPermittedActionParameters;
import org.ovirt.engine.core.common.queries.GetExistingStorageDomainListParameters;
import org.ovirt.engine.core.common.queries.GetHostListFromExternalProviderParameters;
import org.ovirt.engine.core.common.queries.GetHostsForStorageOperationParameters;
import org.ovirt.engine.core.common.queries.GetImagesListByStoragePoolIdParameters;
import org.ovirt.engine.core.common.queries.GetLunsByVgIdParameters;
import org.ovirt.engine.core.common.queries.GetPermittedStorageDomainsByStoragePoolIdParameters;
import org.ovirt.engine.core.common.queries.GetStorageDomainsByConnectionParameters;
import org.ovirt.engine.core.common.queries.GetStoragePoolsByClusterServiceParameters;
import org.ovirt.engine.core.common.queries.GetTagsByUserGroupIdParameters;
import org.ovirt.engine.core.common.queries.GetTagsByUserIdParameters;
import org.ovirt.engine.core.common.queries.GetTagsByVdsIdParameters;
import org.ovirt.engine.core.common.queries.GetTagsByVmIdParameters;
import org.ovirt.engine.core.common.queries.GetVmTemplateParameters;
import org.ovirt.engine.core.common.queries.GetVmUpdatesOnNextRunExistsParameters;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.InterfaceAndIdQueryParameters;
import org.ovirt.engine.core.common.queries.MultilevelAdministrationsQueriesParameters;
import org.ovirt.engine.core.common.queries.NameQueryParameters;
import org.ovirt.engine.core.common.queries.OsQueryParameters;
import org.ovirt.engine.core.common.queries.OsQueryParameters.OsRepositoryVerb;
import org.ovirt.engine.core.common.queries.ProviderQueryParameters;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.ServerParameters;
import org.ovirt.engine.core.common.queries.StorageServerConnectionQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.queries.VdsIdParametersBase;
import org.ovirt.engine.core.common.queries.gluster.AddedGlusterServersParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterHookContentQueryParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterHookQueryParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterServersQueryParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterServiceQueryParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterVolumeAdvancedDetailsParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterVolumeProfileParameters;
import org.ovirt.engine.core.common.queries.gluster.GlusterVolumeQueriesParameters;
import org.ovirt.engine.core.common.utils.ObjectUtils;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.utils.SimpleDependecyInjector;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.IntegerCompat;
import org.ovirt.engine.core.compat.KeyValuePairCompat;
import org.ovirt.engine.core.compat.RefObject;
import org.ovirt.engine.core.compat.RpmVersion;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.searchbackend.OsValueAutoCompleter;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.IAsyncConverter;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.models.ApplicationModeHelper;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.LoginModel;
import org.ovirt.engine.ui.uicommonweb.models.datacenters.NetworkQoSModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.FcpStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.GlusterStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.IStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.ImportFcpStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.ImportIscsiStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.IscsiStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.LocalStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.NfsStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.storage.PosixStorageModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.WANDisableEffects;
import org.ovirt.engine.ui.uicommonweb.models.vms.WanColorDepth;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.EventArgs;
import org.ovirt.engine.ui.uicompat.FrontendMultipleQueryAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleQueryAsyncCallback;
import org.ovirt.engine.ui.uicompat.SpiceConstantsManager;
public class AsyncDataProvider {
private static AsyncDataProvider instance;
public static AsyncDataProvider getInstance() {
if (instance == null) {
instance = new AsyncDataProvider();
}
return instance;
}
public static void setInstance(AsyncDataProvider provider) {
instance = provider;
}
private final String GENERAL = "general"; //$NON-NLS-1$
// dictionary to hold cache of all config values (per version) queried by client, if the request for them succeeded.
private HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object> cachedConfigValues =
new HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object>();
private HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object> cachedConfigValuesPreConvert =
new HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object>();
private String _defaultConfigurationVersion = null;
// cached OS names
private HashMap<Integer, String> osNames;
// cached list of os ids
private List<Integer> osIds;
// cached unique OS names
private HashMap<Integer, String> uniqueOsNames;
// cached linux OS
private List<Integer> linuxOsIds;
// cached NIC hotplug support map
private Map<Pair<Integer, Version>, Boolean> nicHotplugSupportMap;
// cached disk hotpluggable interfaces map
private Map<Pair<Integer, Version>, Set<String>> diskHotpluggableInterfacesMap;
// cached os's balloon enabled by default map (given compatibility version)
private Map<Integer, Map<Version, Boolean>> balloonSupportMap;
// cached windows OS
private List<Integer> windowsOsIds;
// cached OS Architecture
private HashMap<Integer, ArchitectureType> osArchitectures;
// default OS per architecture
private HashMap<ArchitectureType, Integer> defaultOSes;
// cached os's support for display types (given compatibility version)
private HashMap<Integer, Map<Version, List<DisplayType>>> displayTypes;
// cached architecture support for live migration
private Map<ArchitectureType, Map<Version, Boolean>> migrationSupport;
// cached architecture support for memory snapshot
private Map<ArchitectureType, Map<Version, Boolean>> memorySnapshotSupport;
// cached architecture support for VM suspend
private Map<ArchitectureType, Map<Version, Boolean>> suspendSupport;
// cached custom properties
private Map<Version, Map<String, String>> customPropertiesList;
public String getDefaultConfigurationVersion() {
return _defaultConfigurationVersion;
}
private void getDefaultConfigurationVersion(Object target) {
AsyncQuery callback = new AsyncQuery(target, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
if (returnValue != null) {
_defaultConfigurationVersion =
((VdcQueryReturnValue) returnValue).getReturnValue();
} else {
_defaultConfigurationVersion = GENERAL;
}
LoginModel loginModel = (LoginModel) model;
loginModel.getLoggedInEvent().raise(loginModel, EventArgs.EMPTY);
}
});
callback.setHandleFailure(true);
Frontend.getInstance().runQuery(VdcQueryType.GetDefaultConfigurationVersion,
new VdcQueryParametersBase(),
callback);
}
public void initCache(LoginModel loginModel) {
cacheConfigValues(new AsyncQuery(loginModel, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
getDefaultConfigurationVersion(target);
}
}));
initOsNames();
initUniqueOsNames();
initLinuxOsTypes();
initWindowsOsTypes();
initDisplayTypes();
initBalloonSupportMap();
initNicHotplugSupportMap();
initDiskHotpluggableInterfacesMap();
initOsArchitecture();
initDefaultOSes();
initMigrationSupportMap();
initMemorySnapshotSupportMap();
initSuspendSupportMap();
initCustomPropertiesList();
}
private void initCustomPropertiesList() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
customPropertiesList = (Map<Version, Map<String, String>>) returnValue;
}
};
callback.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return (source != null) ? (Map<Version, Map<String, String>>) source
: new HashMap<Version, Map<String, String>>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmCustomProperties,
new VdcQueryParametersBase().withoutRefresh(), callback);
}
public void initDefaultOSes() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
defaultOSes = ((VdcQueryReturnValue) returnValue)
.getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetDefaultOSes), callback);
}
public Boolean isMigrationSupported(ArchitectureType architecture, Version version) {
return migrationSupport.get(architecture).get(version);
}
public Boolean isMemorySnapshotSupportedByArchitecture(ArchitectureType architecture, Version version) {
return memorySnapshotSupport.get(architecture).get(version);
}
public Boolean isSuspendSupportedByArchitecture(ArchitectureType architecture, Version version) {
return suspendSupport.get(architecture).get(version);
}
private void initMigrationSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
migrationSupport = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetArchitectureCapabilities,
new ArchCapabilitiesParameters(ArchCapabilitiesVerb.GetMigrationSupport),
callback);
}
private void initMemorySnapshotSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
memorySnapshotSupport = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetArchitectureCapabilities,
new ArchCapabilitiesParameters(ArchCapabilitiesVerb.GetMemorySnapshotSupport),
callback);
}
private void initSuspendSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
suspendSupport = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetArchitectureCapabilities,
new ArchCapabilitiesParameters(ArchCapabilitiesVerb.GetSuspendSupport),
callback);
}
/**
* Check if memory snapshot is supported
* @param vm
* @return
*/
public boolean isMemorySnapshotSupported(VM vm) {
if (vm == null) {
return false;
}
boolean archMemorySnapshotSupported = isMemorySnapshotSupportedByArchitecture(
vm.getClusterArch(),
vm.getVdsGroupCompatibilityVersion());
return ((Boolean) getConfigValuePreConverted(
ConfigurationValues.MemorySnapshotSupported,
vm.getVdsGroupCompatibilityVersion().toString()))
&& archMemorySnapshotSupported;
}
public boolean canVmsBePaused(List<VM> items) {
for (VM vm : items) {
if (!isSuspendSupportedByArchitecture(vm.getClusterArch(),
vm.getVdsGroupCompatibilityVersion())) {
return false;
}
}
return true;
}
public boolean isLiveMergeSupported(VM vm) {
return (vm != null && (Boolean) getConfigValuePreConverted(
ConfigurationValues.LiveMergeSupported,
vm.getVdsGroupCompatibilityVersion().toString()));
}
public void initNicHotplugSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
nicHotplugSupportMap = ((VdcQueryReturnValue) returnValue)
.getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetNicHotplugSupportMap), callback);
}
public Map<Pair<Integer, Version>, Boolean> getNicHotplugSupportMap() {
return nicHotplugSupportMap;
}
public Boolean getNicHotplugSupport(Integer osId, Version version) {
Pair<Integer, Version> pair = new Pair<Integer, Version>(osId, version);
if (getNicHotplugSupportMap().containsKey(pair)) {
return getNicHotplugSupportMap().get(pair);
}
return false;
}
public Boolean isBalloonEnabled(int osId, Version version) {
return balloonSupportMap.get(osId).get(version);
}
public void initBalloonSupportMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
balloonSupportMap = (Map<Integer, Map<Version, Boolean>>) ((VdcQueryReturnValue) returnValue)
.getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetBalloonSupportMap), callback);
}
public void initDiskHotpluggableInterfacesMap() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
diskHotpluggableInterfacesMap = ((VdcQueryReturnValue) returnValue)
.getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetDiskHotpluggableInterfacesMap), callback);
}
public Map<Pair<Integer, Version>, Set<String>> getDiskHotpluggableInterfacesMap() {
return diskHotpluggableInterfacesMap;
}
public Collection<DiskInterface> getDiskHotpluggableInterfaces(Integer osId, Version version) {
Set<String> diskHotpluggableInterfaces = getDiskHotpluggableInterfacesMap()
.get(new Pair<Integer, Version>(osId, version));
if (diskHotpluggableInterfaces == null) {
return Collections.emptySet();
}
Collection<DiskInterface> diskInterfaces = new HashSet<DiskInterface>();
for (String diskHotpluggableInterface : diskHotpluggableInterfaces) {
diskInterfaces.add(DiskInterface.valueOf(diskHotpluggableInterface));
}
return diskInterfaces;
}
public void getAAAProfilesListViaPublic(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<String>((ArrayList<String>) source)
: new ArrayList<String>();
}
};
Frontend.getInstance().runPublicQuery(VdcQueryType.GetAAAProfileList, new VdcQueryParametersBase(), aQuery);
}
public void getIsoDomainByDataCenterId(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<StorageDomain> storageDomains = (ArrayList<StorageDomain>) source;
for (StorageDomain domain : storageDomains)
{
if (domain.getStorageDomainType() == StorageDomainType.ISO)
{
return domain;
}
}
}
return null;
}
};
IdQueryParameters getIsoParams = new IdQueryParameters(dataCenterId);
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByStoragePoolId, getIsoParams, aQuery);
}
public void getExportDomainByDataCenterId(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<StorageDomain> storageDomains = (ArrayList<StorageDomain>) source;
for (StorageDomain domain : storageDomains)
{
if (domain.getStorageDomainType() == StorageDomainType.ImportExport)
{
return domain;
}
}
return null;
}
};
IdQueryParameters getExportParams = new IdQueryParameters(dataCenterId);
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByStoragePoolId, getExportParams, aQuery);
}
public void getIrsImageList(AsyncQuery aQuery, Guid storagePoolId) {
getIrsImageList(aQuery, storagePoolId, false);
}
public void getIrsImageList(AsyncQuery aQuery, Guid storagePoolId, boolean forceRefresh) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<RepoImage> repoList = (ArrayList<RepoImage>) source;
ArrayList<String> fileNameList = new ArrayList<String>();
for (RepoImage repoImage : repoList)
{
fileNameList.add(repoImage.getRepoImageId());
}
Collections.sort(fileNameList, String.CASE_INSENSITIVE_ORDER);
return fileNameList;
}
return new ArrayList<String>();
}
};
GetImagesListByStoragePoolIdParameters parameters =
new GetImagesListByStoragePoolIdParameters(storagePoolId, ImageFileType.ISO);
parameters.setForceRefresh(forceRefresh);
Frontend.getInstance().runQuery(VdcQueryType.GetImagesListByStoragePoolId, parameters, aQuery);
}
public void getFloppyImageList(AsyncQuery aQuery, Guid storagePoolId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<RepoImage> repoList = (ArrayList<RepoImage>) source;
ArrayList<String> fileNameList = new ArrayList<String>();
for (RepoImage repoImage : repoList)
{
fileNameList.add(repoImage.getRepoImageId());
}
Collections.sort(fileNameList, String.CASE_INSENSITIVE_ORDER);
return fileNameList;
}
return new ArrayList<String>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetImagesListByStoragePoolId,
new GetImagesListByStoragePoolIdParameters(storagePoolId, ImageFileType.Floppy),
aQuery);
}
public void isClusterEmpty(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter<Boolean>() {
@Override
public Boolean Convert(Object source, AsyncQuery _asyncQuery)
{
return (Boolean) source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.IsClusterEmpty, new IdQueryParameters(id), aQuery);
}
public void getHostArchitecture(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter<ArchitectureType>() {
@Override
public ArchitectureType Convert(Object source, AsyncQuery _asyncQuery)
{
return (ArchitectureType) source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetHostArchitecture, new IdQueryParameters(id), aQuery);
}
public void getClusterById(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVdsGroupById, new IdQueryParameters(id), aQuery);
}
public void getClusterListByName(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<VDSGroup>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters("Cluster: name=" + name + " sortby name", SearchType.Cluster), //$NON-NLS-1$ //$NON-NLS-2$
aQuery);
}
public void getPoolById(AsyncQuery aQuery, Guid poolId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmPoolById, new IdQueryParameters(poolId), aQuery);
}
public void getVmById(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmByVmId, new IdQueryParameters(vmId), aQuery);
}
public void getVmNextRunConfiguration(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmNextRunConfiguration, new IdQueryParameters(vmId), aQuery);
}
public void isNextRunConfigurationChanged(VM original, VM updated, AsyncQuery aQuery) {
Frontend.getInstance().runQuery(VdcQueryType.GetVmUpdatesOnNextRunExists,
new GetVmUpdatesOnNextRunExistsParameters(original, updated), aQuery);
}
public void getDataCenterList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<StoragePool>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters("DataCenter: sortby name", SearchType.StoragePool), //$NON-NLS-1$
aQuery);
}
public void getDataCenterByClusterServiceList(AsyncQuery aQuery,
boolean supportsVirtService,
boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source == null) {
return new ArrayList<StoragePool>();
}
// sort data centers
final ArrayList<StoragePool> storagePoolList = (ArrayList<StoragePool>) source;
Collections.sort(storagePoolList, new NameableComparator());
return source;
}
};
final GetStoragePoolsByClusterServiceParameters parameters = new GetStoragePoolsByClusterServiceParameters();
parameters.setSupportsVirtService(supportsVirtService);
parameters.setSupportsGlusterService(supportsGlusterService);
Frontend.getInstance().runQuery(VdcQueryType.GetStoragePoolsByClusterService, parameters, aQuery);
}
public void getDataCenterListByName(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<StoragePool>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters("DataCenter: name=" + name + " sortby name", SearchType.StoragePool), //$NON-NLS-1$ //$NON-NLS-2$
aQuery);
}
public void getSpiceUsbAutoShare(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Boolean) source).booleanValue() : true;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.SpiceUsbAutoShare,
getDefaultConfigurationVersion()),
aQuery);
}
public void getWANColorDepth(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? WanColorDepth.fromInt(((Integer) source).intValue()) : WanColorDepth.depth16;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.WANColorDepth, getDefaultConfigurationVersion()),
aQuery);
}
public void getWANDisableEffects(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<WANDisableEffects>();
}
List<WANDisableEffects> res = new ArrayList<WANDisableEffects>();
String fromDb = (String) source;
for (String value : fromDb.split(",")) {//$NON-NLS-1$
if (value == null) {
continue;
}
String trimmedValue = value.trim();
if ("".equals(trimmedValue)) {
continue;
}
res.add(WANDisableEffects.fromString(trimmedValue));
}
return res;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.WANDisableEffects,
getDefaultConfigurationVersion()),
aQuery);
}
public void getMaxVmsInPool(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1000;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.MaxVmsInPool, getDefaultConfigurationVersion()),
aQuery);
}
public void getMaxNumOfVmSockets(AsyncQuery aQuery, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.MaxNumOfVmSockets);
tempVar.setVersion(version);
getConfigFromCache(tempVar, aQuery);
}
public void getMaxNumOfVmCpus(AsyncQuery aQuery, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.MaxNumOfVmCpus);
tempVar.setVersion(version);
getConfigFromCache(tempVar, aQuery);
}
public void getMaxNumOfCPUsPerSocket(AsyncQuery aQuery, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.MaxNumOfCpuPerSocket);
tempVar.setVersion(version);
getConfigFromCache(tempVar, aQuery);
}
public void getClusterList(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDSGroup> list = (ArrayList<VDSGroup>) source;
Collections.sort(list, new NameableComparator());
return list;
}
return new ArrayList<VDSGroup>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVdsGroupsByStoragePoolId,
new IdQueryParameters(dataCenterId),
aQuery);
}
public List<VDSGroup> filterByArchitecture(List<VDSGroup> clusters, ArchitectureType targetArchitecture) {
List<VDSGroup> filteredClusters = new ArrayList<VDSGroup>();
for (VDSGroup cluster : clusters) {
if (cluster.getArchitecture().equals(targetArchitecture)) {
filteredClusters.add(cluster);
}
}
return filteredClusters;
}
public List<VDSGroup> filterClustersWithoutArchitecture(List<VDSGroup> clusters) {
List<VDSGroup> filteredClusters = new ArrayList<VDSGroup>();
for (VDSGroup cluster : clusters) {
if (cluster.getArchitecture() != ArchitectureType.undefined) {
filteredClusters.add(cluster);
}
}
return filteredClusters;
}
public void getClusterByServiceList(AsyncQuery aQuery, Guid dataCenterId,
final boolean supportsVirtService, final boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source == null) {
return new ArrayList<VDSGroup>();
}
final ArrayList<VDSGroup> list = (ArrayList<VDSGroup>) source;
return getClusterByServiceList(list, supportsVirtService, supportsGlusterService);
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVdsGroupsByStoragePoolId,
new IdQueryParameters(dataCenterId),
aQuery);
}
public void isSoundcardEnabled(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source != null) {
return !((List<?>) source).isEmpty();
}
return false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetSoundDevices, new IdQueryParameters(vmId), aQuery);
}
public void isVirtioScsiEnabledForVm(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source != null) {
return !((List<?>) source).isEmpty();
}
return false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVirtioScsiControllers, new IdQueryParameters(vmId), aQuery);
}
public void getClusterListByService(AsyncQuery aQuery, final boolean supportsVirtService,
final boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDSGroup> list =
getClusterByServiceList((ArrayList<VDSGroup>) source,
supportsVirtService,
supportsGlusterService);
Collections.sort(list, new NameableComparator());
return list;
}
return new ArrayList<VDSGroup>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllVdsGroups, new VdcQueryParametersBase(), aQuery);
}
public void getClusterList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDSGroup> list = (ArrayList<VDSGroup>) source;
Collections.sort(list, new NameableComparator());
return list;
}
return new ArrayList<VDSGroup>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllVdsGroups, new VdcQueryParametersBase(), aQuery);
}
public void getTemplateDiskList(AsyncQuery aQuery, Guid templateId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<DiskImage>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplatesDisks, new IdQueryParameters(templateId), aQuery);
}
/**
* Round the priority to the closest value from n (3 for now) values
*
* i.e.: if priority entered is 30 and the predefined values are 1,50,100
*
* then the return value will be 50 (closest to 50).
*
* @param priority
* - the current priority of the vm
* @param maxPriority
* - the max priority
* @return the rounded priority
*/
public int getRoundedPriority(int priority, int maxPriority) {
int medium = maxPriority / 2;
int[] levels = new int[] { 1, medium, maxPriority };
for (int i = 0; i < levels.length; i++)
{
int lengthToLess = levels[i] - priority;
int lengthToMore = levels[i + 1] - priority;
if (lengthToMore < 0)
{
continue;
}
return Math.abs(lengthToLess) < lengthToMore ? levels[i] : levels[i + 1];
}
return 0;
}
public void getTemplateListByDataCenter(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new TemplateConverter();
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplatesByStoragePoolId,
new IdQueryParameters(dataCenterId),
aQuery);
}
public void getTemplateListByStorage(AsyncQuery aQuery, Guid storageId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<VmTemplate> list = new ArrayList<VmTemplate>();
if (source != null)
{
for (VmTemplate template : (ArrayList<VmTemplate>) source)
{
if (template.getStatus() == VmTemplateStatus.OK)
{
list.add(template);
}
}
Collections.sort(list, new NameableComparator());
}
return list;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplatesFromStorageDomain,
new IdQueryParameters(storageId),
aQuery);
}
public ArrayList<VmTemplate> filterTemplatesByArchitecture(List<VmTemplate> list,
ArchitectureType architecture) {
ArrayList<VmTemplate> filteredList = new ArrayList<VmTemplate>();
for (VmTemplate template : list) {
if (template.getId().equals(Guid.Empty) ||
template.getClusterArch().equals(architecture)) {
filteredList.add(template);
}
}
return filteredList;
}
public void getNumOfMonitorList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<Integer> nums = new ArrayList<Integer>();
if (source != null)
{
Iterable numEnumerable = (Iterable) source;
Iterator numIterator = numEnumerable.iterator();
while (numIterator.hasNext())
{
nums.add(Integer.parseInt(numIterator.next().toString()));
}
}
return nums;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.ValidNumOfMonitors,
getDefaultConfigurationVersion()),
aQuery);
}
public void getStorageDomainList(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<StorageDomain>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByStoragePoolId,
new IdQueryParameters(dataCenterId),
aQuery);
}
public void getMaxVmPriority(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return 100;
}
return source;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.VmPriorityMaxValue,
getDefaultConfigurationVersion()),
aQuery);
}
public void getHostById(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(id), aQuery);
}
public void getHostListByCluster(AsyncQuery aQuery, String clusterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDS> list = Linq.<VDS> cast((ArrayList<IVdcQueryable>) source);
return list;
}
return new ArrayList<VDS>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search, new SearchParameters("Host: cluster = " + clusterName + " sortby name", //$NON-NLS-1$ //$NON-NLS-2$
SearchType.VDS), aQuery);
}
public void getHostListByDataCenter(AsyncQuery aQuery, Guid spId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDS> list = Linq.<VDS> cast((ArrayList<IVdcQueryable>) source);
return list;
}
return new ArrayList<VDS>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllVdsByStoragePool, new IdQueryParameters(spId), aQuery);
}
public void getVmDiskList(AsyncQuery aQuery, Guid vmId, boolean isRefresh) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
return source;
}
return new ArrayList<DiskImage>();
}
};
IdQueryParameters params = new IdQueryParameters(vmId);
params.setRefresh(isRefresh);
Frontend.getInstance().runQuery(VdcQueryType.GetAllDisksByVmId, params, aQuery);
}
public HashMap<Integer, String> getOsUniqueOsNames() {
return uniqueOsNames;
}
public void getAAAProfilesList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<String>((ArrayList<String>) source)
: new ArrayList<String>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAAAProfileList, new VdcQueryParametersBase(), aQuery);
}
public void getRoleList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Role>) source : new ArrayList<Role>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllRoles, new MultilevelAdministrationsQueriesParameters(), aQuery);
}
public void getStorageDomainById(AsyncQuery aQuery, Guid storageDomainId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (StorageDomain) source : null;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainById,
new IdQueryParameters(storageDomainId),
aQuery);
}
public VolumeFormat getDiskVolumeFormat(VolumeType volumeType, StorageType storageType) {
if (storageType.isFileDomain()) {
return VolumeFormat.RAW;
} else if (storageType.isBlockDomain()) {
switch (volumeType) {
case Sparse:
return VolumeFormat.COW;
case Preallocated:
return VolumeFormat.RAW;
default:
return VolumeFormat.Unassigned;
}
} else {
return VolumeFormat.Unassigned;
}
}
public void getClusterNetworkList(AsyncQuery aQuery, Guid clusterId) {
// do not replace a converter = just add if none provided
if (aQuery.converterCallback == null) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<Network>();
}
return source;
}
};
}
Frontend.getInstance().runQuery(VdcQueryType.GetAllNetworksByClusterId, new IdQueryParameters(clusterId), aQuery);
}
public void getAllNetworkQos(Guid dcId, AsyncQuery query) {
query.converterCallback = new IAsyncConverter<List<NetworkQoS>>() {
@Override
public List<NetworkQoS> Convert(Object returnValue, AsyncQuery asyncQuery) {
List<NetworkQoS> qosList = returnValue == null ? new ArrayList<NetworkQoS>() : (List<NetworkQoS>) returnValue;
qosList.add(0, NetworkQoSModel.EMPTY_QOS);
return qosList;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllNetworkQosByStoragePoolId, new IdQueryParameters(dcId), query);
}
public void getDataCenterById(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetStoragePoolById,
new IdQueryParameters(dataCenterId).withoutRefresh(), aQuery);
}
public void getNetworkLabelsByDataCenterId(Guid dataCenterId, AsyncQuery query) {
query.converterCallback = new IAsyncConverter<SortedSet<String>>() {
@Override
public SortedSet<String> Convert(Object returnValue, AsyncQuery asyncQuery) {
SortedSet<String> sortedSet = new TreeSet<String>(new LexoNumericComparator());
sortedSet.addAll((Collection<String>) returnValue);
return sortedSet;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetNetworkLabelsByDataCenterId,
new IdQueryParameters(dataCenterId),
query);
}
public void getWatchdogByVmId(AsyncQuery aQuery, Guid vmId) {
Frontend.getInstance().runQuery(VdcQueryType.GetWatchdog, new IdQueryParameters(vmId), aQuery);
}
public void getTemplateById(AsyncQuery aQuery, Guid templateId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplate, new GetVmTemplateParameters(templateId), aQuery);
}
public void countAllTemplates(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmTemplateCount, new VdcQueryParametersBase(), aQuery);
}
public void getHostList(AsyncQuery aQuery) {
getHostListByStatus(aQuery, null);
}
public void getHostListByStatus(AsyncQuery aQuery, VDSStatus status) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDS> list = Linq.<VDS> cast((Iterable) source);
return list;
}
return new ArrayList<VDS>();
}
};
SearchParameters searchParameters =
new SearchParameters("Host: " + (status == null ? "" : ("status=" + status.name())), SearchType.VDS); //$NON-NLS-1$ //$NON-NLS-2$
searchParameters.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParameters, aQuery);
}
public void getHostsForStorageOperation(AsyncQuery aQuery, Guid storagePoolId, boolean localFsOnly) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source != null) {
return source;
}
return new ArrayList<VDS>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetHostsForStorageOperation,
new GetHostsForStorageOperationParameters(storagePoolId, localFsOnly),
aQuery);
}
public void getVolumeList(AsyncQuery aQuery, String clusterName) {
if ((ApplicationModeHelper.getUiMode().getValue() & ApplicationMode.GlusterOnly.getValue()) == 0) {
aQuery.asyncCallback.onSuccess(aQuery.model, new ArrayList<GlusterVolumeEntity>());
return;
}
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<GlusterVolumeEntity> list =
(ArrayList<GlusterVolumeEntity>) source;
return list;
}
return new ArrayList<GlusterVolumeEntity>();
}
};
SearchParameters searchParameters;
searchParameters =
clusterName == null ? new SearchParameters("Volumes:", SearchType.GlusterVolume) //$NON-NLS-1$
: new SearchParameters("Volumes: cluster.name=" + clusterName, SearchType.GlusterVolume); //$NON-NLS-1$
searchParameters.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParameters, aQuery);
}
public void getGlusterVolumeOptionInfoList(AsyncQuery aQuery, Guid clusterId) {
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeOptionsInfo, new GlusterParameters(clusterId), aQuery);
}
public void getHostFingerprint(AsyncQuery aQuery, String hostAddress) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetServerSSHKeyFingerprint, new ServerParameters(hostAddress), aQuery);
}
public void getHostPublicKey(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetServerSSHPublicKey, new VdcQueryParametersBase(), aQuery);
}
public void getGlusterHosts(AsyncQuery aQuery, String hostAddress, String rootPassword, String fingerprint) {
GlusterServersQueryParameters parameters = new GlusterServersQueryParameters(hostAddress, rootPassword);
parameters.setFingerprint(fingerprint);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterServersForImport,
parameters,
aQuery);
}
public void getClusterGlusterServices(AsyncQuery aQuery, Guid clusterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
// Passing empty values for Volume and Brick to get the services of all the volumes/hosts in the cluster
GlusterVolumeAdvancedDetailsParameters parameters =
new GlusterVolumeAdvancedDetailsParameters(clusterId, null, null, false); //$NON-NLS-1$ //$NON-NLS-2$
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeAdvancedDetails,
parameters,
aQuery);
}
public void getGlusterVolumeBrickDetails(AsyncQuery aQuery, Guid clusterId, Guid volumeId, Guid brickId) {
GlusterVolumeAdvancedDetailsParameters parameters =
new GlusterVolumeAdvancedDetailsParameters(clusterId, volumeId, brickId, true);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeAdvancedDetails,
parameters,
aQuery);
}
public void getGlusterHostsNewlyAdded(AsyncQuery aQuery, Guid clusterId, boolean isFingerprintRequired) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAddedGlusterServers,
new AddedGlusterServersParameters(clusterId, isFingerprintRequired),
aQuery);
}
public void isAnyHostUpInCluster(AsyncQuery aQuery, String clusterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null && !((List<?>) source).isEmpty()) {
return true;
}
return false;
}
};
getUpHostListByCluster(aQuery, clusterName, 1);
}
public void getGlusterHooks(AsyncQuery aQuery, Guid clusterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : new ArrayList<GlusterHookEntity>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterHooks, new GlusterParameters(clusterId), aQuery);
}
public void getGlusterBricksForServer(AsyncQuery aQuery, Guid serverId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : new ArrayList<GlusterBrickEntity>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeBricksByServerId, new IdQueryParameters(serverId), aQuery);
}
public void getGlusterHook(AsyncQuery aQuery, Guid hookId, boolean includeServerHooks) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterHookById,
new GlusterHookQueryParameters(hookId, includeServerHooks),
aQuery);
}
public void getGlusterHookContent(AsyncQuery aQuery, Guid hookId, Guid serverId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? source : ""; //$NON-NLS-1$
}
};
GlusterHookContentQueryParameters parameters = new GlusterHookContentQueryParameters(hookId);
parameters.setGlusterServerId(serverId);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterHookContent, parameters, aQuery);
}
public void getGlusterSwiftServices(AsyncQuery aQuery, Guid serverId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : new ArrayList<GlusterServerService>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterServerServicesByServerId, new GlusterServiceQueryParameters(serverId,
ServiceType.GLUSTER_SWIFT), aQuery);
}
public void getClusterGlusterSwiftService(AsyncQuery aQuery, Guid clusterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source != null) {
List<GlusterClusterService> serviceList = (List<GlusterClusterService>) source;
if (!serviceList.isEmpty()) {
return serviceList.get(0);
}
return null;
}
else {
return source;
}
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterClusterServiceByClusterId,
new GlusterServiceQueryParameters(clusterId,
ServiceType.GLUSTER_SWIFT), aQuery);
}
public void getGlusterSwiftServerServices(AsyncQuery aQuery, Guid clusterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? source : new ArrayList<GlusterServerService>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterServerServicesByClusterId,
new GlusterServiceQueryParameters(clusterId,
ServiceType.GLUSTER_SWIFT), aQuery);
}
public void getGlusterRebalanceStatus(AsyncQuery aQuery, Guid clusterId, Guid volumeId) {
aQuery.setHandleFailure(true);
GlusterVolumeQueriesParameters parameters = new GlusterVolumeQueriesParameters(clusterId, volumeId);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeRebalanceStatus, parameters, aQuery);
}
public void getGlusterVolumeProfilingStatistics(AsyncQuery aQuery, Guid clusterId, Guid volumeId, boolean nfs) {
aQuery.setHandleFailure(true);
GlusterVolumeProfileParameters parameters = new GlusterVolumeProfileParameters(clusterId, volumeId, nfs);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeProfileInfo, parameters, aQuery);
}
public void getGlusterRemoveBricksStatus(AsyncQuery aQuery,
Guid clusterId,
Guid volumeId,
List<GlusterBrickEntity> bricks) {
aQuery.setHandleFailure(true);
GlusterVolumeRemoveBricksQueriesParameters parameters =
new GlusterVolumeRemoveBricksQueriesParameters(clusterId, volumeId, bricks);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeRemoveBricksStatus, parameters, aQuery);
}
public void getRpmVersion(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.ProductRPMVersion);
tempVar.setVersion(getDefaultConfigurationVersion());
getConfigFromCache(tempVar, aQuery);
}
public void getUserMessageOfTheDayViaPublic(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
Frontend.getInstance().runPublicQuery(VdcQueryType.GetConfigurationValue,
new GetConfigurationValueParameters(ConfigurationValues.UserMessageOfTheDay,
getDefaultConfigurationVersion()),
aQuery);
}
public void getSearchResultsLimit(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 100;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.SearchResultsLimit,
getDefaultConfigurationVersion()),
aQuery);
}
public Map<Version, Map<String, String>> getCustomPropertiesList() {
return customPropertiesList;
}
public void getPermissionsByAdElementId(AsyncQuery aQuery, Guid userId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Permissions>) source
: new ArrayList<Permissions>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetPermissionsByAdElementId,
new IdQueryParameters(userId),
aQuery);
}
public void getRoleActionGroupsByRoleId(AsyncQuery aQuery, Guid roleId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<ActionGroup>) source
: new ArrayList<ActionGroup>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetRoleActionGroupsByRoleId,
new IdQueryParameters(roleId),
aQuery);
}
public void isTemplateNameUnique(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? !((Boolean) source).booleanValue() : false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.IsVmTemlateWithSameNameExist,
new NameQueryParameters(name),
aQuery);
}
public void isVmNameUnique(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? !((Boolean) source).booleanValue() : false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.IsVmWithSameNameExist, new NameQueryParameters(name), aQuery);
}
public void getDataCentersWithPermittedActionOnClusters(AsyncQuery aQuery, ActionGroup actionGroup,
final boolean supportsVirtService, final boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<StoragePool>();
}
return source;
}
};
GetDataCentersWithPermittedActionOnClustersParameters getDataCentersWithPermittedActionOnClustersParameters =
new GetDataCentersWithPermittedActionOnClustersParameters();
getDataCentersWithPermittedActionOnClustersParameters.setActionGroup(actionGroup);
getDataCentersWithPermittedActionOnClustersParameters.setSupportsVirtService(supportsVirtService);
getDataCentersWithPermittedActionOnClustersParameters.setSupportsGlusterService(supportsGlusterService);
Frontend.getInstance().runQuery(VdcQueryType.GetDataCentersWithPermittedActionOnClusters,
getDataCentersWithPermittedActionOnClustersParameters,
aQuery);
}
public void getClustersWithPermittedAction(AsyncQuery aQuery, ActionGroup actionGroup,
final boolean supportsVirtService, final boolean supportsGlusterService) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDSGroup> list = (ArrayList<VDSGroup>) source;
return getClusterByServiceList(list, supportsVirtService, supportsGlusterService);
}
return new ArrayList<VDSGroup>();
}
};
GetEntitiesWithPermittedActionParameters getEntitiesWithPermittedActionParameters =
new GetEntitiesWithPermittedActionParameters();
getEntitiesWithPermittedActionParameters.setActionGroup(actionGroup);
Frontend.getInstance().runQuery(VdcQueryType.GetClustersWithPermittedAction, getEntitiesWithPermittedActionParameters, aQuery);
}
public void getAllVmTemplates(AsyncQuery aQuery, final boolean refresh) {
aQuery.converterCallback = new TemplateConverter();
VdcQueryParametersBase params = new VdcQueryParametersBase();
params.setRefresh(refresh);
Frontend.getInstance().runQuery(VdcQueryType.GetAllVmTemplates, params, aQuery);
}
public void isUSBEnabledByDefault(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Boolean) source).booleanValue() : false;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.EnableUSBAsDefault,
getDefaultConfigurationVersion()),
aQuery);
}
public void getStorageConnectionById(AsyncQuery aQuery, String id, boolean isRefresh) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (StorageServerConnections) source : null;
}
};
StorageServerConnectionQueryParametersBase params = new StorageServerConnectionQueryParametersBase(id);
params.setRefresh(isRefresh);
Frontend.getInstance().runQuery(VdcQueryType.GetStorageServerConnectionById, params, aQuery);
}
public void getDataCentersByStorageDomain(AsyncQuery aQuery, Guid storageDomainId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<StoragePool>) source : null;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetStoragePoolsByStorageDomainId,
new IdQueryParameters(storageDomainId),
aQuery);
}
public void getDataCenterVersions(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<Version>();
}
else
{
ArrayList<Version> list = (ArrayList<Version>) source;
Collections.sort(list);
return list;
}
}
};
IdQueryParameters tempVar = new IdQueryParameters(dataCenterId);
Frontend.getInstance().runQuery(VdcQueryType.GetAvailableClusterVersionsByStoragePool, tempVar, aQuery);
}
public void getDataCenterMaxNameLength(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.StoragePoolNameSizeLimit,
getDefaultConfigurationVersion()),
aQuery);
}
public void getClusterServerMemoryOverCommit(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 0;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.MaxVdsMemOverCommitForServers,
getDefaultConfigurationVersion()),
aQuery);
}
public void getClusterDesktopMemoryOverCommit(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 0;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.MaxVdsMemOverCommit,
getDefaultConfigurationVersion()),
aQuery);
}
public void getAllowClusterWithVirtGlusterEnabled(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : Boolean.TRUE;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.AllowClusterWithVirtGlusterEnabled,
getDefaultConfigurationVersion()),
aQuery);
}
public void getCPUList(AsyncQuery aQuery, Version version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<ServerCpu>) source : new ArrayList<ServerCpu>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllServerCpuList, new GetAllServerCpuListParameters(version), aQuery);
}
public void getPmTypeList(AsyncQuery aQuery, Version version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<String> list = new ArrayList<String>();
if (source != null)
{
String[] array = ((String) source).split("[,]", -1); //$NON-NLS-1$
for (String item : array)
{
list.add(item);
}
}
return list;
}
};
GetConfigurationValueParameters param = new GetConfigurationValueParameters(ConfigurationValues.VdsFenceType);
param.setVersion(version != null ? version.toString() : getDefaultConfigurationVersion());
Frontend.getInstance().runQuery(VdcQueryType.GetFenceConfigurationValue, param, aQuery);
}
public void getPmOptions(AsyncQuery aQuery, String pmType, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
String pmtype = (String) _asyncQuery.data[0];
HashMap<String, ArrayList<String>> cachedPmMap =
new HashMap<String, ArrayList<String>>();
HashMap<String, HashMap<String, Object>> dict =
(HashMap<String, HashMap<String, Object>>) source;
for (Map.Entry<String, HashMap<String, Object>> pair : dict.entrySet())
{
ArrayList<String> list = new ArrayList<String>();
for (Map.Entry<String, Object> p : pair.getValue().entrySet())
{
list.add(p.getKey());
}
cachedPmMap.put(pair.getKey(), list);
}
return cachedPmMap.get(pmtype);
}
};
aQuery.setData(new Object[] { pmType });
Frontend.getInstance().runQuery(VdcQueryType.GetAgentFenceOptions, new GetAgentFenceOptionsQueryParameters(version), aQuery);
}
public void getNetworkList(AsyncQuery aQuery, Guid dataCenterId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Network>) source : new ArrayList<Network>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllNetworks, new IdQueryParameters(dataCenterId), aQuery);
}
public void getISOStorageDomainList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<StorageDomain> allStorageDomains =
(ArrayList<StorageDomain>) source;
ArrayList<StorageDomain> isoStorageDomains = new ArrayList<StorageDomain>();
for (StorageDomain storageDomain : allStorageDomains)
{
if (storageDomain.getStorageDomainType() == StorageDomainType.ISO)
{
isoStorageDomains.add(storageDomain);
}
}
return isoStorageDomains;
}
return new ArrayList<StorageDomain>();
}
};
SearchParameters searchParams = new SearchParameters("Storage:", SearchType.StorageDomain); //$NON-NLS-1$
searchParams.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParams, aQuery);
}
public void getStorageDomainList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<StorageDomain>) source
: new ArrayList<StorageDomain>();
}
};
SearchParameters searchParams = new SearchParameters("Storage:", SearchType.StorageDomain); //$NON-NLS-1$
searchParams.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParams, aQuery);
}
public void getLocalStorageHost(AsyncQuery aQuery, String dataCenterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
for (IVdcQueryable item : (ArrayList<IVdcQueryable>) source)
{
return item;
}
}
return null;
}
};
SearchParameters sp = new SearchParameters("hosts: datacenter=" + dataCenterName, SearchType.VDS); //$NON-NLS-1$
Frontend.getInstance().runQuery(VdcQueryType.Search, sp, aQuery);
}
public void getStorageDomainsByConnection(AsyncQuery aQuery, Guid storagePoolId, String connectionPath) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<StorageDomain>) source : null;
}
};
GetStorageDomainsByConnectionParameters param = new GetStorageDomainsByConnectionParameters();
param.setConnection(connectionPath);
if (storagePoolId != null) {
param.setStoragePoolId(storagePoolId);
}
Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByConnection, param, aQuery);
}
public void getExistingStorageDomainList(AsyncQuery aQuery,
Guid hostId,
StorageDomainType domainType,
StorageType storageType,
String path) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<StorageDomain>) source : null;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetExistingStorageDomainList, new GetExistingStorageDomainListParameters(hostId,
storageType,
domainType,
path), aQuery);
}
public void getStorageDomainMaxNameLength(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 1;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.StorageDomainNameSizeLimit,
getDefaultConfigurationVersion()),
aQuery);
}
public void isStorageDomainNameUnique(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<StorageDomain> storageDomains = (ArrayList<StorageDomain>) source;
return storageDomains.isEmpty();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search, new SearchParameters("Storage: name=" + name, //$NON-NLS-1$
SearchType.StorageDomain), aQuery);
}
public void getNetworkConnectivityCheckTimeoutInSeconds(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Integer) source).intValue() : 120;
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.NetworkConnectivityCheckTimeoutInSeconds,
getDefaultConfigurationVersion()),
aQuery);
}
public void getMaxSpmPriority(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? ((Integer) source).intValue() : 0;
}
};
// GetConfigFromCache(
// new GetConfigurationValueParameters(ConfigurationValues.HighUtilizationForPowerSave,
// getDefaultConfigurationVersion()),
// aQuery);
aQuery.asyncCallback.onSuccess(aQuery.getModel(), 10);
}
public void getDefaultSpmPriority(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
return source != null ? ((Integer) source).intValue() : 0;
}
};
// GetConfigFromCache(
// new GetConfigurationValueParameters(ConfigurationValues.HighUtilizationForPowerSave,
// getDefaultConfigurationVersion()),
// aQuery);
aQuery.asyncCallback.onSuccess(aQuery.getModel(), 5);
}
public void getDefaultPmProxyPreferences(AsyncQuery query) {
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.FenceProxyDefaultPreferences,
getDefaultConfigurationVersion()),
query);
}
public void getRootTag(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
Tags tag = (Tags) source;
Tags root =
new Tags(tag.getdescription(),
tag.getparent_id(),
tag.getIsReadonly(),
tag.gettag_id(),
tag.gettag_name());
if (tag.getChildren() != null)
{
fillTagsRecursive(root, tag.getChildren());
}
return root;
}
return new Tags();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetRootTag, new VdcQueryParametersBase(), aQuery);
}
private void setAttachedTagsConverter(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<Tags> ret = new ArrayList<Tags>();
for (Tags tags : (ArrayList<Tags>) source)
{
if (tags.gettype() == TagsType.GeneralTag)
{
ret.add(tags);
}
}
return ret;
}
return new Tags();
}
};
}
public void getAttachedTagsToVm(AsyncQuery aQuery, Guid id) {
setAttachedTagsConverter(aQuery);
Frontend.getInstance().runQuery(VdcQueryType.GetTagsByVmId, new GetTagsByVmIdParameters(id.toString()), aQuery);
}
public void getAttachedTagsToUser(AsyncQuery aQuery, Guid id) {
setAttachedTagsConverter(aQuery);
Frontend.getInstance().runQuery(VdcQueryType.GetTagsByUserId, new GetTagsByUserIdParameters(id.toString()), aQuery);
}
public void getAttachedTagsToUserGroup(AsyncQuery aQuery, Guid id) {
setAttachedTagsConverter(aQuery);
Frontend.getInstance().runQuery(VdcQueryType.GetTagsByUserGroupId, new GetTagsByUserGroupIdParameters(id.toString()), aQuery);
}
public void getAttachedTagsToHost(AsyncQuery aQuery, Guid id) {
setAttachedTagsConverter(aQuery);
Frontend.getInstance().runQuery(VdcQueryType.GetTagsByVdsId, new GetTagsByVdsIdParameters(id.toString()), aQuery);
}
public void getoVirtISOsList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<RpmVersion>((ArrayList<RpmVersion>) source)
: new ArrayList<RpmVersion>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetoVirtISOs, new VdsIdParametersBase(id), aQuery);
}
public void getLunsByVgId(AsyncQuery aQuery, String vgId, Guid vdsId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<LUNs>) source : new ArrayList<LUNs>();
}
};
GetLunsByVgIdParameters params = new GetLunsByVgIdParameters(vgId, vdsId);
Frontend.getInstance().runQuery(VdcQueryType.GetLunsByVgId, params, aQuery);
}
public void getAllTemplatesFromExportDomain(AsyncQuery aQuery, Guid storagePoolId, Guid storageDomainId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? source : new HashMap<VmTemplate, ArrayList<DiskImage>>();
}
};
GetAllFromExportDomainQueryParameters getAllFromExportDomainQueryParamenters =
new GetAllFromExportDomainQueryParameters(storagePoolId, storageDomainId);
Frontend.getInstance().runQuery(VdcQueryType.GetTemplatesFromExportDomain, getAllFromExportDomainQueryParamenters, aQuery);
}
public void getUpHostListByCluster(AsyncQuery aQuery, String clusterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
ArrayList<VDS> list = Linq.<VDS> cast((ArrayList<IVdcQueryable>) source);
return list;
}
return new ArrayList<VDS>();
}
};
getUpHostListByCluster(aQuery, clusterName, null);
}
public void getUpHostListByCluster(AsyncQuery aQuery, String clusterName, Integer maxCount) {
SearchParameters searchParameters =
new SearchParameters("Host: cluster = " + clusterName + " and status = up", SearchType.VDS); //$NON-NLS-1$ //$NON-NLS-2$
if (maxCount != null) {
searchParameters.setMaxCount(maxCount);
}
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParameters, aQuery);
}
public void getVmNicList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<VmNetworkInterface>((ArrayList<VmNetworkInterface>) source)
: new ArrayList<VmNetworkInterface>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmInterfacesByVmId, new IdQueryParameters(id), aQuery);
}
public void getTemplateNicList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? new ArrayList<VmNetworkInterface>((ArrayList<VmNetworkInterface>) source)
: new ArrayList<VmNetworkInterface>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetTemplateInterfacesByTemplateId, new IdQueryParameters(id), aQuery);
}
public void getVmSnapshotList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Snapshot>) source : new ArrayList<Snapshot>();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllVmSnapshotsByVmId, new IdQueryParameters(id), aQuery);
}
public void getVmsRunningOnOrMigratingToVds(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source == null) {
return new ArrayList<VM>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmsRunningOnOrMigratingToVds,
new IdQueryParameters(id),
aQuery);
}
public void getVmDiskList(AsyncQuery aQuery, Guid id) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<Disk> list = new ArrayList<Disk>();
if (source != null)
{
Iterable listEnumerable = (Iterable) source;
Iterator listIterator = listEnumerable.iterator();
while (listIterator.hasNext())
{
list.add((Disk) listIterator.next());
}
}
return list;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllDisksByVmId, new IdQueryParameters(id), aQuery);
}
public void getVmList(AsyncQuery aQuery, String poolName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<VM> vms = Linq.<VM> cast((ArrayList<IVdcQueryable>) source);
return vms;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search, new SearchParameters("Vms: pool=" + poolName, SearchType.VM), aQuery); //$NON-NLS-1$
}
public void getVmListByClusterName(AsyncQuery aQuery, String clusterName) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<VM> vms = Linq.<VM> cast((ArrayList<IVdcQueryable>) source);
return vms;
}
};
Frontend.getInstance().runQuery(VdcQueryType.Search,
new SearchParameters("Vms: cluster=" + clusterName, SearchType.VM), aQuery); //$NON-NLS-1$
}
public void getDiskList(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<DiskImage>) source : new ArrayList<DiskImage>();
}
};
SearchParameters searchParams = new SearchParameters("Disks:", SearchType.Disk); //$NON-NLS-1$
searchParams.setMaxCount(9999);
Frontend.getInstance().runQuery(VdcQueryType.Search, searchParams, aQuery);
}
public void getNextAvailableDiskAliasNameByVMId(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetNextAvailableDiskAliasNameByVMId,
new IdQueryParameters(vmId),
aQuery);
}
public void isPoolNameUnique(AsyncQuery aQuery, String name) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source != null)
{
return !(Boolean) source;
}
return false;
}
};
Frontend.getInstance().runQuery(VdcQueryType.IsVmPoolWithSameNameExists,
new NameQueryParameters(name),
aQuery);
}
public void getVmConfigurationBySnapshot(AsyncQuery aQuery, Guid snapshotSourceId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (VM) source : null;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmConfigurationBySnapshot,
new IdQueryParameters(snapshotSourceId).withoutRefresh(),
aQuery);
}
public void getAllAttachableDisks(AsyncQuery aQuery, Guid storagePoolId, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Disk>) source : new ArrayList<Disk>();
}
};
GetAllAttachableDisks params = new GetAllAttachableDisks(storagePoolId);
params.setVmId(vmId);
Frontend.getInstance().runQuery(VdcQueryType.GetAllAttachableDisks, params, aQuery);
}
public void getPermittedStorageDomainsByStoragePoolId(AsyncQuery aQuery,
Guid dataCenterId,
ActionGroup actionGroup) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new java.util.ArrayList<StorageDomain>();
}
return source;
}
};
GetPermittedStorageDomainsByStoragePoolIdParameters params =
new GetPermittedStorageDomainsByStoragePoolIdParameters();
params.setStoragePoolId(dataCenterId);
params.setActionGroup(actionGroup);
Frontend.getInstance().runQuery(VdcQueryType.GetPermittedStorageDomainsByStoragePoolId, params, aQuery);
}
public void getAllDataCenterNetworks(AsyncQuery aQuery, Guid storagePoolId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (ArrayList<Network>) source : new ArrayList<Network>();
}
};
IdQueryParameters params = new IdQueryParameters(storagePoolId);
Frontend.getInstance().runQuery(VdcQueryType.GetNetworksByDataCenterId, params, aQuery);
}
public void getStorageConnectionsByDataCenterIdAndStorageType(AsyncQuery aQuery,
Guid storagePoolId,
StorageType storageType) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
GetConnectionsByDataCenterAndStorageTypeParameters params = new GetConnectionsByDataCenterAndStorageTypeParameters(storagePoolId, storageType);
Frontend.getInstance().runQuery(VdcQueryType.GetConnectionsByDataCenterAndStorageType, params, aQuery);
}
public void getRedirectServletReportsPage(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? (String) source : ""; //$NON-NLS-1$
}
};
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.RedirectServletReportsPage,
getDefaultConfigurationVersion()),
aQuery);
}
private HashMap<VdcActionType, CommandVersionsInfo> cachedCommandsCompatibilityVersions;
public void isCommandCompatible(AsyncQuery aQuery, final VdcActionType vdcActionType,
final Version cluster, final Version dc) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
cachedCommandsCompatibilityVersions = (HashMap<VdcActionType, CommandVersionsInfo>) source;
return isCommandCompatible(vdcActionType, cluster, dc);
}
};
if (cachedCommandsCompatibilityVersions != null) {
aQuery.asyncCallback.onSuccess(aQuery.getModel(), isCommandCompatible(vdcActionType, cluster, dc));
} else {
Frontend.getInstance().runQuery(VdcQueryType.GetCommandsCompatibilityVersions,
new VdcQueryParametersBase().withoutRefresh(), aQuery);
}
}
private boolean isCommandCompatible(VdcActionType vdcActionType, Version cluster, Version dc) {
if (cachedCommandsCompatibilityVersions == null || cluster == null || dc == null) {
return false;
}
CommandVersionsInfo commandVersionsInfo = cachedCommandsCompatibilityVersions.get(vdcActionType);
if (commandVersionsInfo == null) {
return false;
}
Version clusterCompatibility = commandVersionsInfo.getClusterVersion();
Version dcCompatibility = commandVersionsInfo.getStoragePoolVersion();
return (clusterCompatibility.compareTo(cluster) <= 0)
&& (dcCompatibility.compareTo(dc) <= 0);
}
public CommandVersionsInfo getCommandVersionsInfo(VdcActionType vdcActionType) {
if (cachedCommandsCompatibilityVersions == null) {
return null;
}
return cachedCommandsCompatibilityVersions.get(vdcActionType);
}
/**
* Get the Management Network Name
*
* @param aQuery
* result callback
*/
public void getManagementNetworkName(AsyncQuery aQuery) {
getConfigFromCache(
new GetConfigurationValueParameters(ConfigurationValues.ManagementNetwork,
getDefaultConfigurationVersion()),
aQuery);
}
/**
* Cache configuration values [raw (not converted) values from vdc_options table].
*/
private void cacheConfigValues(AsyncQuery aQuery) {
getDefaultConfigurationVersion();
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object returnValue, AsyncQuery _asyncQuery)
{
if (returnValue != null) {
cachedConfigValuesPreConvert.putAll((HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object>) returnValue);
}
return cachedConfigValuesPreConvert;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetConfigurationValues, new VdcQueryParametersBase(), aQuery);
}
/**
* Get configuration value from 'cachedConfigValuesPreConvert' (raw values from vdc_options table).
*
* @param version
*/
public Object getConfigValuePreConverted(ConfigurationValues configValue, String version) {
KeyValuePairCompat<ConfigurationValues, String> key =
new KeyValuePairCompat<ConfigurationValues, String>(configValue, version);
return cachedConfigValuesPreConvert.get(key);
}
/**
* Get configuration value from 'cachedConfigValuesPreConvert' (raw values from vdc_options table).
*/
public Object getConfigValuePreConverted(ConfigurationValues configValue) {
KeyValuePairCompat<ConfigurationValues, String> key =
new KeyValuePairCompat<ConfigurationValues, String>(configValue, getDefaultConfigurationVersion());
return cachedConfigValuesPreConvert.get(key);
}
/**
* Get configuration value from using a specified converter.
*/
public Object getConfigValue(ConfigurationValues configValue, String version, IAsyncConverter converter) {
if (converter == null) {
return null;
}
KeyValuePairCompat<ConfigurationValues, String> key =
new KeyValuePairCompat<ConfigurationValues, String>(configValue, version);
return converter.Convert(cachedConfigValuesPreConvert.get(key), null);
}
/**
* method to get an item from config while caching it (config is not supposed to change during a session)
*
* @param aQuery
* an async query
* @param parameters
* a converter for the async query
*/
public void getConfigFromCache(GetConfigurationValueParameters parameters, AsyncQuery aQuery) {
// cache key
final KeyValuePairCompat<ConfigurationValues, String> config_key =
new KeyValuePairCompat<ConfigurationValues, String>(parameters.getConfigValue(),
parameters.getVersion());
Object returnValue = null;
if (cachedConfigValues.containsKey(config_key)) {
// cache hit
returnValue = cachedConfigValues.get(config_key);
}
// cache miss: convert configuration value using query's converter
// and call asyncCallback's onSuccess
else if (cachedConfigValuesPreConvert.containsKey(config_key)) {
returnValue = cachedConfigValuesPreConvert.get(config_key);
// run converter
if (aQuery.converterCallback != null) {
returnValue = aQuery.converterCallback.Convert(returnValue, aQuery);
}
if (returnValue != null) {
cachedConfigValues.put(config_key, returnValue);
}
}
aQuery.asyncCallback.onSuccess(aQuery.getModel(), returnValue);
}
/**
* method to get an item from config while caching it (config is not supposed to change during a session)
*
* @param configValue
* the config value to query
* @param version
* the compatibility version to query
* @param aQuery
* an async query
*/
public void getConfigFromCache(ConfigurationValues configValue, String version, AsyncQuery aQuery) {
GetConfigurationValueParameters parameters = new GetConfigurationValueParameters(configValue, version);
getConfigFromCache(parameters, aQuery);
}
public ArrayList<QuotaEnforcementTypeEnum> getQuotaEnforcmentTypes() {
return new ArrayList<QuotaEnforcementTypeEnum>(Arrays.asList(new QuotaEnforcementTypeEnum[] {
QuotaEnforcementTypeEnum.DISABLED,
QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT,
QuotaEnforcementTypeEnum.HARD_ENFORCEMENT }));
}
public void clearCache() {
cachedConfigValues.clear();
}
private class TemplateConverter implements IAsyncConverter {
@Override
public Object Convert(Object source, AsyncQuery asyncQuery) {
List<VmTemplate> list = new ArrayList<VmTemplate>();
if (source != null) {
VmTemplate blankTemplate = null;
for (VmTemplate template : (List<VmTemplate>) source) {
if (template.getId().equals(Guid.Empty)) {
blankTemplate = template;
} else if (template.getStatus() == VmTemplateStatus.OK) {
list.add(template);
}
}
Collections.sort(list, new NameableComparator());
if (blankTemplate != null) {
list.add(0, blankTemplate);
}
}
return list;
}
}
public void getInterfaceOptionsForEditNetwork(final AsyncQuery asyncQuery,
final ArrayList<VdsNetworkInterface> interfaceList,
final VdsNetworkInterface originalInterface,
Network networkToEdit,
final Guid vdsID,
final StringBuilder defaultInterfaceName)
{
final ArrayList<VdsNetworkInterface> ifacesOptions = new ArrayList<VdsNetworkInterface>();
for (VdsNetworkInterface i : interfaceList)
{
if (StringHelper.isNullOrEmpty(i.getNetworkName()) && StringHelper.isNullOrEmpty(i.getBondName()))
{
ifacesOptions.add(i);
}
}
if (originalInterface.getVlanId() == null) // no vlan:
{
// Filter out the Interfaces that have child vlan Interfaces
getAllChildVlanInterfaces(vdsID, ifacesOptions, new IFrontendMultipleQueryAsyncCallback() {
@Override
public void executed(FrontendMultipleQueryAsyncResult result) {
ArrayList<VdsNetworkInterface> ifacesOptionsTemp = new ArrayList<VdsNetworkInterface>();
List<VdcQueryReturnValue> returnValueList = result.getReturnValues();
for (int i = 0; i < returnValueList.size(); i++)
{
VdcQueryReturnValue returnValue = returnValueList.get(i);
if (returnValue != null && returnValue.getSucceeded() && returnValue.getReturnValue() != null)
{
ArrayList<VdsNetworkInterface> childVlanInterfaces =
returnValue.getReturnValue();
if (childVlanInterfaces.size() == 0)
{
ifacesOptionsTemp.add(ifacesOptions.get(i));
}
}
}
ifacesOptions.clear();
ifacesOptions.addAll(ifacesOptionsTemp);
if (originalInterface.getBonded() != null && originalInterface.getBonded())
{
// eth0 -- \
// |---> bond0 -> <networkToEdit>
// eth1 -- /
// ---------------------------------------
// - originalInterface: 'bond0'
// --> We want to add 'eth0' and and 'eth1' as optional Interfaces
// (note that choosing one of them will break the bond):
for (VdsNetworkInterface i : interfaceList)
{
if (ObjectUtils.objectsEqual(i.getBondName(), originalInterface.getName()))
{
ifacesOptions.add(i);
}
}
}
// add the original interface as an option and set it as the default option:
ifacesOptions.add(originalInterface);
defaultInterfaceName.append(originalInterface.getName());
asyncQuery.asyncCallback.onSuccess(asyncQuery.model, ifacesOptions);
}
});
}
else // vlan:
{
getVlanParentInterface(vdsID, originalInterface, new AsyncQuery(asyncQuery, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
final VdsNetworkInterface vlanParent = (VdsNetworkInterface) returnValue;
if (vlanParent != null && vlanParent.getBonded() != null && vlanParent.getBonded()) {
interfaceHasSiblingVlanInterfaces(vdsID, originalInterface, new AsyncQuery(asyncQuery,
new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
Boolean interfaceHasSiblingVlanInterfaces = (Boolean) returnValue;
if (!interfaceHasSiblingVlanInterfaces) {
// eth0 -- \
// |--- bond0 ---> bond0.3 -> <networkToEdit>
// eth1 -- /
// ---------------------------------------------------
// - originalInterface: 'bond0.3'
// - vlanParent: 'bond0'
// - 'bond0.3' has no vlan siblings
// --> We want to add 'eth0' and and 'eth1' as optional Interfaces.
// (note that choosing one of them will break the bond):
// ifacesOptions.AddRange(interfaceList.Where(a => a.bond_name ==
// vlanParent.name).ToList());
for (VdsNetworkInterface i : interfaceList) {
if (ObjectUtils.objectsEqual(i.getBondName(), vlanParent.getName())) {
ifacesOptions.add(i);
}
}
}
// the vlanParent should already be in ifacesOptions
// (since it has no network_name or bond_name).
defaultInterfaceName.append(vlanParent.getName());
asyncQuery.asyncCallback.onSuccess(asyncQuery.model, ifacesOptions);
}
}));
} else {
// the vlanParent should already be in ifacesOptions
// (since it has no network_name or bond_name).
if (vlanParent != null)
defaultInterfaceName.append(vlanParent.getName());
asyncQuery.asyncCallback.onSuccess(asyncQuery.model, ifacesOptions);
}
}
}));
}
}
private void getVlanParentInterface(Guid vdsID, VdsNetworkInterface iface, AsyncQuery aQuery)
{
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVlanParent, new InterfaceAndIdQueryParameters(vdsID,
iface), aQuery);
}
private void interfaceHasSiblingVlanInterfaces(Guid vdsID, VdsNetworkInterface iface, AsyncQuery aQuery)
{
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
ArrayList<VdsNetworkInterface> siblingVlanInterfaces = (ArrayList<VdsNetworkInterface>) source;
return !siblingVlanInterfaces.isEmpty();
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllSiblingVlanInterfaces,
new InterfaceAndIdQueryParameters(vdsID, iface), aQuery);
}
public void getExternalProviderHostList(AsyncQuery aQuery,
Guid providerId,
boolean filterOutExistingHosts,
String searchFilter) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<VDS>();
}
return source;
}
};
GetHostListFromExternalProviderParameters params = new GetHostListFromExternalProviderParameters();
params.setFilterOutExistingHosts(filterOutExistingHosts);
params.setProviderId(providerId);
params.setSearchFilter(searchFilter);
Frontend.getInstance().runQuery(VdcQueryType.GetHostListFromExternalProvider,
params,
aQuery);
}
public void getExternalProviderDiscoveredHostList(AsyncQuery aQuery, Provider provider) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<ExternalDiscoveredHost>();
}
return source;
}
};
ProviderQueryParameters params = new ProviderQueryParameters();
params.setProvider(provider);
Frontend.getInstance().runQuery(VdcQueryType.GetDiscoveredHostListFromExternalProvider, params, aQuery);
}
public void getExternalProviderHostGroupList(AsyncQuery aQuery, Provider provider) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<ExternalHostGroup>();
}
return source;
}
};
ProviderQueryParameters params = new ProviderQueryParameters();
params.setProvider(provider);
Frontend.getInstance().runQuery(VdcQueryType.GetHostGroupsFromExternalProvider, params, aQuery);
}
public void getExternalProviderComputeResourceList(AsyncQuery aQuery, Provider provider) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<ExternalComputeResource>();
}
return source;
}
};
ProviderQueryParameters params = new ProviderQueryParameters();
params.setProvider(provider);
Frontend.getInstance().runQuery(VdcQueryType.GetComputeResourceFromExternalProvider, params, aQuery);
}
public void getAllProviders(AsyncQuery aQuery) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<Provider>();
}
Collections.sort((List<Provider>) source, new NameableComparator());
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllProviders, new GetAllProvidersParameters(), aQuery);
}
public void getAllProvidersByProvidedEntity(AsyncQuery query, final VdcObjectType providedEntity) {
query.converterCallback = new IAsyncConverter<List<Provider>>() {
@Override
public List<Provider> Convert(Object returnValue, AsyncQuery asyncQuery) {
if (returnValue == null) {
return new ArrayList<Provider>();
}
List<Provider> providers =
Linq.toList(Linq.filterProvidersByProvidedType((Collection<Provider>) returnValue, providedEntity));
Collections.sort(providers, new NameableComparator());
return providers;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllProviders, new GetAllProvidersParameters(), query);
}
public void getAllNetworkProviders(AsyncQuery query) {
getAllProvidersByProvidedEntity(query, VdcObjectType.Network);
}
public void getAllProvidersByType(AsyncQuery aQuery, ProviderType providerType) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null) {
return new ArrayList<Provider>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllProviders, new GetAllProvidersParameters(providerType), aQuery);
}
public void getProviderCertificateChain(AsyncQuery aQuery, Provider provider) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetProviderCertificateChain, new ProviderQueryParameters(provider), aQuery);
}
private void getAllChildVlanInterfaces(Guid vdsID,
List<VdsNetworkInterface> ifaces,
IFrontendMultipleQueryAsyncCallback callback)
{
ArrayList<VdcQueryParametersBase> parametersList = new ArrayList<VdcQueryParametersBase>();
ArrayList<VdcQueryType> queryTypeList = new ArrayList<VdcQueryType>();
for (final VdsNetworkInterface iface : ifaces)
{
queryTypeList.add(VdcQueryType.GetAllChildVlanInterfaces);
parametersList.add(new InterfaceAndIdQueryParameters(vdsID, iface));
}
Frontend.getInstance().runMultipleQueries(queryTypeList, parametersList, callback);
}
public void isSupportBridgesReportByVDSM(AsyncQuery aQuery, String version) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
return source != null ? ((Boolean) source).booleanValue() : true;
}
};
GetConfigurationValueParameters tempVar =
new GetConfigurationValueParameters(ConfigurationValues.SupportBridgesReportByVDSM);
tempVar.setVersion(version);
getConfigFromCache(tempVar, aQuery);
}
public void fillTagsRecursive(Tags tagToFill, List<Tags> children)
{
ArrayList<Tags> list = new ArrayList<Tags>();
for (Tags tag : children)
{
// tags child = new tags(tag.description, tag.parent_id, tag.IsReadonly, tag.tag_id, tag.tag_name);
if (tag.gettype() == TagsType.GeneralTag)
{
list.add(tag);
if (tag.getChildren() != null)
{
fillTagsRecursive(tag, tag.getChildren());
}
}
}
tagToFill.setChildren(list);
}
public ArrayList<EventNotificationEntity> getEventNotificationTypeList()
{
ArrayList<EventNotificationEntity> ret = new ArrayList<EventNotificationEntity>();
// TODO: We can translate it here too
for (EventNotificationEntity entity : EventNotificationEntity.values()) {
if (entity != EventNotificationEntity.UNKNOWN) {
ret.add(entity);
}
}
return ret;
}
public Map<EventNotificationEntity, HashSet<AuditLogType>> getAvailableNotificationEvents() {
return VdcEventNotificationUtils.getNotificationEvents();
}
public void getNicTypeList(final int osId, Version version, AsyncQuery asyncQuery) {
final INewAsyncCallback chainedCallback = asyncQuery.asyncCallback;
asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ArrayList<String> nics = ((VdcQueryReturnValue) returnValue).getReturnValue();
List<VmInterfaceType> interfaceTypes = new ArrayList<VmInterfaceType>();
for (String nic : nics) {
try {
interfaceTypes.add(VmInterfaceType.valueOf(nic));
} catch (IllegalArgumentException e) {
// ignore if we can't find the enum value.
}
}
chainedCallback.onSuccess(model, interfaceTypes);
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository,
new OsQueryParameters(OsRepositoryVerb.GetNetworkDevices, osId, version),
asyncQuery);
}
public VmInterfaceType getDefaultNicType(Collection<VmInterfaceType> items)
{
if (items == null || items.isEmpty()) {
return null;
} else if (items.contains(VmInterfaceType.pv)) {
return VmInterfaceType.pv;
} else {
return items.iterator().next();
}
}
public boolean isVersionMatchStorageType(Version version, boolean isLocalType) {
return version.compareTo(new Version(3, 0)) >= 0;
}
public int getClusterDefaultMemoryOverCommit() {
return 100;
}
public boolean getClusterDefaultCountThreadsAsCores() {
return false;
}
public ArrayList<VolumeType> getVolumeTypeList() {
return new ArrayList<VolumeType>(Arrays.asList(new VolumeType[] {
VolumeType.Preallocated,
VolumeType.Sparse
}));
}
public ArrayList<StorageType> getStorageTypeList()
{
return new ArrayList<StorageType>(Arrays.asList(new StorageType[] {
StorageType.ISCSI,
StorageType.FCP
}));
}
public void getDiskInterfaceList(int osId, Version clusterVersion, AsyncQuery asyncQuery)
{
final INewAsyncCallback chainedCallback = asyncQuery.asyncCallback;
asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ArrayList<String> interfaces = ((VdcQueryReturnValue) returnValue).getReturnValue();
List<DiskInterface> interfaceTypes = new ArrayList<DiskInterface>();
for (String diskIfs : interfaces) {
try {
interfaceTypes.add(DiskInterface.valueOf(diskIfs));
} catch (IllegalArgumentException e) {
// ignore if we can't find the enum value.
}
}
chainedCallback.onSuccess(model, interfaceTypes);
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository,
new OsQueryParameters(OsRepositoryVerb.GetDiskInterfaces, osId, clusterVersion),
asyncQuery);
}
public ArrayList<DiskInterface> getDiskInterfaceList()
{
ArrayList<DiskInterface> diskInterfaces = new ArrayList<DiskInterface>(
Arrays.asList(new DiskInterface[] {
DiskInterface.IDE,
DiskInterface.VirtIO,
DiskInterface.VirtIO_SCSI,
DiskInterface.SPAPR_VSCSI
}));
return diskInterfaces;
}
public String getNewNicName(Collection<VmNetworkInterface> existingInterfaces)
{
int maxIfaceNumber = 0;
if (existingInterfaces != null)
{
for (VmNetworkInterface iface : existingInterfaces)
{
// name of Interface is "eth<n>" (<n>: integer).
if (iface.getName().length() > 3) {
final Integer ifaceNumber = IntegerCompat.tryParse(iface.getName().substring(3));
if (ifaceNumber != null && ifaceNumber > maxIfaceNumber) {
maxIfaceNumber = ifaceNumber;
}
}
}
}
return "nic" + (maxIfaceNumber + 1); //$NON-NLS-1$
}
/**
* Gets a value composed of "[string1]+[string2]+..." and returns "[string1Translated]+[string2Translated]+..."
*
* @param complexValue
* string in the form of "[string1]+[string2]+..."
* @return string in the form of "[string1Translated]+[string2Translated]+..."
*/
public String getComplexValueFromSpiceRedKeysResource(String complexValue) {
if (StringHelper.isNullOrEmpty(complexValue)) {
return ""; //$NON-NLS-1$
}
ArrayList<String> values = new ArrayList<String>();
for (String s : complexValue.split("[+]", -1)) { //$NON-NLS-1$
try {
String value =
SpiceConstantsManager.getInstance()
.getSpiceRedKeys()
.getString(s.replaceAll("-", "_")); //$NON-NLS-1$ //$NON-NLS-2$
values.add(value);
} catch (MissingResourceException e) {
values.add(s);
}
}
return StringHelper.join("+", values.toArray(new String[] {})); //$NON-NLS-1$
}
public Guid getEntityGuid(Object entity)
{
if (entity instanceof VM)
{
return ((VM) entity).getId();
}
else if (entity instanceof StoragePool)
{
return ((StoragePool) entity).getId();
}
else if (entity instanceof VDSGroup)
{
return ((VDSGroup) entity).getId();
}
else if (entity instanceof VDS)
{
return ((VDS) entity).getId();
}
else if (entity instanceof StorageDomain)
{
return ((StorageDomain) entity).getId();
}
else if (entity instanceof VmTemplate)
{
return ((VmTemplate) entity).getId();
}
else if (entity instanceof VmPool)
{
return ((VmPool) entity).getVmPoolId();
}
else if (entity instanceof DbUser)
{
return ((DbUser) entity).getId();
}
else if (entity instanceof DbGroup)
{
return ((DbGroup) entity).getId();
}
else if (entity instanceof Quota)
{
return ((Quota) entity).getId();
}
else if (entity instanceof DiskImage)
{
return ((DiskImage) entity).getId();
}
else if (entity instanceof GlusterVolumeEntity)
{
return ((GlusterVolumeEntity) entity).getId();
}
else if (entity instanceof Network)
{
return ((Network) entity).getId();
}
else if (entity instanceof VnicProfile)
{
return ((VnicProfile) entity).getId();
}
return Guid.Empty;
}
public boolean isWindowsOsType(Integer osType) {
// can be null as a consequence of setItems on ListModel
if (osType == null) {
return false;
}
return windowsOsIds.contains(osType);
}
public boolean isLinuxOsType(Integer osId) {
// can be null as a consequence of setItems on ListModel
if (osId == null) {
return false;
}
return linuxOsIds.contains(osId);
}
public void initWindowsOsTypes() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
windowsOsIds = (ArrayList<Integer>) ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetWindowsOss), callback);
}
public void initLinuxOsTypes() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
linuxOsIds = (ArrayList<Integer>) ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetLinuxOss), callback);
}
public void initUniqueOsNames() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
uniqueOsNames = ((VdcQueryReturnValue) returnValue).getReturnValue();
// Initialize specific UI dependencies for search
SimpleDependecyInjector.getInstance().bind(new OsValueAutoCompleter(uniqueOsNames));
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetUniqueOsNames), callback);
}
public void initOsNames() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
osNames = ((VdcQueryReturnValue) returnValue).getReturnValue();
initOsIds();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetOsNames), callback);
}
private void initOsIds() {
osIds = new ArrayList<Integer>(osNames.keySet());
Collections.sort(osIds, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return osNames.get(o1).compareTo(osNames.get(o2));
}
});
}
public void initOsArchitecture() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
osArchitectures = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetOsArchitectures), callback);
}
public boolean osNameExists(Integer osId) {
return osNames.keySet().contains(osId);
}
public String getOsName(Integer osId) {
// can be null as a consequence of setItems on ListModel
if (osId == null) {
return "";
}
return osNames.get(osId);
}
public boolean hasSpiceSupport(int osId, Version version) {
return getDisplayTypes(osId, version).contains(DisplayType.qxl);
}
public List<DisplayType> getDisplayTypes(int osId, Version version) {
return displayTypes.get(osId).get(version);
}
private void initDisplayTypes() {
AsyncQuery callback = new AsyncQuery();
callback.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
displayTypes = ((VdcQueryReturnValue) returnValue).getReturnValue();
}
};
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(OsRepositoryVerb.GetDisplayTypes), callback);
}
public List<Integer> getOsIds(ArchitectureType architectureType) {
List<Integer> osIds = new ArrayList<Integer>();
for (Entry<Integer, ArchitectureType> entry : osArchitectures.entrySet()) {
if (entry.getValue() == architectureType) {
osIds.add(entry.getKey());
}
}
Collections.sort(osIds, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return osNames.get(o1).compareTo(osNames.get(o2));
}
});
return osIds;
}
public void getOsMaxRam(int osId, Version version, AsyncQuery asyncQuery) {
Frontend.getInstance().runQuery(VdcQueryType.OsRepository,
new OsQueryParameters(OsRepositoryVerb.GetMaxOsRam, osId, version),
asyncQuery);
}
public void getVmWatchdogTypes(int osId, Version version,
AsyncQuery asyncQuery) {
Frontend.getInstance().runQuery(VdcQueryType.OsRepository, new OsQueryParameters(
OsRepositoryVerb.GetVmWatchdogTypes, osId, version), asyncQuery);
}
public ArrayList<Map.Entry<String, EntityModel<String>>> getBondingOptionList(RefObject<Map.Entry<String, EntityModel<String>>> defaultItem)
{
ArrayList<Map.Entry<String, EntityModel<String>>> list =
new ArrayList<Map.Entry<String, EntityModel<String>>>();
EntityModel<String> entityModel = new EntityModel<String>();
entityModel.setEntity("(Mode 1) Active-Backup"); //$NON-NLS-1$
list.add(new KeyValuePairCompat<String, EntityModel<String>>("mode=1 miimon=100", entityModel)); //$NON-NLS-1$
entityModel = new EntityModel<String>();
entityModel.setEntity("(Mode 2) Load balance (balance-xor)"); //$NON-NLS-1$
list.add(new KeyValuePairCompat<String, EntityModel<String>>("mode=2 miimon=100", entityModel)); //$NON-NLS-1$
entityModel = new EntityModel<String>();
entityModel.setEntity("(Mode 4) Dynamic link aggregation (802.3ad)"); //$NON-NLS-1$
defaultItem.argvalue = new KeyValuePairCompat<String, EntityModel<String>>("mode=4 miimon=100", entityModel); //$NON-NLS-1$
list.add(defaultItem.argvalue);
entityModel = new EntityModel<String>();
entityModel.setEntity("(Mode 5) Adaptive transmit load balancing (balance-tlb)"); //$NON-NLS-1$
list.add(new KeyValuePairCompat<String, EntityModel<String>>("mode=5 miimon=100", entityModel)); //$NON-NLS-1$
entityModel = new EntityModel<String>();
entityModel.setEntity(""); //$NON-NLS-1$
list.add(new KeyValuePairCompat<String, EntityModel<String>>("custom", entityModel)); //$NON-NLS-1$
return list;
}
public String getDefaultBondingOption()
{
return "mode=802.3ad miimon=150"; //$NON-NLS-1$
}
public int getMaxVmPriority()
{
return (Integer) getConfigValuePreConverted(ConfigurationValues.VmPriorityMaxValue,
getDefaultConfigurationVersion());
}
public int roundPriority(int priority)
{
int max = getMaxVmPriority();
int medium = max / 2;
int[] levels = new int[] { 1, medium, max };
for (int i = 0; i < levels.length; i++)
{
int lengthToLess = levels[i] - priority;
int lengthToMore = levels[i + 1] - priority;
if (lengthToMore < 0)
{
continue;
}
return Math.abs(lengthToLess) < lengthToMore ? levels[i] : levels[i + 1];
}
return 0;
}
public void getVmGuestAgentInterfacesByVmId(AsyncQuery aQuery, Guid vmId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<VmGuestAgentInterface>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVmGuestAgentInterfacesByVmId, new IdQueryParameters(vmId), aQuery);
}
public void getVnicProfilesByNetworkId(AsyncQuery aQuery, Guid networkId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<VnicProfileView>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetVnicProfilesByNetworkId, new IdQueryParameters(networkId), aQuery);
}
public void getVnicProfilesByDcId(AsyncQuery aQuery, Guid dcId) {
// do not replace a converter = just add if none provided
if (aQuery.converterCallback == null) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return new ArrayList<VnicProfileView>();
}
return source;
}
};
}
Frontend.getInstance().runQuery(VdcQueryType.GetVnicProfilesByDataCenterId, new IdQueryParameters(dcId), aQuery);
}
public void getNumberOfActiveVmsInCluster(AsyncQuery aQuery, Guid clusterId) {
// do not replace a converter = just add if none provided
if (aQuery.converterCallback == null) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery)
{
if (source == null)
{
return Integer.valueOf(0);
}
return source;
}
};
}
Frontend.getInstance().runQuery(VdcQueryType.GetNumberOfActiveVmsInVdsGroupByVdsGroupId, new IdQueryParameters(clusterId), aQuery);
}
public void getNumberOfVmsInCluster(AsyncQuery aQuery, Guid clusterId) {
Frontend.getInstance().runQuery(VdcQueryType.GetNumberOfVmsInVdsGroupByVdsGroupId, new IdQueryParameters(clusterId),
aQuery);
}
public boolean isMixedStorageDomainsSupported(Version version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.MixedDomainTypesInDataCenter, version.toString());
}
private ArrayList<VDSGroup> getClusterByServiceList(ArrayList<VDSGroup> list,
boolean supportsVirtService,
boolean supportsGlusterService) {
final ArrayList<VDSGroup> filteredList = new ArrayList<VDSGroup>();
for (VDSGroup cluster : list) {
if ((supportsVirtService && cluster.supportsVirtService())
|| (supportsGlusterService && cluster.supportsGlusterService())) {
filteredList.add(cluster);
}
}
// sort by cluster name
Collections.sort(filteredList, new NameableComparator());
return filteredList;
}
public String priorityToString(int value) {
int roundedPriority = roundPriority(value);
if (roundedPriority == 1) {
return ConstantsManager.getInstance().getConstants().vmLowPriority();
}
else if (roundedPriority == getMaxVmPriority() / 2) {
return ConstantsManager.getInstance().getConstants().vmMediumPriority();
}
else if (roundedPriority == getMaxVmPriority()) {
return ConstantsManager.getInstance().getConstants().vmHighPriority();
}
else {
return ConstantsManager.getInstance().getConstants().vmUnknownPriority();
}
}
public void getExternalNetworkMap(AsyncQuery aQuery, Guid providerId) {
aQuery.converterCallback = new IAsyncConverter() {
@Override
public Object Convert(Object source, AsyncQuery _asyncQuery) {
if (source == null) {
return new HashMap<Network, Set<Guid>>();
}
return source;
}
};
Frontend.getInstance().runQuery(VdcQueryType.GetAllExternalNetworksOnProvider,
new IdQueryParameters(providerId),
aQuery);
}
public Integer getMaxVmNameLengthWin() {
Integer maxVmNameLengthWindows = (Integer) getConfigValuePreConverted(ConfigurationValues.MaxVmNameLengthWindows);
if (maxVmNameLengthWindows == null) {
return 15;
}
return maxVmNameLengthWindows;
}
public Integer getMaxVmNameLengthNonWin() {
Integer maxVmNameLengthNonWindows = (Integer) getConfigValuePreConverted(ConfigurationValues.MaxVmNameLengthNonWindows);
if (maxVmNameLengthNonWindows == null) {
return 64;
}
return maxVmNameLengthNonWindows;
}
public int getOptimizeSchedulerForSpeedPendingRequests() {
return (Integer) getConfigValuePreConverted(ConfigurationValues.SpeedOptimizationSchedulingThreshold,
getDefaultConfigurationVersion());
}
public boolean getScheudulingAllowOverbookingSupported() {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.SchedulerAllowOverBooking,
getDefaultConfigurationVersion());
}
public int getSchedulerAllowOverbookingPendingRequestsThreshold() {
return (Integer) getConfigValuePreConverted(ConfigurationValues.SchedulerOverBookingThreshold,
getDefaultConfigurationVersion());
}
public Integer getDefaultOs (ArchitectureType architectureType) {
return defaultOSes.get(architectureType);
}
public boolean isRebootCommandExecutionAllowed(List<VM> vms) {
if (vms.isEmpty() || !VdcActionUtils.canExecute(vms, VM.class, VdcActionType.RebootVm)) {
return false;
}
for (VM vm : vms) {
Version version = vm.getVdsGroupCompatibilityVersion();
Version anyDcVersion = new Version();
// currently on VDSM side reboot is supported only when the guest agent is present and responsive so we need to check for that
if (!isCommandCompatible(VdcActionType.RebootVm, version, anyDcVersion) || StringHelper.isNullOrEmpty(vm.getVmIp())) {
return false;
}
}
return true;
}
public boolean isSerialNumberPolicySupported(String version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.SerialNumberPolicySupported, version);
}
public boolean isBootMenuSupported(String version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.BootMenuSupported, version);
}
public boolean isSpiceFileTransferToggleSupported(String version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.SpiceFileTransferToggleSupported, version);
}
public boolean isSpiceCopyPasteToggleSupported(String version) {
return (Boolean) getConfigValuePreConverted(ConfigurationValues.SpiceCopyPasteToggleSupported, version);
}
public List<IStorageModel> getDataStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
models.addAll(getFileDataStorageModels());
models.addAll(getBlockDataStorageModels());
return models;
}
public List<IStorageModel> getFileDataStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
NfsStorageModel nfsDataModel = new NfsStorageModel();
models.add(nfsDataModel);
PosixStorageModel posixDataModel = new PosixStorageModel();
models.add(posixDataModel);
GlusterStorageModel GlusterDataModel = new GlusterStorageModel();
models.add(GlusterDataModel);
LocalStorageModel localDataModel = new LocalStorageModel();
models.add(localDataModel);
addTypeToStorageModels(StorageDomainType.Data, models);
return models;
}
public List<IStorageModel> getBlockDataStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
IscsiStorageModel iscsiDataModel = new IscsiStorageModel();
iscsiDataModel.setIsGrouppedByTarget(true);
models.add(iscsiDataModel);
FcpStorageModel fcpDataModel = new FcpStorageModel();
models.add(fcpDataModel);
addTypeToStorageModels(StorageDomainType.Data, models);
return models;
}
public List<IStorageModel> getImportBlockDataStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
ImportIscsiStorageModel iscsiDataModel = new ImportIscsiStorageModel();
models.add(iscsiDataModel);
ImportFcpStorageModel fcpDataModel = new ImportFcpStorageModel();
models.add(fcpDataModel);
addTypeToStorageModels(StorageDomainType.Data, models);
return models;
}
public List<IStorageModel> getIsoStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
NfsStorageModel nfsIsoModel = new NfsStorageModel();
models.add(nfsIsoModel);
PosixStorageModel posixIsoModel = new PosixStorageModel();
models.add(posixIsoModel);
LocalStorageModel localIsoModel = new LocalStorageModel();
models.add(localIsoModel);
addTypeToStorageModels(StorageDomainType.ISO, models);
return models;
}
public List<IStorageModel> getExportStorageModels() {
ArrayList<IStorageModel> models = new ArrayList<IStorageModel>();
NfsStorageModel nfsExportModel = new NfsStorageModel();
models.add(nfsExportModel);
PosixStorageModel posixExportModel = new PosixStorageModel();
models.add(posixExportModel);
GlusterStorageModel glusterExportModel = new GlusterStorageModel();
models.add(glusterExportModel);
addTypeToStorageModels(StorageDomainType.ImportExport, models);
return models;
}
private void addTypeToStorageModels(StorageDomainType storageDomainType, List<IStorageModel> models) {
for (IStorageModel model : models) {
model.setRole(storageDomainType);
}
}
}
|
webadmin: Fix FB issues in AsyncDataProvider
Fix FindBugs issues (members that should have been static) introduced by
commit 69e57dc94cc30652caa7b790bd5e9a94816b6d8d.
Change-Id: I1dd37f91f0b53b3e334d17082839876529ee9bc5
Signed-off-by: Allon Mureinik <[email protected]>
|
frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/dataprovider/AsyncDataProvider.java
|
webadmin: Fix FB issues in AsyncDataProvider
|
<ide><path>rontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/dataprovider/AsyncDataProvider.java
<ide> instance = provider;
<ide> }
<ide>
<del> private final String GENERAL = "general"; //$NON-NLS-1$
<add> private static final String GENERAL = "general"; //$NON-NLS-1$
<ide>
<ide> // dictionary to hold cache of all config values (per version) queried by client, if the request for them succeeded.
<ide> private HashMap<KeyValuePairCompat<ConfigurationValues, String>, Object> cachedConfigValues =
<ide> cachedConfigValues.clear();
<ide> }
<ide>
<del> private class TemplateConverter implements IAsyncConverter {
<add> private static class TemplateConverter implements IAsyncConverter {
<ide>
<ide> @Override
<ide> public Object Convert(Object source, AsyncQuery asyncQuery) {
|
|
Java
|
mit
|
error: pathspec 'core/src/main/java/org/jeecqrs/events/EventBusInterest.java' did not match any file(s) known to git
|
c77f8fc6167a1b2fb170e06e38b4f0be92547e50
| 1 |
JEEventStore/JEECQRS
|
package org.jeecqrs.events;
import java.util.Set;
/**
* Provides the ability to specify which events a listener wants to
* receive on the event bus.
*
* @param <E> the message base type
*/
public interface EventBusInterest<E> {
/**
* Gets the set of event types the listener is interested in.
*
* @return the set of event classes
*/
Set<Class<? extends E>> interestEventTypes();
/**
* Tells whether the interest includes the given event type.
*
* @param clazz the event type
* @return {@code true} if the interest includes the given even type
*/
boolean includes(Class<? extends E> clazz);
}
|
core/src/main/java/org/jeecqrs/events/EventBusInterest.java
|
Add EventBusInterest
|
core/src/main/java/org/jeecqrs/events/EventBusInterest.java
|
Add EventBusInterest
|
<ide><path>ore/src/main/java/org/jeecqrs/events/EventBusInterest.java
<add>package org.jeecqrs.events;
<add>
<add>import java.util.Set;
<add>
<add>/**
<add> * Provides the ability to specify which events a listener wants to
<add> * receive on the event bus.
<add> *
<add> * @param <E> the message base type
<add> */
<add>public interface EventBusInterest<E> {
<add>
<add> /**
<add> * Gets the set of event types the listener is interested in.
<add> *
<add> * @return the set of event classes
<add> */
<add> Set<Class<? extends E>> interestEventTypes();
<add>
<add> /**
<add> * Tells whether the interest includes the given event type.
<add> *
<add> * @param clazz the event type
<add> * @return {@code true} if the interest includes the given even type
<add> */
<add> boolean includes(Class<? extends E> clazz);
<add>
<add>}
|
|
JavaScript
|
apache-2.0
|
9b840a216be1b72e58154b19f1ed3071184d7625
| 0 |
uhm-coe/assist,uhm-coe/assist,uhm-coe/assist,uhm-coe/assist
|
$(document).ready(function(){
/**
* @name: formatPostContent()
* @author: Myles Enriquez
* @date: 20160125
* @description: Adds bootstrap syntax to elements within post to make
* a post responsive.
*
* @params: null
* @returns: null
*/
function formatPostContent() {
// Each li contains a line break
$('#postcontent li').each(function(){
$(this).after('<hr/>');
});
// Each li has a class of 'row'
$('#postcontent li').each(function(){
$(this).addClass('row');
});
// Each p inside of a li contains a class of 12 for xs devices and 6 for medium devices
$('#postcontent li p').each(function(){
$(this).addClass('col-xs-12 col-md-6');
});
}
formatPostContent();
$('.sidebar-content').on('click', '> li > a', function(){
$('.sidebar-content').find('.open').removeClass('open');
$(this).addClass('open');
});
/**
* @name: stickyElement()
* @author: Myles Enriquez
* @date: 20160125
* @description: Will make an element 'sticky' by sticking it to top of viewport when the two touch.
*
* @params: {String} classOfElement Class name given to the element
* @returns: null
*/
function stickyElement(classOfElement) {
var stickyTop = $(classOfElement).offset().top;
$(window).scroll(function(event) {
var windowTop = $(window).scrollTop();
if (stickyTop < windowTop) {
$(classOfElement).css(
{
'position': 'fixed',
'width': '212.5', // TODO: change to percentage
'top': '0'
});
}
else {
$(classOfElement).css({'position':'static'});
}
});
}
// stickyElement('.sidebar-content');
});
|
assets/js/main.js
|
$(document).ready(function(){
/**
* @name: formatPostContent()
* @author: Myles Enriquez
* @date: 20160125
* @description: Adds bootstrap syntax to elements within post to make
* a post responsive.
*
* @params: null
* @returns: null
*/
function formatPostContent() {
// Each li contains a line break
$('#postcontent li').each(function(){
$(this).after('<hr/>');
});
// Each li has a class of 'row'
$('#postcontent li').each(function(){
$(this).addClass('row');
});
// Each p inside of a li contains a class of 12 for xs devices and 6 for medium devices
$('#postcontent li p').each(function(){
$(this).addClass('col-xs-12 col-md-6');
});
}
formatPostContent();
/**
* @name: stickyElement()
* @author: Myles Enriquez
* @date: 20160125
* @description: Will make an element 'sticky' by sticking it to top of viewport when the two touch.
*
* @params: {String} classOfElement Class name given to the element
* @returns: null
*/
function stickyElement(classOfElement) {
var stickyTop = $(classOfElement).offset().top;
$(window).scroll(function(event) {
var windowTop = $(window).scrollTop();
if (stickyTop < windowTop) {
$(classOfElement).css(
{
'position': 'fixed',
'width': '212.5', // TODO: change to percentage
'top': '0'
});
}
else {
$(classOfElement).css({'position':'static'});
}
});
}
// stickyElement('.sidebar-content');
});
|
Add onclick function for parent list items.
|
assets/js/main.js
|
Add onclick function for parent list items.
|
<ide><path>ssets/js/main.js
<ide> });
<ide> }
<ide> formatPostContent();
<add>
<add> $('.sidebar-content').on('click', '> li > a', function(){
<add> $('.sidebar-content').find('.open').removeClass('open');
<add> $(this).addClass('open');
<add> });
<ide>
<ide>
<ide>
|
|
JavaScript
|
apache-2.0
|
702aa14304d9034c76d4198d4867e02950b33e7b
| 0 |
googlecodelabs/tools,Qwiklabs/codelab-tools,googlecodelabs/tools,googlecodelabs/tools,Qwiklabs/codelab-tools,Qwiklabs/codelab-tools,googlecodelabs/tools,Qwiklabs/codelab-tools
|
/**
* @license
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.module('googlecodelabs.Codelab');
const EventHandler = goog.require('goog.events.EventHandler');
const HTML5LocalStorage = goog.require('goog.storage.mechanism.HTML5LocalStorage');
const KeyCodes = goog.require('goog.events.KeyCodes');
const Templates = goog.require('googlecodelabs.Codelab.Templates');
const Transition = goog.require('goog.fx.css3.Transition');
const TransitionEventType = goog.require('goog.fx.Transition.EventType');
const dom = goog.require('goog.dom');
const events = goog.require('goog.events');
const soy = goog.require('goog.soy');
/**
* Deprecated. Title causes the bowser to display a tooltip over the whole codelab.
* Use codelab-title instead.
* @const {string}
*/
const TITLE_ATTR = 'title';
/** @const {string} */
const CODELAB_TITLE_ATTR = 'codelab-title';
/** @const {string} */
const ENVIRONMENT_ATTR = 'environment';
/** @const {string} */
const CATEGORY_ATTR = 'category';
/** @const {string} */
const GAID_ATTR = 'codelab-gaid';
/** @const {string} */
const FEEDBACK_LINK_ATTR = 'feedback-link';
/** @const {string} */
const SELECTED_ATTR = 'selected';
/** @const {string} */
const LAST_UPDATED_ATTR = 'last-updated';
/** @const {string} */
const DURATION_ATTR = 'duration';
/** @const {string} */
const HIDDEN_ATTR = 'hidden';
/** @const {string} */
const COMPLETED_ATTR = 'completed';
/** @const {string} */
const LABEL_ATTR = 'label';
/** @const {string} */
const DONT_SET_HISTORY_ATTR = 'dsh';
/** @const {string} */
const ANIMATING_ATTR = 'animating';
/** @const {string} */
const NO_TOOLBAR_ATTR = 'no-toolbar';
/** @const {string} */
const NO_ARROWS_ATTR = 'no-arrows';
/** @const {string} */
const DISAPPEAR_ATTR = 'disappear';
/** @const {number} Page transition time in seconds */
const ANIMATION_DURATION = .5;
/** @const {string} */
const DRAWER_OPEN_ATTR = 'drawer--open';
/** @const {string} */
const ANALYTICS_READY_ATTR = 'anayltics-ready';
/**
* The general codelab action event fired for trackable interactions.
*/
const CODELAB_ACTION_EVENT = 'google-codelab-action';
/**
* The general codelab action event fired for trackable interactions.
*/
const CODELAB_PAGEVIEW_EVENT = 'google-codelab-pageview';
/**
* The general codelab action event fired when the codelab element is ready.
*/
const CODELAB_READY_EVENT = 'google-codelab-ready'
/**
* @extends {HTMLElement}
*/
class Codelab extends HTMLElement {
/** @return {string} */
static getTagName() { return 'google-codelab'; }
constructor() {
super();
/** @private {?Element} */
this.drawer_ = null;
/** @private {?Element} */
this.stepsContainer_ = null;
/** @private {?Element} */
this.titleContainer_ = null;
/** @private {?Element} */
this.nextStepBtn_ = null;
/** @private {?Element} */
this.prevStepBtn_ = null;
/** @private {?Element} */
this.controls_ = null;
/** @private {?Element} */
this.doneBtn_ = null;
/** @private {string} */
this.id_ = '';
/** @private {string} */
this.title_ = '';
/** @private {!Array<!Element>} */
this.steps_ = [];
/** @private {number} */
this.currentSelectedStep_ = -1;
/**
* @private {!EventHandler}
* @const
*/
this.eventHandler_ = new EventHandler();
/**
* @private {!EventHandler}
* @const
*/
this.transitionEventHandler_ = new EventHandler();
/** @private {boolean} */
this.hasSetup_ = false;
/** @private {boolean} */
this.ready_ = false;
/** @private {?Transition} */
this.transitionIn_ = null;
/** @private {?Transition} */
this.transitionOut_ = null;
/** @private {boolean} */
this.resumed_ = false;
/**
* @private {!HTML5LocalStorage}
* @const
*/
this.storage_ = new HTML5LocalStorage();
}
/**
* @export
* @override
*/
connectedCallback() {
if (!this.hasSetup_) {
this.setupDom_();
}
this.addEvents_();
this.configureAnalytics_();
this.showSelectedStep_();
this.updateTitle_();
this.toggleArrows_();
this.toggleToolbar_();
if (this.resumed_) {
console.log('resumed');
// TODO Show resume dialog
}
if (!this.ready_) {
this.ready_ = true;
this.fireEvent_(CODELAB_READY_EVENT);
}
}
/**
* @export
* @override
*/
disconnectedCallback() {
this.eventHandler_.removeAll();
this.transitionEventHandler_.removeAll();
}
/**
* @return {!Array<string>}
* @export
*/
static get observedAttributes() {
return [TITLE_ATTR, CODELAB_TITLE_ATTR, ENVIRONMENT_ATTR, CATEGORY_ATTR,
FEEDBACK_LINK_ATTR, SELECTED_ATTR, LAST_UPDATED_ATTR, NO_TOOLBAR_ATTR,
NO_ARROWS_ATTR, ANALYTICS_READY_ATTR];
}
/**
* @param {string} attr
* @param {?string} oldValue
* @param {?string} newValue
* @param {?string} namespace
* @export
* @override
*/
attributeChangedCallback(attr, oldValue, newValue, namespace) {
switch (attr) {
case TITLE_ATTR:
if (this.hasAttribute(TITLE_ATTR)) {
this.title_ = this.getAttribute(TITLE_ATTR);
this.removeAttribute(TITLE_ATTR);
this.setAttribute(CODELAB_TITLE_ATTR, this.title_);
}
break;
case CODELAB_TITLE_ATTR:
this.title_ = this.getAttribute(CODELAB_TITLE_ATTR);
this.updateTitle_();
break;
case SELECTED_ATTR:
this.showSelectedStep_();
break;
case NO_TOOLBAR_ATTR:
this.toggleToolbar_();
break;
case NO_ARROWS_ATTR:
this.toggleArrows_();
break;
case ANALYTICS_READY_ATTR:
if (this.hasAttribute(ANALYTICS_READY_ATTR)) {
if (this.ready_) {
this.firePageLoadEvents_();
} else {
this.addEventListener(CODELAB_READY_EVENT,
() => this.firePageLoadEvents_());
}
}
break;
}
}
/**
* @private
*/
configureAnalytics_() {
const analytics = document.querySelector('google-codelab-analytics');
if (analytics) {
const gaid = this.getAttribute(GAID_ATTR);
if (gaid) {
analytics.setAttribute(GAID_ATTR, gaid);
}
analytics.setAttribute(
ENVIRONMENT_ATTR, this.getAttribute(ENVIRONMENT_ATTR));
analytics.setAttribute(CATEGORY_ATTR, this.getAttribute(CATEGORY_ATTR));
}
}
/**
* @export
*/
selectNext() {
this.setAttribute(SELECTED_ATTR, this.currentSelectedStep_ + 1);
}
/**
* @export
*/
selectPrevious() {
this.setAttribute(SELECTED_ATTR, this.currentSelectedStep_ - 1);
}
/**
* @export
* @param {number} index
*/
select(index) {
this.setAttribute(SELECTED_ATTR, index);
}
/**
* @private
*/
addEvents_() {
if (this.prevStepBtn_) {
this.eventHandler_.listen(this.prevStepBtn_, events.EventType.CLICK,
(e) => {
e.preventDefault();
e.stopPropagation();
this.selectPrevious();
});
}
if (this.nextStepBtn_) {
this.eventHandler_.listen(this.nextStepBtn_, events.EventType.CLICK,
(e) => {
e.preventDefault();
e.stopPropagation();
this.selectNext();
});
}
if (this.drawer_) {
this.eventHandler_.listen(this.drawer_, events.EventType.CLICK,
(e) => this.handleDrawerClick_(e));
this.eventHandler_.listen(this.drawer_, events.EventType.KEYDOWN,
(e) => this.handleDrawerKeyDown_(e));
}
if (this.titleContainer_) {
const menuBtn = this.titleContainer_.querySelector('#menu');
if (menuBtn) {
this.eventHandler_.listen(menuBtn, events.EventType.CLICK, (e) => {
e.preventDefault();
e.stopPropagation();
if (this.hasAttribute(DRAWER_OPEN_ATTR)) {
this.removeAttribute(DRAWER_OPEN_ATTR);
} else {
this.setAttribute(DRAWER_OPEN_ATTR, '');
}
});
this.eventHandler_.listen(document.body, events.EventType.CLICK, (e) => {
if (this.hasAttribute(DRAWER_OPEN_ATTR)) {
this.removeAttribute(DRAWER_OPEN_ATTR);
}
});
}
}
this.eventHandler_.listen(dom.getWindow(), events.EventType.POPSTATE, (e) => {
this.handlePopStateChanged_(e);
});
this.eventHandler_.listen(document.body, events.EventType.KEYDOWN, (e) => {
this.handleKeyDown_(e);
});
}
/**
* @private
*/
toggleToolbar_() {
if (!this.titleContainer_) {
return;
}
if (this.hasAttribute(NO_TOOLBAR_ATTR)) {
this.titleContainer_.setAttribute(HIDDEN_ATTR, '');
} else {
this.titleContainer_.removeAttribute(HIDDEN_ATTR);
}
}
/**
* @private
*/
toggleArrows_() {
if (!this.controls_) {
return;
}
if (this.hasAttribute(NO_ARROWS_ATTR)) {
this.controls_.setAttribute(HIDDEN_ATTR, '');
} else {
this.controls_.removeAttribute(HIDDEN_ATTR);
}
}
/**
*
* @param {!events.BrowserEvent} e
* @private
*/
handleDrawerKeyDown_(e) {
if (!this.drawer_) {
return;
}
const focused = this.drawer_.querySelector(':focus');
let li;
if (focused) {
li = /** @type {!Element} */ (focused.parentNode);
} else {
li = this.drawer_.querySelector(`[${SELECTED_ATTR}]`);
}
if (!li) {
return;
}
let next;
if (e.keyCode == KeyCodes.UP) {
next = dom.getPreviousElementSibling(li);
} else if (e.keyCode == KeyCodes.DOWN) {
next = dom.getNextElementSibling(li);
}
if (next) {
const a = next.querySelector('a');
if (a) {
a.focus();
}
}
}
/**
* @param {!events.BrowserEvent} e
* @private
*/
handleKeyDown_(e) {
if (e.keyCode == KeyCodes.LEFT) {
if (document.activeElement) {
document.activeElement.blur();
}
this.selectPrevious();
} else if (e.keyCode == KeyCodes.RIGHT) {
if (document.activeElement) {
document.activeElement.blur();
}
this.selectNext();
}
}
/**
* History popState callback
* @param {!Event} e
* @private
*/
handlePopStateChanged_(e) {
if (document.location.hash) {
this.setAttribute(DONT_SET_HISTORY_ATTR, '');
this.setAttribute(SELECTED_ATTR, document.location.hash.substring(1));
this.removeAttribute(DONT_SET_HISTORY_ATTR);
}
}
/**
* Updates the browser history state
* @param {string} path The new browser state
* @param {boolean=} replaceState optionally replace state instead of pushing
* @export
*/
updateHistoryState(path, replaceState=false) {
if (replaceState) {
window.history.replaceState({path}, document.title, path);
} else {
window.history.pushState({path}, document.title, path);
}
}
/**
* @param {!Event} e
* @private
*/
handleDrawerClick_(e) {
e.preventDefault();
e.stopPropagation();
let target = /** @type {!Element} */ (e.target);
while (target !== this.drawer_) {
if (target.tagName.toUpperCase() === 'A') {
break;
}
target = /** @type {!Element} */ (target.parentNode);
}
if (target === this.drawer_) {
return;
}
const selected = new URL(target.getAttribute('href'), document.location.origin)
.hash.substring(1);
this.setAttribute(SELECTED_ATTR, selected);
}
/**
* @private
*/
updateTitle_() {
if (!this.title_ || !this.titleContainer_) {
return;
}
const newTitleEl =
soy.renderAsElement(Templates.title, {title: this.title_});
document.title = this.title_;
const oldTitleEl = this.titleContainer_.querySelector('h1');
const buttons = this.titleContainer_.querySelector('#codelab-nav-buttons');
if (oldTitleEl) {
dom.replaceNode(newTitleEl, oldTitleEl);
} else {
dom.insertSiblingAfter(newTitleEl, buttons);
}
}
/**
* @private
*/
updateTimeRemaining_() {
if (!this.titleContainer_) {
return;
}
let time = 0;
for (let i = this.currentSelectedStep_; i < this.steps_.length; i++) {
const step = /** @type {!Element} */ (this.steps_[i]);
let n = parseInt(step.getAttribute(DURATION_ATTR), 10);
if (n) {
time += n;
}
}
const newTimeEl = soy.renderAsElement(Templates.timeRemaining, {time});
const oldTimeEl = this.titleContainer_.querySelector('#time-remaining');
if (oldTimeEl) {
dom.replaceNode(newTimeEl, oldTimeEl);
} else {
dom.appendChild(this.titleContainer_, newTimeEl);
}
}
/**
* @private
*/
setupSteps_() {
this.steps_.forEach((step, index) => {
step = /** @type {!Element} */ (step);
step.setAttribute('step', index+1);
});
}
/**
* @private
*/
showSelectedStep_() {
let selected = 0;
if (this.hasAttribute(SELECTED_ATTR)) {
selected = parseInt(this.getAttribute(SELECTED_ATTR), 0);
} else {
this.setAttribute(SELECTED_ATTR, selected);
return;
}
selected = Math.min(Math.max(0, parseInt(selected, 10)), this.steps_.length - 1);
if (this.currentSelectedStep_ === selected || isNaN(selected)) {
// Either the current step is already selected or an invalid option was provided
// do nothing and return.
return;
}
const stepTitleEl = this.steps_[selected].querySelector('.step-title');
const stepTitle = stepTitleEl ? stepTitleEl.textContent : '';
const stepTitlePrefix = (selected + 1) + '.';
const re = new RegExp(stepTitlePrefix, 'g');
this.fireEvent_(CODELAB_PAGEVIEW_EVENT, {
'page': location.pathname + '#' + selected,
'title': stepTitle.replace(re, '').trim()
});
if (this.currentSelectedStep_ === -1) {
// No previous selected step, so select the correct step with no animation
const stepToSelect = this.steps_[selected];
stepToSelect.setAttribute(SELECTED_ATTR, '');
} else {
if (this.transitionIn_) {
this.transitionIn_.stop();
}
if (this.transitionOut_) {
this.transitionOut_.stop();
}
this.transitionEventHandler_.removeAll();
const transitionInInitialStyle = {};
const transitionInFinalStyle = {
transform: 'translate3d(0, 0, 0)'
};
const transitionOutInitialStyle = {
transform: 'translate3d(0, 0, 0)'
};
const transitionOutFinalStyle = {};
const stepToSelect = this.steps_[selected];
const currentStep = this.steps_[this.currentSelectedStep_];
stepToSelect.setAttribute(ANIMATING_ATTR, '');
if (this.currentSelectedStep_ < selected) {
// Move new step in from the right
transitionInInitialStyle['transform'] = 'translate3d(110%, 0, 0)';
transitionOutFinalStyle['transform'] = 'translate3d(-110%, 0, 0)';
} else {
// Move new step in from the left
transitionInInitialStyle['transform'] = 'translate3d(-110%, 0, 0)';
transitionOutFinalStyle['transform'] = 'translate3d(110%, 0, 0)';
}
const animationProperties = [{
property: 'transform',
duration: ANIMATION_DURATION,
delay: 0,
timing: 'cubic-bezier(0.4, 0, 0.2, 1)'
}];
this.transitionIn_ = new Transition(stepToSelect, ANIMATION_DURATION,
transitionInInitialStyle, transitionInFinalStyle, animationProperties);
this.transitionOut_ = new Transition(currentStep, ANIMATION_DURATION,
transitionOutInitialStyle, transitionOutFinalStyle, animationProperties);
this.transitionIn_.play();
this.transitionOut_.play();
this.transitionEventHandler_.listenOnce(this.transitionIn_,
[TransitionEventType.FINISH, TransitionEventType.STOP], () => {
stepToSelect.setAttribute(SELECTED_ATTR, '');
stepToSelect.removeAttribute(ANIMATING_ATTR);
});
this.transitionEventHandler_.listenOnce(this.transitionOut_,
[TransitionEventType.FINISH, TransitionEventType.STOP], () => {
currentStep.removeAttribute(SELECTED_ATTR);
});
}
this.currentSelectedStep_ = selected;
if (this.nextStepBtn_ && this.prevStepBtn_ && this.doneBtn_) {
if (selected === 0) {
this.prevStepBtn_.setAttribute(DISAPPEAR_ATTR, '');
} else {
this.prevStepBtn_.removeAttribute(DISAPPEAR_ATTR);
}
if (selected === this.steps_.length - 1) {
this.nextStepBtn_.setAttribute(HIDDEN_ATTR, '');
this.doneBtn_.removeAttribute(HIDDEN_ATTR);
this.fireEvent_(CODELAB_ACTION_EVENT, {
'category': 'codelab',
'action': 'complete',
'label': this.title_
});
} else {
this.nextStepBtn_.removeAttribute(HIDDEN_ATTR);
this.doneBtn_.setAttribute(HIDDEN_ATTR, '');
}
}
if (this.drawer_) {
const steps = this.drawer_.querySelectorAll('li');
steps.forEach((step, i) => {
if (i <= selected) {
step.setAttribute(COMPLETED_ATTR, '');
} else {
step.removeAttribute(COMPLETED_ATTR);
}
if (i === selected) {
step.setAttribute(SELECTED_ATTR, '');
step.scrollIntoViewIfNeeded();
} else {
step.removeAttribute(SELECTED_ATTR);
}
});
}
this.updateTimeRemaining_();
if (!this.hasAttribute(DONT_SET_HISTORY_ATTR)) {
this.updateHistoryState(`#${selected}`, true);
}
this.storage_.set(`progress_${this.id_}`, String(this.currentSelectedStep_));
}
/**
* @private
*/
renderDrawer_() {
const feedback = this.getAttribute(FEEDBACK_LINK_ATTR);
const steps = this.steps_.map((step) => step.getAttribute(LABEL_ATTR));
soy.renderElement(this.drawer_, Templates.drawer, {steps, feedback});
}
/**
* @private
* @return {string}
*/
getHomeUrl_() {
const url = new URL(document.location.toString());
let index = url.searchParams.get('index');
if (!index) {
return '/';
}
index = index.replace(/[^a-z0-9\-]+/ig, '');
if (!index || index.trim() === '') {
return '/';
}
if (index === 'index') {
index = '';
}
const u = new URL(index, document.location.origin);
return u.pathname;
}
/**
* @param {string} eventName
* @param {!Object=} detail
* @private
*/
fireEvent_(eventName, detail={}) {
const event = new CustomEvent(eventName, {
detail: detail,
bubbles: true,
});
this.dispatchEvent(event);
}
/**
* Fires events for initial page load.
*/
firePageLoadEvents_() {
this.fireEvent_(CODELAB_PAGEVIEW_EVENT, {
'page': location.pathname + '#' + this.currentSelectedStep_,
'title': this.steps_[this.currentSelectedStep_].getAttribute(LABEL_ATTR)
});
window.requestAnimationFrame(() => {
document.body.removeAttribute('unresolved');
this.fireEvent_(CODELAB_ACTION_EVENT, {
'category': 'codelab',
'action': 'ready'
});
});
}
/**
* @private
*/
setupDom_() {
this.steps_ = Array.from(this.querySelectorAll('google-codelab-step'));
soy.renderElement(this, Templates.structure, {
homeUrl: this.getHomeUrl_()
});
this.drawer_ = this.querySelector('#drawer');
this.titleContainer_ = this.querySelector('#codelab-title');
this.stepsContainer_ = this.querySelector('#steps');
this.controls_ = this.querySelector('#controls');
this.prevStepBtn_ = this.querySelector('#controls #previous-step');
this.nextStepBtn_ = this.querySelector('#controls #next-step');
this.doneBtn_ = this.querySelector('#controls #done');
this.steps_.forEach((step) => dom.appendChild(this.stepsContainer_, step));
this.setupSteps_();
this.renderDrawer_();
if (document.location.hash) {
const h = parseInt(document.location.hash.substring(1), 10);
if (!isNaN(h) && h) {
this.setAttribute(SELECTED_ATTR, document.location.hash.substring(1));
}
}
this.id_ = this.getAttribute('id');
const progress = this.storage_.get(`progress_${this.id_}`);
if (progress && progress !== '0') {
this.resumed_ = true;
this.setAttribute(SELECTED_ATTR, progress);
}
this.hasSetup_ = true;
}
}
exports = Codelab;
|
codelab-elements/google-codelab/google_codelab.js
|
/**
* @license
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.module('googlecodelabs.Codelab');
const EventHandler = goog.require('goog.events.EventHandler');
const HTML5LocalStorage = goog.require('goog.storage.mechanism.HTML5LocalStorage');
const KeyCodes = goog.require('goog.events.KeyCodes');
const Templates = goog.require('googlecodelabs.Codelab.Templates');
const Transition = goog.require('goog.fx.css3.Transition');
const TransitionEventType = goog.require('goog.fx.Transition.EventType');
const dom = goog.require('goog.dom');
const events = goog.require('goog.events');
const soy = goog.require('goog.soy');
/**
* Deprecated. Title causes the bowser to display a tooltip over the whole codelab.
* Use codelab-title instead.
* @const {string}
*/
const TITLE_ATTR = 'title';
/** @const {string} */
const CODELAB_TITLE_ATTR = 'codelab-title';
/** @const {string} */
const ENVIRONMENT_ATTR = 'environment';
/** @const {string} */
const CATEGORY_ATTR = 'category';
/** @const {string} */
const GAID_ATTR = 'codelab-gaid';
/** @const {string} */
const FEEDBACK_LINK_ATTR = 'feedback-link';
/** @const {string} */
const SELECTED_ATTR = 'selected';
/** @const {string} */
const LAST_UPDATED_ATTR = 'last-updated';
/** @const {string} */
const DURATION_ATTR = 'duration';
/** @const {string} */
const HIDDEN_ATTR = 'hidden';
/** @const {string} */
const COMPLETED_ATTR = 'completed';
/** @const {string} */
const LABEL_ATTR = 'label';
/** @const {string} */
const DONT_SET_HISTORY_ATTR = 'dsh';
/** @const {string} */
const ANIMATING_ATTR = 'animating';
/** @const {string} */
const NO_TOOLBAR_ATTR = 'no-toolbar';
/** @const {string} */
const NO_ARROWS_ATTR = 'no-arrows';
/** @const {string} */
const DISAPPEAR_ATTR = 'disappear';
/** @const {number} Page transition time in seconds */
const ANIMATION_DURATION = .5;
/** @const {string} */
const DRAWER_OPEN_ATTR = 'drawer--open';
/** @const {string} */
const ANALYTICS_READY_ATTR = 'anayltics-ready';
/**
* The general codelab action event fired for trackable interactions.
*/
const CODELAB_ACTION_EVENT = 'google-codelab-action';
/**
* The general codelab action event fired for trackable interactions.
*/
const CODELAB_PAGEVIEW_EVENT = 'google-codelab-pageview';
/**
* The general codelab action event fired when the codelab element is ready.
*/
const CODELAB_READY_EVENT = 'google-codelab-ready'
/**
* @extends {HTMLElement}
*/
class Codelab extends HTMLElement {
/** @return {string} */
static getTagName() { return 'google-codelab'; }
constructor() {
super();
/** @private {?Element} */
this.drawer_ = null;
/** @private {?Element} */
this.stepsContainer_ = null;
/** @private {?Element} */
this.titleContainer_ = null;
/** @private {?Element} */
this.nextStepBtn_ = null;
/** @private {?Element} */
this.prevStepBtn_ = null;
/** @private {?Element} */
this.controls_ = null;
/** @private {?Element} */
this.doneBtn_ = null;
/** @private {string} */
this.id_ = '';
/** @private {string} */
this.title_ = '';
/** @private {!Array<!Element>} */
this.steps_ = [];
/** @private {number} */
this.currentSelectedStep_ = -1;
/**
* @private {!EventHandler}
* @const
*/
this.eventHandler_ = new EventHandler();
/**
* @private {!EventHandler}
* @const
*/
this.transitionEventHandler_ = new EventHandler();
/** @private {boolean} */
this.hasSetup_ = false;
/** @private {boolean} */
this.ready_ = false;
/** @private {?Transition} */
this.transitionIn_ = null;
/** @private {?Transition} */
this.transitionOut_ = null;
/** @private {boolean} */
this.resumed_ = false;
/**
* @private {!HTML5LocalStorage}
* @const
*/
this.storage_ = new HTML5LocalStorage();
}
/**
* @export
* @override
*/
connectedCallback() {
if (!this.hasSetup_) {
this.setupDom_();
}
this.addEvents_();
this.configureAnalytics_();
this.showSelectedStep_();
this.updateTitle_();
this.toggleArrows_();
this.toggleToolbar_();
if (this.resumed_) {
console.log('resumed');
// TODO Show resume dialog
}
if (!this.ready_) {
this.ready_ = true;
this.fireEvent_(CODELAB_READY_EVENT);
}
}
/**
* @export
* @override
*/
disconnectedCallback() {
this.eventHandler_.removeAll();
this.transitionEventHandler_.removeAll();
}
/**
* @return {!Array<string>}
* @export
*/
static get observedAttributes() {
return [TITLE_ATTR, CODELAB_TITLE_ATTR, ENVIRONMENT_ATTR, CATEGORY_ATTR,
FEEDBACK_LINK_ATTR, SELECTED_ATTR, LAST_UPDATED_ATTR, NO_TOOLBAR_ATTR,
NO_ARROWS_ATTR, ANALYTICS_READY_ATTR];
}
/**
* @param {string} attr
* @param {?string} oldValue
* @param {?string} newValue
* @param {?string} namespace
* @export
* @override
*/
attributeChangedCallback(attr, oldValue, newValue, namespace) {
switch (attr) {
case TITLE_ATTR:
if (this.hasAttribute(TITLE_ATTR)) {
this.title_ = this.getAttribute(TITLE_ATTR);
this.removeAttribute(TITLE_ATTR);
this.setAttribute(CODELAB_TITLE_ATTR, this.title_);
}
break;
case CODELAB_TITLE_ATTR:
this.title_ = this.getAttribute(CODELAB_TITLE_ATTR);
this.updateTitle_();
break;
case SELECTED_ATTR:
this.showSelectedStep_();
break;
case NO_TOOLBAR_ATTR:
this.toggleToolbar_();
break;
case NO_ARROWS_ATTR:
this.toggleArrows_();
break;
case ANALYTICS_READY_ATTR:
if (this.hasAttribute(ANALYTICS_READY_ATTR)) {
if (this.ready_) {
this.firePageLoadEvents_();
} else {
document.body.addEventListener(CODELAB_READY_EVENT,
() => this.firePageLoadEvents_());
}
}
break;
}
}
/**
* @private
*/
configureAnalytics_() {
const analytics = document.querySelector('google-codelab-analytics');
if (analytics) {
const gaid = this.getAttribute(GAID_ATTR);
if (gaid) {
analytics.setAttribute(GAID_ATTR, gaid);
}
analytics.setAttribute(
ENVIRONMENT_ATTR, this.getAttribute(ENVIRONMENT_ATTR));
analytics.setAttribute(CATEGORY_ATTR, this.getAttribute(CATEGORY_ATTR));
}
}
/**
* @export
*/
selectNext() {
this.setAttribute(SELECTED_ATTR, this.currentSelectedStep_ + 1);
}
/**
* @export
*/
selectPrevious() {
this.setAttribute(SELECTED_ATTR, this.currentSelectedStep_ - 1);
}
/**
* @export
* @param {number} index
*/
select(index) {
this.setAttribute(SELECTED_ATTR, index);
}
/**
* @private
*/
addEvents_() {
if (this.prevStepBtn_) {
this.eventHandler_.listen(this.prevStepBtn_, events.EventType.CLICK,
(e) => {
e.preventDefault();
e.stopPropagation();
this.selectPrevious();
});
}
if (this.nextStepBtn_) {
this.eventHandler_.listen(this.nextStepBtn_, events.EventType.CLICK,
(e) => {
e.preventDefault();
e.stopPropagation();
this.selectNext();
});
}
if (this.drawer_) {
this.eventHandler_.listen(this.drawer_, events.EventType.CLICK,
(e) => this.handleDrawerClick_(e));
this.eventHandler_.listen(this.drawer_, events.EventType.KEYDOWN,
(e) => this.handleDrawerKeyDown_(e));
}
if (this.titleContainer_) {
const menuBtn = this.titleContainer_.querySelector('#menu');
if (menuBtn) {
this.eventHandler_.listen(menuBtn, events.EventType.CLICK, (e) => {
e.preventDefault();
e.stopPropagation();
if (this.hasAttribute(DRAWER_OPEN_ATTR)) {
this.removeAttribute(DRAWER_OPEN_ATTR);
} else {
this.setAttribute(DRAWER_OPEN_ATTR, '');
}
});
this.eventHandler_.listen(document.body, events.EventType.CLICK, (e) => {
if (this.hasAttribute(DRAWER_OPEN_ATTR)) {
this.removeAttribute(DRAWER_OPEN_ATTR);
}
});
}
}
this.eventHandler_.listen(dom.getWindow(), events.EventType.POPSTATE, (e) => {
this.handlePopStateChanged_(e);
});
this.eventHandler_.listen(document.body, events.EventType.KEYDOWN, (e) => {
this.handleKeyDown_(e);
});
}
/**
* @private
*/
toggleToolbar_() {
if (!this.titleContainer_) {
return;
}
if (this.hasAttribute(NO_TOOLBAR_ATTR)) {
this.titleContainer_.setAttribute(HIDDEN_ATTR, '');
} else {
this.titleContainer_.removeAttribute(HIDDEN_ATTR);
}
}
/**
* @private
*/
toggleArrows_() {
if (!this.controls_) {
return;
}
if (this.hasAttribute(NO_ARROWS_ATTR)) {
this.controls_.setAttribute(HIDDEN_ATTR, '');
} else {
this.controls_.removeAttribute(HIDDEN_ATTR);
}
}
/**
*
* @param {!events.BrowserEvent} e
* @private
*/
handleDrawerKeyDown_(e) {
if (!this.drawer_) {
return;
}
const focused = this.drawer_.querySelector(':focus');
let li;
if (focused) {
li = /** @type {!Element} */ (focused.parentNode);
} else {
li = this.drawer_.querySelector(`[${SELECTED_ATTR}]`);
}
if (!li) {
return;
}
let next;
if (e.keyCode == KeyCodes.UP) {
next = dom.getPreviousElementSibling(li);
} else if (e.keyCode == KeyCodes.DOWN) {
next = dom.getNextElementSibling(li);
}
if (next) {
const a = next.querySelector('a');
if (a) {
a.focus();
}
}
}
/**
* @param {!events.BrowserEvent} e
* @private
*/
handleKeyDown_(e) {
if (e.keyCode == KeyCodes.LEFT) {
if (document.activeElement) {
document.activeElement.blur();
}
this.selectPrevious();
} else if (e.keyCode == KeyCodes.RIGHT) {
if (document.activeElement) {
document.activeElement.blur();
}
this.selectNext();
}
}
/**
* History popState callback
* @param {!Event} e
* @private
*/
handlePopStateChanged_(e) {
if (document.location.hash) {
this.setAttribute(DONT_SET_HISTORY_ATTR, '');
this.setAttribute(SELECTED_ATTR, document.location.hash.substring(1));
this.removeAttribute(DONT_SET_HISTORY_ATTR);
}
}
/**
* Updates the browser history state
* @param {string} path The new browser state
* @param {boolean=} replaceState optionally replace state instead of pushing
* @export
*/
updateHistoryState(path, replaceState=false) {
if (replaceState) {
window.history.replaceState({path}, document.title, path);
} else {
window.history.pushState({path}, document.title, path);
}
}
/**
* @param {!Event} e
* @private
*/
handleDrawerClick_(e) {
e.preventDefault();
e.stopPropagation();
let target = /** @type {!Element} */ (e.target);
while (target !== this.drawer_) {
if (target.tagName.toUpperCase() === 'A') {
break;
}
target = /** @type {!Element} */ (target.parentNode);
}
if (target === this.drawer_) {
return;
}
const selected = new URL(target.getAttribute('href'), document.location.origin)
.hash.substring(1);
this.setAttribute(SELECTED_ATTR, selected);
}
/**
* @private
*/
updateTitle_() {
if (!this.title_ || !this.titleContainer_) {
return;
}
const newTitleEl =
soy.renderAsElement(Templates.title, {title: this.title_});
document.title = this.title_;
const oldTitleEl = this.titleContainer_.querySelector('h1');
const buttons = this.titleContainer_.querySelector('#codelab-nav-buttons');
if (oldTitleEl) {
dom.replaceNode(newTitleEl, oldTitleEl);
} else {
dom.insertSiblingAfter(newTitleEl, buttons);
}
}
/**
* @private
*/
updateTimeRemaining_() {
if (!this.titleContainer_) {
return;
}
let time = 0;
for (let i = this.currentSelectedStep_; i < this.steps_.length; i++) {
const step = /** @type {!Element} */ (this.steps_[i]);
let n = parseInt(step.getAttribute(DURATION_ATTR), 10);
if (n) {
time += n;
}
}
const newTimeEl = soy.renderAsElement(Templates.timeRemaining, {time});
const oldTimeEl = this.titleContainer_.querySelector('#time-remaining');
if (oldTimeEl) {
dom.replaceNode(newTimeEl, oldTimeEl);
} else {
dom.appendChild(this.titleContainer_, newTimeEl);
}
}
/**
* @private
*/
setupSteps_() {
this.steps_.forEach((step, index) => {
step = /** @type {!Element} */ (step);
step.setAttribute('step', index+1);
});
}
/**
* @private
*/
showSelectedStep_() {
let selected = 0;
if (this.hasAttribute(SELECTED_ATTR)) {
selected = parseInt(this.getAttribute(SELECTED_ATTR), 0);
} else {
this.setAttribute(SELECTED_ATTR, selected);
return;
}
selected = Math.min(Math.max(0, parseInt(selected, 10)), this.steps_.length - 1);
if (this.currentSelectedStep_ === selected || isNaN(selected)) {
// Either the current step is already selected or an invalid option was provided
// do nothing and return.
return;
}
const stepTitleEl = this.steps_[selected].querySelector('.step-title');
const stepTitle = stepTitleEl ? stepTitleEl.textContent : '';
const stepTitlePrefix = (selected + 1) + '.';
const re = new RegExp(stepTitlePrefix, 'g');
this.fireEvent_(CODELAB_PAGEVIEW_EVENT, {
'page': location.pathname + '#' + selected,
'title': stepTitle.replace(re, '').trim()
});
if (this.currentSelectedStep_ === -1) {
// No previous selected step, so select the correct step with no animation
const stepToSelect = this.steps_[selected];
stepToSelect.setAttribute(SELECTED_ATTR, '');
} else {
if (this.transitionIn_) {
this.transitionIn_.stop();
}
if (this.transitionOut_) {
this.transitionOut_.stop();
}
this.transitionEventHandler_.removeAll();
const transitionInInitialStyle = {};
const transitionInFinalStyle = {
transform: 'translate3d(0, 0, 0)'
};
const transitionOutInitialStyle = {
transform: 'translate3d(0, 0, 0)'
};
const transitionOutFinalStyle = {};
const stepToSelect = this.steps_[selected];
const currentStep = this.steps_[this.currentSelectedStep_];
stepToSelect.setAttribute(ANIMATING_ATTR, '');
if (this.currentSelectedStep_ < selected) {
// Move new step in from the right
transitionInInitialStyle['transform'] = 'translate3d(110%, 0, 0)';
transitionOutFinalStyle['transform'] = 'translate3d(-110%, 0, 0)';
} else {
// Move new step in from the left
transitionInInitialStyle['transform'] = 'translate3d(-110%, 0, 0)';
transitionOutFinalStyle['transform'] = 'translate3d(110%, 0, 0)';
}
const animationProperties = [{
property: 'transform',
duration: ANIMATION_DURATION,
delay: 0,
timing: 'cubic-bezier(0.4, 0, 0.2, 1)'
}];
this.transitionIn_ = new Transition(stepToSelect, ANIMATION_DURATION,
transitionInInitialStyle, transitionInFinalStyle, animationProperties);
this.transitionOut_ = new Transition(currentStep, ANIMATION_DURATION,
transitionOutInitialStyle, transitionOutFinalStyle, animationProperties);
this.transitionIn_.play();
this.transitionOut_.play();
this.transitionEventHandler_.listenOnce(this.transitionIn_,
[TransitionEventType.FINISH, TransitionEventType.STOP], () => {
stepToSelect.setAttribute(SELECTED_ATTR, '');
stepToSelect.removeAttribute(ANIMATING_ATTR);
});
this.transitionEventHandler_.listenOnce(this.transitionOut_,
[TransitionEventType.FINISH, TransitionEventType.STOP], () => {
currentStep.removeAttribute(SELECTED_ATTR);
});
}
this.currentSelectedStep_ = selected;
if (this.nextStepBtn_ && this.prevStepBtn_ && this.doneBtn_) {
if (selected === 0) {
this.prevStepBtn_.setAttribute(DISAPPEAR_ATTR, '');
} else {
this.prevStepBtn_.removeAttribute(DISAPPEAR_ATTR);
}
if (selected === this.steps_.length - 1) {
this.nextStepBtn_.setAttribute(HIDDEN_ATTR, '');
this.doneBtn_.removeAttribute(HIDDEN_ATTR);
this.fireEvent_(CODELAB_ACTION_EVENT, {
'category': 'codelab',
'action': 'complete',
'label': this.title_
});
} else {
this.nextStepBtn_.removeAttribute(HIDDEN_ATTR);
this.doneBtn_.setAttribute(HIDDEN_ATTR, '');
}
}
if (this.drawer_) {
const steps = this.drawer_.querySelectorAll('li');
steps.forEach((step, i) => {
if (i <= selected) {
step.setAttribute(COMPLETED_ATTR, '');
} else {
step.removeAttribute(COMPLETED_ATTR);
}
if (i === selected) {
step.setAttribute(SELECTED_ATTR, '');
step.scrollIntoViewIfNeeded();
} else {
step.removeAttribute(SELECTED_ATTR);
}
});
}
this.updateTimeRemaining_();
if (!this.hasAttribute(DONT_SET_HISTORY_ATTR)) {
this.updateHistoryState(`#${selected}`, true);
}
this.storage_.set(`progress_${this.id_}`, String(this.currentSelectedStep_));
}
/**
* @private
*/
renderDrawer_() {
const feedback = this.getAttribute(FEEDBACK_LINK_ATTR);
const steps = this.steps_.map((step) => step.getAttribute(LABEL_ATTR));
soy.renderElement(this.drawer_, Templates.drawer, {steps, feedback});
}
/**
* @private
* @return {string}
*/
getHomeUrl_() {
const url = new URL(document.location.toString());
let index = url.searchParams.get('index');
if (!index) {
return '/';
}
index = index.replace(/[^a-z0-9\-]+/ig, '');
if (!index || index.trim() === '') {
return '/';
}
if (index === 'index') {
index = '';
}
const u = new URL(index, document.location.origin);
return u.pathname;
}
/**
* @param {string} eventName
* @param {!Object=} detail
* @private
*/
fireEvent_(eventName, detail={}) {
const event = new CustomEvent(eventName, {
detail: detail
});
document.body.dispatchEvent(event);
}
/**
* Fires events for initial page load.
*/
firePageLoadEvents_() {
this.fireEvent_(CODELAB_PAGEVIEW_EVENT, {
'page': location.pathname + '#' + this.currentSelectedStep_,
'title': this.steps_[this.currentSelectedStep_].getAttribute(LABEL_ATTR)
});
window.requestAnimationFrame(() => {
document.body.removeAttribute('unresolved');
this.fireEvent_(CODELAB_ACTION_EVENT, {
'category': 'codelab',
'action': 'ready'
});
});
}
/**
* @private
*/
setupDom_() {
this.steps_ = Array.from(this.querySelectorAll('google-codelab-step'));
soy.renderElement(this, Templates.structure, {
homeUrl: this.getHomeUrl_()
});
this.drawer_ = this.querySelector('#drawer');
this.titleContainer_ = this.querySelector('#codelab-title');
this.stepsContainer_ = this.querySelector('#steps');
this.controls_ = this.querySelector('#controls');
this.prevStepBtn_ = this.querySelector('#controls #previous-step');
this.nextStepBtn_ = this.querySelector('#controls #next-step');
this.doneBtn_ = this.querySelector('#controls #done');
this.steps_.forEach((step) => dom.appendChild(this.stepsContainer_, step));
this.setupSteps_();
this.renderDrawer_();
if (document.location.hash) {
const h = parseInt(document.location.hash.substring(1), 10);
if (!isNaN(h) && h) {
this.setAttribute(SELECTED_ATTR, document.location.hash.substring(1));
}
}
this.id_ = this.getAttribute('id');
const progress = this.storage_.get(`progress_${this.id_}`);
if (progress && progress !== '0') {
this.resumed_ = true;
this.setAttribute(SELECTED_ATTR, progress);
}
this.hasSetup_ = true;
}
}
exports = Codelab;
|
Applied the event to the codelabs object and made it bubble
|
codelab-elements/google-codelab/google_codelab.js
|
Applied the event to the codelabs object and made it bubble
|
<ide><path>odelab-elements/google-codelab/google_codelab.js
<ide> if (this.ready_) {
<ide> this.firePageLoadEvents_();
<ide> } else {
<del> document.body.addEventListener(CODELAB_READY_EVENT,
<add> this.addEventListener(CODELAB_READY_EVENT,
<ide> () => this.firePageLoadEvents_());
<ide> }
<ide> }
<ide> */
<ide> fireEvent_(eventName, detail={}) {
<ide> const event = new CustomEvent(eventName, {
<del> detail: detail
<add> detail: detail,
<add> bubbles: true,
<ide> });
<del> document.body.dispatchEvent(event);
<add> this.dispatchEvent(event);
<ide> }
<ide>
<ide> /**
|
|
Java
|
mit
|
da1a1dce96212bb7350681e775fbf5c2868472bb
| 0 |
cdai/interview
|
package advanced.combinatorial.subset.lc090_subsets2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Given a collection of integers that might contain duplicates, nums, return all possible subsets.
* Note: The solution set must not contain duplicate subsets.
* For example, If nums = [1,2,2], a solution is:
* [
* [2],
* [1],
* [1,2,2],
* [2,2],
* [1,2],
* []
* ]
*/
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().subsetsWithDup(new int[]{1, 2, 2, 2}));
}
// Recursive solution, inspired from 40-Combination Sum II
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums); // error: forget to sort...
doSubset(result, new ArrayList<>(), nums, 0);
return result;
}
private void doSubset(List<List<Integer>> result,
List<Integer> path, int[] nums, int start) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
return;
}
result.add(new ArrayList<>(path));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) continue; // Bypass duplicates
path.add(nums[i]);
doSubset(result, path, nums, i + 1);
path.remove(path.size() - 1);
}
}
// My 2nd from leetcode discuss - iterative DP solution
public List<List<Integer>> subsetsWithDup_iterative(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
Arrays.sort(nums); // must sort for this problem
int size = 0;
for (int i = 0, j = 0; i < nums.length; i++) {
List<List<Integer>> tmp = new ArrayList<>();
j = (i > 0 && nums[i] == nums[i - 1]) ? size : 0;
size = result.size();
for ( ; j < result.size(); j++) {
List<Integer> newSub = new ArrayList<>(result.get(j));
newSub.add(nums[i]);
tmp.add(newSub);
}
result.addAll(tmp);
}
return result;
}
// My 1st: solution from <The Algorithm Design Manual>
public List<List<Integer>> subsetsWithDup1(int[] nums) {
Set<List<Integer>> result = new HashSet<>();
boolean[] presents = new boolean[nums.length];
Arrays.sort(nums);
subset(result, presents, nums, 0);
return new ArrayList<>(result);
}
private void subset(Set<List<Integer>> result, boolean[] presents, int[] nums, int k) {
if (k == nums.length) {
List<Integer> r = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (presents[i]) {
r.add(nums[i]);
}
}
if (!result.contains(r)) {
result.add(r);
}
return;
}
presents[k] = false;
subset(result, presents, nums, k+1);
presents[k] = true;
subset(result, presents, nums, k+1);
}
}
|
1-algorithm/13-leetcode/java/src/advanced/combinatorial/subset/lc090_subsets2/Solution.java
|
package advanced.combinatorial.subset.lc090_subsets2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Given a collection of integers that might contain duplicates, nums, return all possible subsets.
* Note: The solution set must not contain duplicate subsets.
* For example, If nums = [1,2,2], a solution is:
* [
* [2],
* [1],
* [1,2,2],
* [2,2],
* [1,2],
* []
* ]
*/
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().subsetsWithDup(new int[]{1, 2, 2, 2}));
}
// My 2nd from leetcode discuss - iterative DP solution
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
Arrays.sort(nums); // must sort for this problem
int size = 0;
for (int i = 0, j = 0; i < nums.length; i++) {
List<List<Integer>> tmp = new ArrayList<>();
j = (i > 0 && nums[i] == nums[i - 1]) ? size : 0;
size = result.size();
for ( ; j < result.size(); j++) {
List<Integer> newSub = new ArrayList<>(result.get(j));
newSub.add(nums[i]);
tmp.add(newSub);
}
result.addAll(tmp);
}
return result;
}
// My 1st: solution from <The Algorithm Design Manual>
public List<List<Integer>> subsetsWithDup1(int[] nums) {
Set<List<Integer>> result = new HashSet<>();
boolean[] presents = new boolean[nums.length];
Arrays.sort(nums);
subset(result, presents, nums, 0);
return new ArrayList<>(result);
}
private void subset(Set<List<Integer>> result, boolean[] presents, int[] nums, int k) {
if (k == nums.length) {
List<Integer> r = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (presents[i]) {
r.add(nums[i]);
}
}
if (!result.contains(r)) {
result.add(r);
}
return;
}
presents[k] = false;
subset(result, presents, nums, k+1);
presents[k] = true;
subset(result, presents, nums, k+1);
}
}
|
My 3AC
|
1-algorithm/13-leetcode/java/src/advanced/combinatorial/subset/lc090_subsets2/Solution.java
|
My 3AC
|
<ide><path>-algorithm/13-leetcode/java/src/advanced/combinatorial/subset/lc090_subsets2/Solution.java
<ide> System.out.println(new Solution().subsetsWithDup(new int[]{1, 2, 2, 2}));
<ide> }
<ide>
<add> // Recursive solution, inspired from 40-Combination Sum II
<add> public List<List<Integer>> subsetsWithDup(int[] nums) {
<add> List<List<Integer>> result = new ArrayList<>();
<add> Arrays.sort(nums); // error: forget to sort...
<add> doSubset(result, new ArrayList<>(), nums, 0);
<add> return result;
<add> }
<add>
<add> private void doSubset(List<List<Integer>> result,
<add> List<Integer> path, int[] nums, int start) {
<add> if (path.size() == nums.length) {
<add> result.add(new ArrayList<>(path));
<add> return;
<add> }
<add>
<add> result.add(new ArrayList<>(path));
<add> for (int i = start; i < nums.length; i++) {
<add> if (i > start && nums[i] == nums[i - 1]) continue; // Bypass duplicates
<add> path.add(nums[i]);
<add> doSubset(result, path, nums, i + 1);
<add> path.remove(path.size() - 1);
<add> }
<add> }
<add>
<ide> // My 2nd from leetcode discuss - iterative DP solution
<del> public List<List<Integer>> subsetsWithDup(int[] nums) {
<add> public List<List<Integer>> subsetsWithDup_iterative(int[] nums) {
<ide> List<List<Integer>> result = new ArrayList<>();
<ide> result.add(new ArrayList<>());
<ide> Arrays.sort(nums); // must sort for this problem
|
|
Java
|
apache-2.0
|
aa32d50e7aff26c2f360e666aeb65732296237c5
| 0 |
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
|
// Copyright (C) 2012 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.git;
import static com.google.gerrit.server.DeadlineChecker.getTimeoutFormatter;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
import com.google.common.base.Ticker;
import com.google.common.flogger.FluentLogger;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.gerrit.server.CancellationMetrics;
import com.google.gerrit.server.cancellation.RequestStateProvider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ProgressMonitor;
/**
* Progress reporting interface that multiplexes multiple sub-tasks.
*
* <p>Output is of the format:
*
* <pre>
* Task: subA: 1, subB: 75% (3/4) (-)\r
* Task: subA: 2, subB: 75% (3/4), subC: 1 (\)\r
* Task: subA: 2, subB: 100% (4/4), subC: 1 (|)\r
* Task: subA: 4, subB: 100% (4/4), subC: 4, done \n
* </pre>
*
* <p>Callers should try to keep task and sub-task descriptions short, since the output should fit
* on one terminal line. (Note that git clients do not accept terminal control characters, so true
* multi-line progress messages would be impossible.)
*
* <p>Whether the client is disconnected or the deadline is exceeded can be checked by {@link
* #checkIfCancelled(RequestStateProvider.OnCancelled)}. This allows the worker thread to react to
* cancellations and abort its execution and finish gracefully. After a cancellation has been
* signaled the worker thread has 10 * {@link #maxIntervalNanos} to react to the cancellation and
* finish gracefully. If the worker thread doesn't finish gracefully in time after the cancellation
* has been signaled, the future executing the task is forcefully cancelled which means that the
* worker thread gets interrupted and an internal error is returned to the client. To react to
* cancellations it is recommended that the task opens a {@link
* com.google.gerrit.server.cancellation.RequestStateContext} in a try-with-resources block to
* register the {@link MultiProgressMonitor} as a {@link RequestStateProvider}. This way the worker
* thread gets aborted by a {@link com.google.gerrit.server.cancellation.RequestCancelledException}
* when the request is cancelled which allows the worker thread to handle the cancellation
* gracefully by catching this exception (e.g. to return a proper error message). {@link
* com.google.gerrit.server.cancellation.RequestCancelledException} is only thrown when the worker
* thread checks for cancellation via {@link
* com.google.gerrit.server.cancellation.RequestStateContext#abortIfCancelled()}. E.g. this is done
* whenever {@link com.google.gerrit.server.logging.TraceContext.TraceTimer} is opened/closed.
*/
public class MultiProgressMonitor implements RequestStateProvider {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
/** Constant indicating the total work units cannot be predicted. */
public static final int UNKNOWN = 0;
private static final char[] SPINNER_STATES = new char[] {'-', '\\', '|', '/'};
private static final char NO_SPINNER = ' ';
public enum TaskKind {
INDEXING,
RECEIVE_COMMITS;
}
/** Handle for a sub-task. */
public class Task implements ProgressMonitor {
private final String name;
private final int total;
private int count;
private int lastPercent;
Task(String subTaskName, int totalWork) {
this.name = subTaskName;
this.total = totalWork;
}
/**
* Indicate that work has been completed on this sub-task.
*
* <p>Must be called from a worker thread.
*
* @param completed number of work units completed.
*/
@Override
public void update(int completed) {
boolean w = false;
synchronized (MultiProgressMonitor.this) {
count += completed;
if (total != UNKNOWN) {
int percent = count * 100 / total;
if (percent > lastPercent) {
lastPercent = percent;
w = true;
}
}
}
if (w) {
wakeUp();
}
}
/**
* Indicate that this sub-task is finished.
*
* <p>Must be called from a worker thread.
*/
public void end() {
if (total == UNKNOWN && getCount() > 0) {
wakeUp();
}
}
@Override
public void start(int totalTasks) {}
@Override
public void beginTask(String title, int totalWork) {}
@Override
public void endTask() {}
@Override
public boolean isCancelled() {
return false;
}
public int getCount() {
synchronized (MultiProgressMonitor.this) {
return count;
}
}
public int getTotal() {
return total;
}
public String getName() {
return name;
}
public String getTotalDisplay(int total) {
return String.valueOf(total);
}
}
/** Handle for a sub-task whose total work can be updated while the task is in progress. */
public class VolatileTask extends Task {
protected AtomicInteger volatileTotal;
protected AtomicBoolean isTotalFinalized = new AtomicBoolean(false);
public VolatileTask(String subTaskName) {
super(subTaskName, UNKNOWN);
volatileTotal = new AtomicInteger(UNKNOWN);
}
/**
* Update the total work for this sub-task.
*
* <p>Intended to be called from a worker thread.
*
* @param workUnits number of work units to be added to existing total work.
*/
public void updateTotal(int workUnits) {
if (!isTotalFinalized.get()) {
volatileTotal.addAndGet(workUnits);
} else {
logger.atWarning().log(
"Total work has been finalized on sub-task %s and cannot be updated", getName());
}
}
/**
* Mark the total on this sub-task as unmodifiable.
*
* <p>Intended to be called from a worker thread.
*/
public void finalizeTotal() {
isTotalFinalized.set(true);
}
@Override
public int getTotal() {
return volatileTotal.get();
}
@Override
public String getTotalDisplay(int total) {
return super.getTotalDisplay(total) + (isTotalFinalized.get() ? "" : "+");
}
}
public interface Factory {
MultiProgressMonitor create(OutputStream out, TaskKind taskKind, String taskName);
MultiProgressMonitor create(
OutputStream out,
TaskKind taskKind,
String taskName,
long maxIntervalTime,
TimeUnit maxIntervalUnit);
}
private final CancellationMetrics cancellationMetrics;
private final OutputStream out;
private final TaskKind taskKind;
private final String taskName;
private final List<Task> tasks = new CopyOnWriteArrayList<>();
private int spinnerIndex;
private char spinnerState = NO_SPINNER;
private boolean done;
private boolean clientDisconnected;
private boolean deadlineExceeded;
private boolean forcefulTermination;
private Optional<Long> timeout = Optional.empty();
private final long maxIntervalNanos;
private final Ticker ticker;
/**
* Create a new progress monitor for multiple sub-tasks.
*
* @param out stream for writing progress messages.
* @param taskName name of the overall task.
*/
@SuppressWarnings("UnusedMethod")
@AssistedInject
private MultiProgressMonitor(
CancellationMetrics cancellationMetrics,
Ticker ticker,
@Assisted OutputStream out,
@Assisted TaskKind taskKind,
@Assisted String taskName) {
this(cancellationMetrics, ticker, out, taskKind, taskName, 500, MILLISECONDS);
}
/**
* Create a new progress monitor for multiple sub-tasks.
*
* @param out stream for writing progress messages.
* @param taskName name of the overall task.
* @param maxIntervalTime maximum interval between progress messages.
* @param maxIntervalUnit time unit for progress interval.
*/
@AssistedInject
private MultiProgressMonitor(
CancellationMetrics cancellationMetrics,
Ticker ticker,
@Assisted OutputStream out,
@Assisted TaskKind taskKind,
@Assisted String taskName,
@Assisted long maxIntervalTime,
@Assisted TimeUnit maxIntervalUnit) {
this.cancellationMetrics = cancellationMetrics;
this.ticker = ticker;
this.out = out;
this.taskKind = taskKind;
this.taskName = taskName;
maxIntervalNanos = NANOSECONDS.convert(maxIntervalTime, maxIntervalUnit);
}
/**
* Wait for a task managed by a {@link Future}, with no timeout.
*
* @see #waitFor(Future, long, TimeUnit, long, TimeUnit)
*/
public <T> T waitFor(Future<T> workerFuture) {
try {
return waitFor(
workerFuture,
/* taskTimeoutTime= */ 0,
/* taskTimeoutUnit= */ null,
/* cancellationTimeoutTime= */ 0,
/* cancellationTimeoutUnit= */ null);
} catch (TimeoutException e) {
throw new IllegalStateException("timout exception without setting a timeout", e);
}
}
/**
* Wait for a task managed by a {@link Future}.
*
* <p>Must be called from the main thread, <em>not</em> a worker thread. Once a worker thread
* calls {@link #end()}, the future has an additional {@code maxInterval} to finish before it is
* forcefully cancelled and {@link ExecutionException} is thrown.
*
* @see #waitForNonFinalTask(Future, long, TimeUnit, long, TimeUnit)
* @param workerFuture a future that returns when worker threads are finished.
* @param taskTimeoutTime overall timeout for the task; the future gets a cancellation signal
* after this timeout is exceeded; non-positive values indicate no timeout.
* @param taskTimeoutUnit unit for overall task timeout.
* @param cancellationTimeoutTime timeout for the task to react to the cancellation signal; if the
* task doesn't terminate within this time it is forcefully cancelled; non-positive values
* indicate no timeout.
* @param cancellationTimeoutUnit unit for the cancellation timeout.
* @throws TimeoutException if this thread or a worker thread was interrupted, the worker was
* cancelled, or timed out waiting for a worker to call {@link #end()}.
*/
public <T> T waitFor(
Future<T> workerFuture,
long taskTimeoutTime,
TimeUnit taskTimeoutUnit,
long cancellationTimeoutTime,
TimeUnit cancellationTimeoutUnit)
throws TimeoutException {
T t =
waitForNonFinalTask(
workerFuture,
taskTimeoutTime,
taskTimeoutUnit,
cancellationTimeoutTime,
cancellationTimeoutUnit);
synchronized (this) {
if (!done) {
// The worker may not have called end() explicitly, which is likely a
// programming error.
logger.atWarning().log("MultiProgressMonitor worker did not call end() before returning");
end();
}
}
sendDone();
return t;
}
/**
* Wait for a non-final task managed by a {@link Future}, with no timeout.
*
* @see #waitForNonFinalTask(Future, long, TimeUnit, long, TimeUnit)
*/
public <T> T waitForNonFinalTask(Future<T> workerFuture) {
try {
return waitForNonFinalTask(workerFuture, 0, null, 0, null);
} catch (TimeoutException e) {
throw new IllegalStateException("timout exception without setting a timeout", e);
}
}
/**
* Wait for a task managed by a {@link Future}. This call does not expect the worker thread to
* call {@link #end()}. It is intended to be used to track a non-final task.
*
* @param workerFuture a future that returns when worker threads are finished.
* @param taskTimeoutTime overall timeout for the task; the future is forcefully cancelled if the
* task exceeds the timeout. Non-positive values indicate no timeout.
* @param taskTimeoutUnit unit for overall task timeout.
* @param cancellationTimeoutTime timeout for the task to react to the cancellation signal; if the
* task doesn't terminate within this time it is forcefully cancelled; non-positive values
* indicate no timeout.
* @param cancellationTimeoutUnit unit for the cancellation timeout.
* @throws TimeoutException if this thread or a worker thread was interrupted, the worker was
* cancelled, or timed out waiting for a worker to call {@link #end()}.
*/
public <T> T waitForNonFinalTask(
Future<T> workerFuture,
long taskTimeoutTime,
TimeUnit taskTimeoutUnit,
long cancellationTimeoutTime,
TimeUnit cancellationTimeoutUnit)
throws TimeoutException {
long overallStart = ticker.read();
long cancellationNanos =
cancellationTimeoutTime > 0
? NANOSECONDS.convert(cancellationTimeoutTime, cancellationTimeoutUnit)
: 0;
long deadline;
if (taskTimeoutTime > 0) {
timeout = Optional.of(NANOSECONDS.convert(taskTimeoutTime, taskTimeoutUnit));
deadline = overallStart + timeout.get();
} else {
deadline = 0;
}
synchronized (this) {
long left = maxIntervalNanos;
while (!workerFuture.isDone() && !done) {
long start = ticker.read();
try {
// Conditions below gives better granularity for timeouts.
// Originally, code always used fixed interval:
// NANOSECONDS.timedWait(this, maxIntervalNanos);
// As a result, the actual check for timeouts happened only every maxIntervalNanos
// (default value 500ms); so even if timout was set to 1ms, the actual timeout was 500ms.
// This is not a big issue, however it made our tests for timeouts flaky. For example,
// some tests in the CancellationIT set timeout to 1ms and expect that server returns
// timeout. However, server often returned OK result, because a request takes less than
// 500ms.
if (deadlineExceeded || deadline == 0) {
// We want to set deadlineExceeded flag as earliest as possible. If it is already
// set - there is no reason to wait less than maxIntervalNanos
NANOSECONDS.timedWait(this, maxIntervalNanos);
} else if (start <= deadline) {
// if deadlineExceeded is not set, then we should wait until deadline, but no longer
// than maxIntervalNanos (because we want to report a progress every maxIntervalNanos).
NANOSECONDS.timedWait(this, Math.min(deadline - start + 1, maxIntervalNanos));
}
} catch (InterruptedException e) {
throw new UncheckedExecutionException(e);
}
// Send an update on every wakeup (manual or spurious), but only move
// the spinner every maxInterval.
long now = ticker.read();
if (deadline > 0 && now > deadline) {
if (!deadlineExceeded) {
logger.atFine().log(
"deadline exceeded after %sms, signaling cancellation (timeout=%sms, task=%s(%s))",
MILLISECONDS.convert(now - overallStart, NANOSECONDS),
MILLISECONDS.convert(now - deadline, NANOSECONDS),
taskKind,
taskName);
}
deadlineExceeded = true;
// After setting deadlineExceeded = true give the cancellationNanos to react to the
// cancellation and return gracefully.
if (now > deadline + cancellationNanos) {
// The worker didn't react to the cancellation, cancel it forcefully by an interrupt.
workerFuture.cancel(true);
forcefulTermination = true;
if (workerFuture.isCancelled()) {
logger.atWarning().log(
"MultiProgressMonitor worker killed after %sms, cancelled (timeout=%sms, task=%s(%s))",
MILLISECONDS.convert(now - overallStart, NANOSECONDS),
MILLISECONDS.convert(now - deadline, NANOSECONDS),
taskKind,
taskName);
if (taskKind == TaskKind.RECEIVE_COMMITS) {
cancellationMetrics.countForcefulReceiveTimeout();
}
}
break;
}
}
left -= now - start;
if (left <= 0) {
moveSpinner();
left = maxIntervalNanos;
}
sendUpdate();
}
if (deadlineExceeded && !forcefulTermination && taskKind == TaskKind.RECEIVE_COMMITS) {
cancellationMetrics.countGracefulReceiveTimeout();
}
wakeUp();
}
// The loop exits as soon as the worker calls end(), but we give it another
// 2 x maxIntervalNanos to finish up and return.
try {
return workerFuture.get(2 * maxIntervalNanos, NANOSECONDS);
} catch (InterruptedException | CancellationException e) {
logger.atWarning().withCause(e).log(
"unable to finish processing (task=%s(%s))", taskKind, taskName);
throw new UncheckedExecutionException(e);
} catch (TimeoutException e) {
workerFuture.cancel(true);
throw e;
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e);
}
}
private synchronized void wakeUp() {
notifyAll();
}
/**
* Begin a sub-task.
*
* @param subTask sub-task name.
* @param subTaskWork total work units in sub-task, or {@link #UNKNOWN}.
* @return sub-task handle.
*/
public Task beginSubTask(String subTask, int subTaskWork) {
Task task = new Task(subTask, subTaskWork);
tasks.add(task);
return task;
}
/**
* Begin a sub-task whose total work can be updated.
*
* @param subTask sub-task name.
* @return sub-task handle.
*/
public VolatileTask beginVolatileSubTask(String subTask) {
VolatileTask task = new VolatileTask(subTask);
tasks.add(task);
return task;
}
/**
* End the overall task.
*
* <p>Must be called from a worker thread.
*/
public synchronized void end() {
done = true;
wakeUp();
}
private void sendDone() {
spinnerState = NO_SPINNER;
StringBuilder s = format();
boolean any = false;
for (Task t : tasks) {
if (t.count != 0) {
any = true;
break;
}
}
if (any) {
s.append(",");
}
s.append(" done \n");
send(s);
}
private void moveSpinner() {
spinnerIndex = (spinnerIndex + 1) % SPINNER_STATES.length;
spinnerState = SPINNER_STATES[spinnerIndex];
}
private void sendUpdate() {
send(format());
}
private StringBuilder format() {
StringBuilder s = new StringBuilder().append("\r").append(taskName).append(':');
if (!tasks.isEmpty()) {
boolean first = true;
for (Task t : tasks) {
int count = t.getCount();
int total = t.getTotal();
if (count == 0) {
continue;
}
if (!first) {
s.append(',');
} else {
first = false;
}
s.append(' ');
if (!Strings.isNullOrEmpty(t.name)) {
s.append(t.name).append(": ");
}
if (total == UNKNOWN) {
s.append(count);
} else {
s.append(
String.format("%d%% (%d/%s)", count * 100 / total, count, t.getTotalDisplay(total)));
}
}
}
if (spinnerState != NO_SPINNER) {
// Don't output a spinner until the alarm fires for the first time.
s.append(" (").append(spinnerState).append(')');
}
return s;
}
private void send(StringBuilder s) {
String progress = s.toString();
logger.atInfo().atMostEvery(1, MINUTES).log(
"%s", CharMatcher.javaIsoControl().removeFrom(progress));
if (!clientDisconnected) {
try {
out.write(Constants.encode(progress));
out.flush();
} catch (IOException e) {
logger.atWarning().withCause(e).log(
"Sending progress to client failed. Stop sending updates for task %s(%s)",
taskKind, taskName);
clientDisconnected = true;
}
}
}
@Override
public void checkIfCancelled(OnCancelled onCancelled) {
if (clientDisconnected) {
onCancelled.onCancel(RequestStateProvider.Reason.CLIENT_CLOSED_REQUEST, /* message= */ null);
} else if (deadlineExceeded) {
onCancelled.onCancel(
RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED,
timeout
.map(
taskKind == TaskKind.RECEIVE_COMMITS
? getTimeoutFormatter("receive.timeout")
: getTimeoutFormatter("timeout"))
.orElse(null));
}
}
}
|
java/com/google/gerrit/server/git/MultiProgressMonitor.java
|
// Copyright (C) 2012 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.git;
import static com.google.gerrit.server.DeadlineChecker.getTimeoutFormatter;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
import com.google.common.base.Ticker;
import com.google.common.flogger.FluentLogger;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.gerrit.server.CancellationMetrics;
import com.google.gerrit.server.cancellation.RequestStateProvider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ProgressMonitor;
/**
* Progress reporting interface that multiplexes multiple sub-tasks.
*
* <p>Output is of the format:
*
* <pre>
* Task: subA: 1, subB: 75% (3/4) (-)\r
* Task: subA: 2, subB: 75% (3/4), subC: 1 (\)\r
* Task: subA: 2, subB: 100% (4/4), subC: 1 (|)\r
* Task: subA: 4, subB: 100% (4/4), subC: 4, done \n
* </pre>
*
* <p>Callers should try to keep task and sub-task descriptions short, since the output should fit
* on one terminal line. (Note that git clients do not accept terminal control characters, so true
* multi-line progress messages would be impossible.)
*
* <p>Whether the client is disconnected or the deadline is exceeded can be checked by {@link
* #checkIfCancelled(RequestStateProvider.OnCancelled)}. This allows the worker thread to react to
* cancellations and abort its execution and finish gracefully. After a cancellation has been
* signaled the worker thread has 10 * {@link #maxIntervalNanos} to react to the cancellation and
* finish gracefully. If the worker thread doesn't finish gracefully in time after the cancellation
* has been signaled, the future executing the task is forcefully cancelled which means that the
* worker thread gets interrupted and an internal error is returned to the client. To react to
* cancellations it is recommended that the task opens a {@link
* com.google.gerrit.server.cancellation.RequestStateContext} in a try-with-resources block to
* register the {@link MultiProgressMonitor} as a {@link RequestStateProvider}. This way the worker
* thread gets aborted by a {@link com.google.gerrit.server.cancellation.RequestCancelledException}
* when the request is cancelled which allows the worker thread to handle the cancellation
* gracefully by catching this exception (e.g. to return a proper error message). {@link
* com.google.gerrit.server.cancellation.RequestCancelledException} is only thrown when the worker
* thread checks for cancellation via {@link
* com.google.gerrit.server.cancellation.RequestStateContext#abortIfCancelled()}. E.g. this is done
* whenever {@link com.google.gerrit.server.logging.TraceContext.TraceTimer} is opened/closed.
*/
public class MultiProgressMonitor implements RequestStateProvider {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
/** Constant indicating the total work units cannot be predicted. */
public static final int UNKNOWN = 0;
private static final char[] SPINNER_STATES = new char[] {'-', '\\', '|', '/'};
private static final char NO_SPINNER = ' ';
public enum TaskKind {
INDEXING,
RECEIVE_COMMITS;
}
/** Handle for a sub-task. */
public class Task implements ProgressMonitor {
private final String name;
private final int total;
private int count;
private int lastPercent;
Task(String subTaskName, int totalWork) {
this.name = subTaskName;
this.total = totalWork;
}
/**
* Indicate that work has been completed on this sub-task.
*
* <p>Must be called from a worker thread.
*
* @param completed number of work units completed.
*/
@Override
public void update(int completed) {
boolean w = false;
synchronized (MultiProgressMonitor.this) {
count += completed;
if (total != UNKNOWN) {
int percent = count * 100 / total;
if (percent > lastPercent) {
lastPercent = percent;
w = true;
}
}
}
if (w) {
wakeUp();
}
}
/**
* Indicate that this sub-task is finished.
*
* <p>Must be called from a worker thread.
*/
public void end() {
if (total == UNKNOWN && getCount() > 0) {
wakeUp();
}
}
@Override
public void start(int totalTasks) {}
@Override
public void beginTask(String title, int totalWork) {}
@Override
public void endTask() {}
@Override
public boolean isCancelled() {
return false;
}
public int getCount() {
synchronized (MultiProgressMonitor.this) {
return count;
}
}
public int getTotal() {
return total;
}
public String getName() {
return name;
}
public String getTotalDisplay(int total) {
return String.valueOf(total);
}
}
/** Handle for a sub-task whose total work can be updated while the task is in progress. */
public class VolatileTask extends Task {
protected AtomicInteger volatileTotal;
protected AtomicBoolean isTotalFinalized = new AtomicBoolean(false);
public VolatileTask(String subTaskName) {
super(subTaskName, UNKNOWN);
volatileTotal = new AtomicInteger(UNKNOWN);
}
/**
* Update the total work for this sub-task.
*
* <p>Intended to be called from a worker thread.
*
* @param workUnits number of work units to be added to existing total work.
*/
public void updateTotal(int workUnits) {
if (!isTotalFinalized.get()) {
volatileTotal.addAndGet(workUnits);
} else {
logger.atWarning().log(
"Total work has been finalized on sub-task %s and cannot be updated", getName());
}
}
/**
* Mark the total on this sub-task as unmodifiable.
*
* <p>Intended to be called from a worker thread.
*/
public void finalizeTotal() {
isTotalFinalized.set(true);
}
@Override
public int getTotal() {
return volatileTotal.get();
}
@Override
public String getTotalDisplay(int total) {
return super.getTotalDisplay(total) + (isTotalFinalized.get() ? "" : "+");
}
}
public interface Factory {
MultiProgressMonitor create(OutputStream out, TaskKind taskKind, String taskName);
MultiProgressMonitor create(
OutputStream out,
TaskKind taskKind,
String taskName,
long maxIntervalTime,
TimeUnit maxIntervalUnit);
}
private final CancellationMetrics cancellationMetrics;
private final OutputStream out;
private final TaskKind taskKind;
private final String taskName;
private final List<Task> tasks = new CopyOnWriteArrayList<>();
private int spinnerIndex;
private char spinnerState = NO_SPINNER;
private boolean done;
private boolean clientDisconnected;
private boolean deadlineExceeded;
private boolean forcefulTermination;
private Optional<Long> timeout = Optional.empty();
private final long maxIntervalNanos;
private final Ticker ticker;
/**
* Create a new progress monitor for multiple sub-tasks.
*
* @param out stream for writing progress messages.
* @param taskName name of the overall task.
*/
@SuppressWarnings("UnusedMethod")
@AssistedInject
private MultiProgressMonitor(
CancellationMetrics cancellationMetrics,
Ticker ticker,
@Assisted OutputStream out,
@Assisted TaskKind taskKind,
@Assisted String taskName) {
this(cancellationMetrics, ticker, out, taskKind, taskName, 500, MILLISECONDS);
}
/**
* Create a new progress monitor for multiple sub-tasks.
*
* @param out stream for writing progress messages.
* @param taskName name of the overall task.
* @param maxIntervalTime maximum interval between progress messages.
* @param maxIntervalUnit time unit for progress interval.
*/
@AssistedInject
private MultiProgressMonitor(
CancellationMetrics cancellationMetrics,
Ticker ticker,
@Assisted OutputStream out,
@Assisted TaskKind taskKind,
@Assisted String taskName,
@Assisted long maxIntervalTime,
@Assisted TimeUnit maxIntervalUnit) {
this.cancellationMetrics = cancellationMetrics;
this.ticker = ticker;
this.out = out;
this.taskKind = taskKind;
this.taskName = taskName;
maxIntervalNanos = NANOSECONDS.convert(maxIntervalTime, maxIntervalUnit);
}
/**
* Wait for a task managed by a {@link Future}, with no timeout.
*
* @see #waitFor(Future, long, TimeUnit, long, TimeUnit)
*/
public <T> T waitFor(Future<T> workerFuture) {
try {
return waitFor(
workerFuture,
/* taskTimeoutTime= */ 0,
/* taskTimeoutUnit= */ null,
/* cancellationTimeoutTime= */ 0,
/* cancellationTimeoutUnit= */ null);
} catch (TimeoutException e) {
throw new IllegalStateException("timout exception without setting a timeout", e);
}
}
/**
* Wait for a task managed by a {@link Future}.
*
* <p>Must be called from the main thread, <em>not</em> a worker thread. Once a worker thread
* calls {@link #end()}, the future has an additional {@code maxInterval} to finish before it is
* forcefully cancelled and {@link ExecutionException} is thrown.
*
* @see #waitForNonFinalTask(Future, long, TimeUnit, long, TimeUnit)
* @param workerFuture a future that returns when worker threads are finished.
* @param taskTimeoutTime overall timeout for the task; the future gets a cancellation signal
* after this timeout is exceeded; non-positive values indicate no timeout.
* @param taskTimeoutUnit unit for overall task timeout.
* @param cancellationTimeoutTime timeout for the task to react to the cancellation signal; if the
* task doesn't terminate within this time it is forcefully cancelled; non-positive values
* indicate no timeout.
* @param cancellationTimeoutUnit unit for the cancellation timeout.
* @throws TimeoutException if this thread or a worker thread was interrupted, the worker was
* cancelled, or timed out waiting for a worker to call {@link #end()}.
*/
public <T> T waitFor(
Future<T> workerFuture,
long taskTimeoutTime,
TimeUnit taskTimeoutUnit,
long cancellationTimeoutTime,
TimeUnit cancellationTimeoutUnit)
throws TimeoutException {
T t =
waitForNonFinalTask(
workerFuture,
taskTimeoutTime,
taskTimeoutUnit,
cancellationTimeoutTime,
cancellationTimeoutUnit);
synchronized (this) {
if (!done) {
// The worker may not have called end() explicitly, which is likely a
// programming error.
logger.atWarning().log("MultiProgressMonitor worker did not call end() before returning");
end();
}
}
sendDone();
return t;
}
/**
* Wait for a non-final task managed by a {@link Future}, with no timeout.
*
* @see #waitForNonFinalTask(Future, long, TimeUnit, long, TimeUnit)
*/
public <T> T waitForNonFinalTask(Future<T> workerFuture) {
try {
return waitForNonFinalTask(workerFuture, 0, null, 0, null);
} catch (TimeoutException e) {
throw new IllegalStateException("timout exception without setting a timeout", e);
}
}
/**
* Wait for a task managed by a {@link Future}. This call does not expect the worker thread to
* call {@link #end()}. It is intended to be used to track a non-final task.
*
* @param workerFuture a future that returns when worker threads are finished.
* @param taskTimeoutTime overall timeout for the task; the future is forcefully cancelled if the
* task exceeds the timeout. Non-positive values indicate no timeout.
* @param taskTimeoutUnit unit for overall task timeout.
* @param cancellationTimeoutTime timeout for the task to react to the cancellation signal; if the
* task doesn't terminate within this time it is forcefully cancelled; non-positive values
* indicate no timeout.
* @param cancellationTimeoutUnit unit for the cancellation timeout.
* @throws TimeoutException if this thread or a worker thread was interrupted, the worker was
* cancelled, or timed out waiting for a worker to call {@link #end()}.
*/
public <T> T waitForNonFinalTask(
Future<T> workerFuture,
long taskTimeoutTime,
TimeUnit taskTimeoutUnit,
long cancellationTimeoutTime,
TimeUnit cancellationTimeoutUnit)
throws TimeoutException {
long overallStart = ticker.read();
long cancellationNanos =
cancellationTimeoutTime > 0
? NANOSECONDS.convert(cancellationTimeoutTime, cancellationTimeoutUnit)
: 0;
long deadline;
if (taskTimeoutTime > 0) {
timeout = Optional.of(NANOSECONDS.convert(taskTimeoutTime, taskTimeoutUnit));
deadline = overallStart + timeout.get();
} else {
deadline = 0;
}
synchronized (this) {
long left = maxIntervalNanos;
while (!workerFuture.isDone() && !done) {
long start = ticker.read();
try {
// Conditions below gives better granularity for timeouts.
// Originally, code always used fixed interval:
// NANOSECONDS.timedWait(this, maxIntervalNanos);
// As a result, the actual check for timeouts happened only every maxIntervalNanos
// (default value 500ms); so even if timout was set to 1ms, the actual timeout was 500ms.
// This is not a big issue, however it made our tests for timeouts flaky. For example,
// some tests in the CancellationIT set timeout to 1ms and expect that server returns
// timeout. However, server often returned OK result, because a request takes less than
// 500ms.
if (deadlineExceeded || deadline == 0) {
// We want to set deadlineExceeded flag as earliest as possible. If it is already
// set - there is no reason to wait less than maxIntervalNanos
NANOSECONDS.timedWait(this, maxIntervalNanos);
} else if (start <= deadline) {
// if deadlineExceeded is not set, then we should wait until deadline, but no longer
// than maxIntervalNanos (because we want to report a progress every maxIntervalNanos).
NANOSECONDS.timedWait(this, Math.min(deadline - start + 1, maxIntervalNanos));
}
} catch (InterruptedException e) {
throw new UncheckedExecutionException(e);
}
// Send an update on every wakeup (manual or spurious), but only move
// the spinner every maxInterval.
long now = ticker.read();
if (deadline > 0 && now > deadline) {
if (!deadlineExceeded) {
logger.atFine().log(
"deadline exceeded after %sms, signaling cancellation (timeout=%sms, task=%s(%s))",
MILLISECONDS.convert(now - overallStart, NANOSECONDS),
MILLISECONDS.convert(now - deadline, NANOSECONDS),
taskKind,
taskName);
}
deadlineExceeded = true;
// After setting deadlineExceeded = true give the cancellationNanos to react to the
// cancellation and return gracefully.
if (now > deadline + cancellationNanos) {
// The worker didn't react to the cancellation, cancel it forcefully by an interrupt.
workerFuture.cancel(true);
forcefulTermination = true;
if (workerFuture.isCancelled()) {
logger.atWarning().log(
"MultiProgressMonitor worker killed after %sms, cancelled (timeout=%sms, task=%s(%s))",
MILLISECONDS.convert(now - overallStart, NANOSECONDS),
MILLISECONDS.convert(now - deadline, NANOSECONDS),
taskKind,
taskName);
if (taskKind == TaskKind.RECEIVE_COMMITS) {
cancellationMetrics.countForcefulReceiveTimeout();
}
}
break;
}
}
left -= now - start;
if (left <= 0) {
moveSpinner();
left = maxIntervalNanos;
}
sendUpdate();
}
if (deadlineExceeded && !forcefulTermination && taskKind == TaskKind.RECEIVE_COMMITS) {
cancellationMetrics.countGracefulReceiveTimeout();
}
wakeUp();
}
// The loop exits as soon as the worker calls end(), but we give it another
// 2 x maxIntervalNanos to finish up and return.
try {
return workerFuture.get(2 * maxIntervalNanos, NANOSECONDS);
} catch (InterruptedException | CancellationException e) {
logger.atWarning().withCause(e).log(
"unable to finish processing (task=%s(%s))", taskKind, taskName);
throw new UncheckedExecutionException(e);
} catch (TimeoutException e) {
workerFuture.cancel(true);
throw e;
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e);
}
}
private synchronized void wakeUp() {
notifyAll();
}
/**
* Begin a sub-task.
*
* @param subTask sub-task name.
* @param subTaskWork total work units in sub-task, or {@link #UNKNOWN}.
* @return sub-task handle.
*/
public Task beginSubTask(String subTask, int subTaskWork) {
Task task = new Task(subTask, subTaskWork);
tasks.add(task);
return task;
}
/**
* Begin a sub-task whose total work can be updated.
*
* @param subTask sub-task name.
* @return sub-task handle.
*/
public VolatileTask beginVolatileSubTask(String subTask) {
VolatileTask task = new VolatileTask(subTask);
tasks.add(task);
return task;
}
/**
* End the overall task.
*
* <p>Must be called from a worker thread.
*/
public synchronized void end() {
done = true;
wakeUp();
}
private void sendDone() {
spinnerState = NO_SPINNER;
StringBuilder s = format();
boolean any = false;
for (Task t : tasks) {
if (t.count != 0) {
any = true;
break;
}
}
if (any) {
s.append(",");
}
s.append(" done \n");
send(s);
}
private void moveSpinner() {
spinnerIndex = (spinnerIndex + 1) % SPINNER_STATES.length;
spinnerState = SPINNER_STATES[spinnerIndex];
}
private void sendUpdate() {
send(format());
}
private StringBuilder format() {
StringBuilder s = new StringBuilder().append("\r").append(taskName).append(':');
if (!tasks.isEmpty()) {
boolean first = true;
for (Task t : tasks) {
int count = t.getCount();
int total = t.getTotal();
if (count == 0) {
continue;
}
if (!first) {
s.append(',');
} else {
first = false;
}
s.append(' ');
if (!Strings.isNullOrEmpty(t.name)) {
s.append(t.name).append(": ");
}
if (total == UNKNOWN) {
s.append(count);
} else {
s.append(
String.format("%d%% (%d/%s)", count * 100 / total, count, t.getTotalDisplay(total)));
}
}
}
if (spinnerState != NO_SPINNER) {
// Don't output a spinner until the alarm fires for the first time.
s.append(" (").append(spinnerState).append(')');
}
return s;
}
private void send(StringBuilder s) {
String progress = s.toString();
logger.atInfo().atMostEvery(1, MINUTES).log(CharMatcher.javaIsoControl().removeFrom(progress));
if (!clientDisconnected) {
try {
out.write(Constants.encode(progress));
out.flush();
} catch (IOException e) {
logger.atWarning().withCause(e).log(
"Sending progress to client failed. Stop sending updates for task %s(%s)",
taskKind, taskName);
clientDisconnected = true;
}
}
}
@Override
public void checkIfCancelled(OnCancelled onCancelled) {
if (clientDisconnected) {
onCancelled.onCancel(RequestStateProvider.Reason.CLIENT_CLOSED_REQUEST, /* message= */ null);
} else if (deadlineExceeded) {
onCancelled.onCancel(
RequestStateProvider.Reason.SERVER_DEADLINE_EXCEEDED,
timeout
.map(
taskKind == TaskKind.RECEIVE_COMMITS
? getTimeoutFormatter("receive.timeout")
: getTimeoutFormatter("timeout"))
.orElse(null));
}
}
}
|
Fix FloggerLogString error
Arguments to log(String) must be compile-time constants or parameters
annotated with @CompileTimeConstant. Otherwise, we use Flogger's
formatting log methods as in this change.
Release-Notes: skip
Change-Id: I5cc1f2eae1d11562b4e18625536df2a2b7e5767f
|
java/com/google/gerrit/server/git/MultiProgressMonitor.java
|
Fix FloggerLogString error
|
<ide><path>ava/com/google/gerrit/server/git/MultiProgressMonitor.java
<ide>
<ide> private void send(StringBuilder s) {
<ide> String progress = s.toString();
<del> logger.atInfo().atMostEvery(1, MINUTES).log(CharMatcher.javaIsoControl().removeFrom(progress));
<add> logger.atInfo().atMostEvery(1, MINUTES).log(
<add> "%s", CharMatcher.javaIsoControl().removeFrom(progress));
<ide> if (!clientDisconnected) {
<ide> try {
<ide> out.write(Constants.encode(progress));
|
|
Java
|
epl-1.0
|
376b9d32900a86ae2f26c4413022de8bb56beaf4
| 0 |
rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse
|
package com.redhat.ceylon.eclipse.code.editor;
import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IBreakpointManager;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.debug.core.model.IDebugElement;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.ISuspendResume;
import org.eclipse.debug.ui.actions.IRunToLineTarget;
import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget;
import org.eclipse.debug.ui.actions.RunToLineHandler;
import org.eclipse.jdt.debug.core.IJavaDebugTarget;
import org.eclipse.jdt.debug.core.IJavaLineBreakpoint;
import org.eclipse.jdt.debug.core.IJavaStratumLineBreakpoint;
import org.eclipse.jdt.debug.core.JDIDebugModel;
import org.eclipse.jdt.debug.ui.IJavaDebugUIConstants;
import org.eclipse.jdt.internal.debug.ui.BreakpointUtils;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.ide.FileStoreEditorInput;
import com.redhat.ceylon.model.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.core.external.ExternalSourceArchiveManager;
import com.redhat.ceylon.eclipse.core.model.IResourceAware;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget, IRunToLineTarget {
private static final String JDT_DEBUG_PLUGIN_ID = "org.eclipse.jdt.debug";
public ToggleBreakpointAdapter() {}
static interface BreakpointAction {
void doIt(ITextSelection selection, Map.Entry<Integer, Node> firstValidLocation, IFile sourceFile) throws CoreException;
}
public void doOnBreakpoints(IWorkbenchPart part, ISelection selection, BreakpointAction action) throws CoreException {
if (selection instanceof ITextSelection) {
ITextSelection textSel= (ITextSelection) selection;
IEditorPart editorPart= (IEditorPart) part.getAdapter(IEditorPart.class);
//TODO: handle org.eclipse.ui.ide.FileStoreEditorInput
// to set breakpoints in code from archives
IEditorInput editorInput = editorPart.getEditorInput();
final IFile origSrcFile = getSourceFile(editorInput);
int line = textSel.getStartLine();
boolean emptyLine = true;
Map.Entry<Integer, Node> location = null;
try {
CeylonEditor editor = (CeylonEditor) editorPart;
IDocument document = editor.getCeylonSourceViewer().getDocument();
int lineCount = document.getNumberOfLines();
String text = null;
while (line < lineCount) {
final IRegion lineInformation = document.getLineInformation(line);
text = document.get(lineInformation.getOffset(),
lineInformation.getLength()).trim();
if (! text.isEmpty()) {
emptyLine = false;
break;
}
line ++;
};
if (!emptyLine) {
Tree.CompilationUnit rootNode = editor.getParseController().getLastCompilationUnit();
if (rootNode != null) {
location = getFirstValidLocation(rootNode, document, textSel);
}
}
} catch (Exception e) {
e.printStackTrace();
}
action.doIt(textSel, location, origSrcFile);
}
}
public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
doOnBreakpoints(part, selection, new BreakpointAction() {
@Override
public void doIt(final ITextSelection selection, final Map.Entry<Integer, Node> firstValidLocation,
final IFile sourceFile) throws CoreException {
final int requestedLineNumber = selection.getStartLine();
IWorkspaceRunnable wr = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
IMarker marker = findBreakpointMarker(sourceFile, requestedLineNumber + 1);
if (marker!=null) {
// The following will delete the associated marker
clearLineBreakpoint(sourceFile, requestedLineNumber + 1);
} else if (firstValidLocation != null) {
// The following will create a marker as a side-effect
createLineBreakpoint(sourceFile, firstValidLocation.getKey() + 1, null, false);
}
}
};
try {
getWorkspace().run(wr, null);
}
catch (CoreException e) {
throw new DebugException(e.getStatus());
}
}
});
}
private IFile getSourceFile(IEditorInput editorInput) {
final IFile origSrcFile;
if (editorInput instanceof IFileEditorInput) {
origSrcFile= ((IFileEditorInput)editorInput).getFile();
} else if (editorInput instanceof FileStoreEditorInput) {
URI uri = ((FileStoreEditorInput) editorInput).getURI();
IResource resource = ExternalSourceArchiveManager.toResource(uri);
if (resource instanceof IFile) {
origSrcFile = (IFile) resource;
} else {
origSrcFile = null;
}
} else {
origSrcFile = null;
}
return origSrcFile;
}
private static Map.Entry<Integer, Node> getFirstValidLocation(Tree.CompilationUnit rootNode,
final IDocument document, final ITextSelection textSelection) {
class BreakpointVisitor extends Visitor {
TreeMap<Integer, Node> nodes = new TreeMap<>();
int requestedLine = textSelection.getStartLine();
void check(Node node) {
Integer startIndex = node.getStartIndex();
Integer stopIndex = node.getStopIndex();
if (startIndex != null && stopIndex != null) {
stopIndex ++;
int nodeStartLine;
try {
nodeStartLine = document.getLineOfOffset(startIndex);
if (nodeStartLine >= requestedLine) {
nodes.put(nodeStartLine, node);
} else {
int nodeEndLine = document.getLineOfOffset(stopIndex);
if (nodeEndLine >= requestedLine) {
nodes.put(requestedLine, node);
}
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
@Override
public void visit(Tree.Annotation that) {}
// @Override
// public void visit(Tree.MethodDefinition that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
// @Override
// public void visit(Tree.ClassDefinition that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
// @Override
// public void visit(Tree.Constructor that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
// @Override
// public void visit(Tree.AttributeGetterDefinition that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
// @Override
// public void visit(Tree.AttributeSetterDefinition that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
@Override
public void visit(Tree.ExecutableStatement that) {
check(that);
super.visit(that);
}
@Override
public void visit(Tree.SpecifierOrInitializerExpression that) {
check(that);
super.visit(that);
}
@Override
public void visit(Tree.Expression that) {
check(that);
super.visit(that);
}
};
BreakpointVisitor visitor = new BreakpointVisitor();
visitor.visit(rootNode);
return visitor.nodes.firstEntry();
}
private IMarker findBreakpointMarker(IFile srcFile, int lineNumber) throws CoreException {
IMarker[] markers = srcFile.findMarkers(IBreakpoint.LINE_BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
for (int k = 0; k < markers.length; k++ ){
if (((Integer) markers[k].getAttribute(IMarker.LINE_NUMBER)).intValue() == lineNumber){
return markers[k];
}
}
return null;
}
public static final String ORIGIN = CeylonPlugin.PLUGIN_ID + ".breakpointAttribute.Origin";
public IJavaStratumLineBreakpoint createLineBreakpoint(IFile file, int lineNumber, Map<String,Object> attributes, boolean isForRunToLine) throws CoreException {
String srcFileName = file.getName();
String srcPath = null;
IPath relativePath = null;
String classnamePattern = null;
IPath projectRelativePath = file.getProjectRelativePath();
if (ExternalSourceArchiveManager.isInSourceArchive(file)) {
relativePath = ExternalSourceArchiveManager.getSourceArchiveEntryPath(file);
} else {
IResourceAware unit = CeylonBuilder.getUnit(file);
if (unit != null) {
relativePath = new Path(((Unit)unit).getRelativePath());
}
}
if (relativePath != null) {
srcPath = relativePath.toOSString();
} else {
String[] segments = projectRelativePath.segments();
if (segments.length == 1) {
srcPath=srcFileName;
} else {
String pattern = buildClassNamePattern(segments);
classnamePattern = pattern;
}
}
if (attributes == null) {
attributes = new HashMap<String, Object>();
}
attributes.put(ORIGIN, CeylonPlugin.PLUGIN_ID);
try {
return JDIDebugModel.createStratumBreakpoint(isForRunToLine ? getWorkspace().getRoot() : file, null, srcFileName,
srcPath, classnamePattern, lineNumber, -1, -1, 0, !isForRunToLine, attributes);
}
catch (CoreException e) {
e.printStackTrace();
}
return null;
}
private String buildClassNamePattern(String[] projectRelativePathSegments) {
String currentPattern = "*";
String[] patterns = new String[projectRelativePathSegments.length-1];
for (int i=projectRelativePathSegments.length-2; i>=0; i--) {
currentPattern = projectRelativePathSegments[i] + "." + currentPattern;
patterns[i] = currentPattern;
}
String pattern = patterns[0];
for (int i=1; i<patterns.length; i++) {
pattern += "," + patterns[i];
}
return pattern;
}
public void clearLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt = findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.delete();
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
public void disableLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt = findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.setEnabled(false);
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
public void enableLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt = findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.setEnabled(true);
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
/**
* Returns a Java line breakpoint that is already registered with the breakpoint
* manager for a type with the given name at the given line number.
*
* @param typeName fully qualified type name
* @param lineNumber line number
* @return a Java line breakpoint that is already registered with the breakpoint
* manager for a type with the given name at the given line number or <code>null</code>
* if no such breakpoint is registered
* @exception CoreException if unable to retrieve the associated marker
* attributes (line number).
*/
public static IJavaLineBreakpoint findStratumBreakpoint(IResource resource, int lineNumber) throws CoreException {
String modelId = JDT_DEBUG_PLUGIN_ID;
String markerType = "org.eclipse.jdt.debug.javaStratumLineBreakpointMarker";
IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints = manager.getBreakpoints(modelId);
for (int i = 0; i < breakpoints.length; i++) {
if (!(breakpoints[i] instanceof IJavaLineBreakpoint)) {
continue;
}
IJavaLineBreakpoint breakpoint = (IJavaLineBreakpoint) breakpoints[i];
IMarker marker = breakpoint.getMarker();
if (marker != null && marker.exists() && marker.getType().equals(markerType)) {
if (breakpoint.getLineNumber() == lineNumber &&
resource.equals(marker.getResource())) {
return breakpoint;
}
}
}
return null;
}
public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) {
return true;
}
public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
}
public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) {
return false;
}
public void toggleWatchpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
}
public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) {
return false;
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IRunToLineTarget#runToLine(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection, org.eclipse.debug.core.model.ISuspendResume)
*/
public void runToLine(IWorkbenchPart part, ISelection selection, final ISuspendResume target) throws CoreException {
doOnBreakpoints(part, selection, new BreakpointAction() {
@Override
public void doIt(final ITextSelection textSelection, final Map.Entry<Integer, Node> firstValidLocation,
final IFile sourceFile) throws CoreException {
final int requestedLineNumber = textSelection.getStartLine();
String errorMessage; //$NON-NLS-1$
if (firstValidLocation != null && requestedLineNumber == firstValidLocation.getKey().intValue()) {
errorMessage = "Unable to locate debug target"; //$NON-NLS-1$
if (target instanceof IAdaptable) {
IDebugTarget debugTarget = (IDebugTarget) ((IAdaptable)target).getAdapter(IDebugTarget.class);
if (debugTarget != null) {
IBreakpoint breakpoint= null;
Map<String, Object> attributes = new HashMap<String, Object>(4);
BreakpointUtils.addRunToLineAttributes(attributes);
breakpoint = createLineBreakpoint(sourceFile, firstValidLocation.getKey() + 1, attributes, true);
RunToLineHandler handler = new RunToLineHandler(debugTarget, target, breakpoint);
handler.run(new NullProgressMonitor());
return;
}
}
} else {
// invalid line
if (textSelection.getLength() > 0) {
errorMessage = "Selected line is not a valid location to run to"; //$NON-NLS-1$
} else {
errorMessage = "Cursor position is not a valid location to run to"; //$NON-NLS-1$
}
}
throw new CoreException(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IJavaDebugUIConstants.INTERNAL_ERROR,
errorMessage, null));
}
});
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IRunToLineTarget#canRunToLine(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection, org.eclipse.debug.core.model.ISuspendResume)
*/
public boolean canRunToLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) {
if (target instanceof IDebugElement && target.canResume()) {
IDebugElement element = (IDebugElement) target;
IJavaDebugTarget adapter = (IJavaDebugTarget) element.getDebugTarget().getAdapter(IJavaDebugTarget.class);
return adapter != null;
}
return false;
}
}
|
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/editor/ToggleBreakpointAdapter.java
|
package com.redhat.ceylon.eclipse.code.editor;
import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IBreakpointManager;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.debug.core.model.IDebugElement;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.ISuspendResume;
import org.eclipse.debug.ui.actions.IRunToLineTarget;
import org.eclipse.debug.ui.actions.IToggleBreakpointsTarget;
import org.eclipse.debug.ui.actions.RunToLineHandler;
import org.eclipse.jdt.debug.core.IJavaDebugTarget;
import org.eclipse.jdt.debug.core.IJavaLineBreakpoint;
import org.eclipse.jdt.debug.core.IJavaStratumLineBreakpoint;
import org.eclipse.jdt.debug.core.JDIDebugModel;
import org.eclipse.jdt.debug.ui.IJavaDebugUIConstants;
import org.eclipse.jdt.internal.debug.ui.BreakpointUtils;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.ide.FileStoreEditorInput;
import com.redhat.ceylon.model.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.core.external.ExternalSourceArchiveManager;
import com.redhat.ceylon.eclipse.core.model.IResourceAware;
public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget, IRunToLineTarget {
private static final String JDT_DEBUG_PLUGIN_ID = "org.eclipse.jdt.debug";
public ToggleBreakpointAdapter() {}
static interface BreakpointAction {
void doIt(ITextSelection selection, Map.Entry<Integer, Node> firstValidLocation, IFile sourceFile) throws CoreException;
}
public void doOnBreakpoints(IWorkbenchPart part, ISelection selection, BreakpointAction action) throws CoreException {
if (selection instanceof ITextSelection) {
ITextSelection textSel= (ITextSelection) selection;
IEditorPart editorPart= (IEditorPart) part.getAdapter(IEditorPart.class);
//TODO: handle org.eclipse.ui.ide.FileStoreEditorInput
// to set breakpoints in code from archives
IEditorInput editorInput = editorPart.getEditorInput();
final IFile origSrcFile = getSourceFile(editorInput);
int line = textSel.getStartLine();
boolean emptyLine = true;
Map.Entry<Integer, Node> location = null;
try {
CeylonEditor editor = (CeylonEditor) editorPart;
IDocument document = editor.getCeylonSourceViewer().getDocument();
int lineCount = document.getNumberOfLines();
String text = null;
while (line < lineCount) {
final IRegion lineInformation = document.getLineInformation(line);
text = document.get(lineInformation.getOffset(),
lineInformation.getLength()).trim();
if (! text.isEmpty()) {
emptyLine = false;
break;
}
line ++;
};
if (!emptyLine) {
Tree.CompilationUnit rootNode = editor.getParseController().getLastCompilationUnit();
location = getFirstValidLocation(rootNode, document, textSel);
}
} catch (Exception e) {
e.printStackTrace();
}
action.doIt(textSel, location, origSrcFile);
}
}
public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
doOnBreakpoints(part, selection, new BreakpointAction() {
@Override
public void doIt(final ITextSelection selection, final Map.Entry<Integer, Node> firstValidLocation,
final IFile sourceFile) throws CoreException {
final int requestedLineNumber = selection.getStartLine();
IWorkspaceRunnable wr = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
IMarker marker = findBreakpointMarker(sourceFile, requestedLineNumber + 1);
if (marker!=null) {
// The following will delete the associated marker
clearLineBreakpoint(sourceFile, requestedLineNumber + 1);
} else if (firstValidLocation != null) {
// The following will create a marker as a side-effect
createLineBreakpoint(sourceFile, firstValidLocation.getKey() + 1, null, false);
}
}
};
try {
getWorkspace().run(wr, null);
}
catch (CoreException e) {
throw new DebugException(e.getStatus());
}
}
});
}
private IFile getSourceFile(IEditorInput editorInput) {
final IFile origSrcFile;
if (editorInput instanceof IFileEditorInput) {
origSrcFile= ((IFileEditorInput)editorInput).getFile();
} else if (editorInput instanceof FileStoreEditorInput) {
URI uri = ((FileStoreEditorInput) editorInput).getURI();
IResource resource = ExternalSourceArchiveManager.toResource(uri);
if (resource instanceof IFile) {
origSrcFile = (IFile) resource;
} else {
origSrcFile = null;
}
} else {
origSrcFile = null;
}
return origSrcFile;
}
private static Map.Entry<Integer, Node> getFirstValidLocation(Tree.CompilationUnit rootNode,
final IDocument document, final ITextSelection textSelection) {
class BreakpointVisitor extends Visitor {
TreeMap<Integer, Node> nodes = new TreeMap<>();
int requestedLine = textSelection.getStartLine();
void check(Node node) {
Integer startIndex = node.getStartIndex();
Integer stopIndex = node.getStopIndex();
if (startIndex != null && stopIndex != null) {
stopIndex ++;
int nodeStartLine;
try {
nodeStartLine = document.getLineOfOffset(startIndex);
if (nodeStartLine >= requestedLine) {
nodes.put(nodeStartLine, node);
} else {
int nodeEndLine = document.getLineOfOffset(stopIndex);
if (nodeEndLine >= requestedLine) {
nodes.put(requestedLine, node);
}
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
@Override
public void visit(Tree.Annotation that) {}
// @Override
// public void visit(Tree.MethodDefinition that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
// @Override
// public void visit(Tree.ClassDefinition that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
// @Override
// public void visit(Tree.Constructor that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
// @Override
// public void visit(Tree.AttributeGetterDefinition that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
// @Override
// public void visit(Tree.AttributeSetterDefinition that) {
// if (in(that.getIdentifier())) {
// result = that;
// }
// super.visit(that);
// }
@Override
public void visit(Tree.ExecutableStatement that) {
check(that);
super.visit(that);
}
@Override
public void visit(Tree.SpecifierOrInitializerExpression that) {
check(that);
super.visit(that);
}
@Override
public void visit(Tree.Expression that) {
check(that);
super.visit(that);
}
};
BreakpointVisitor visitor = new BreakpointVisitor();
visitor.visit(rootNode);
return visitor.nodes.firstEntry();
}
private IMarker findBreakpointMarker(IFile srcFile, int lineNumber) throws CoreException {
IMarker[] markers = srcFile.findMarkers(IBreakpoint.LINE_BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE);
for (int k = 0; k < markers.length; k++ ){
if (((Integer) markers[k].getAttribute(IMarker.LINE_NUMBER)).intValue() == lineNumber){
return markers[k];
}
}
return null;
}
public IJavaStratumLineBreakpoint createLineBreakpoint(IFile file, int lineNumber, Map<String,Object> attributes, boolean isForRunToLine) throws CoreException {
String srcFileName = file.getName();
String srcPath = null;
IPath relativePath = null;
String classnamePattern = null;
IPath projectRelativePath = file.getProjectRelativePath();
if (ExternalSourceArchiveManager.isInSourceArchive(file)) {
relativePath = ExternalSourceArchiveManager.getSourceArchiveEntryPath(file);
} else {
IResourceAware unit = CeylonBuilder.getUnit(file);
if (unit != null) {
relativePath = new Path(((Unit)unit).getRelativePath());
}
}
if (relativePath != null) {
srcPath = relativePath.toOSString();
} else {
String[] segments = projectRelativePath.segments();
if (segments.length == 1) {
srcPath=srcFileName;
} else {
String pattern = buildClassNamePattern(segments);
classnamePattern = pattern;
}
}
if (attributes == null) {
attributes = new HashMap<String, Object>();
}
try {
return JDIDebugModel.createStratumBreakpoint(isForRunToLine ? getWorkspace().getRoot() : file, null, srcFileName,
srcPath, classnamePattern, lineNumber, -1, -1, 0, !isForRunToLine, attributes);
}
catch (CoreException e) {
e.printStackTrace();
}
return null;
}
private String buildClassNamePattern(String[] projectRelativePathSegments) {
String currentPattern = "*";
String[] patterns = new String[projectRelativePathSegments.length-1];
for (int i=projectRelativePathSegments.length-2; i>=0; i--) {
currentPattern = projectRelativePathSegments[i] + "." + currentPattern;
patterns[i] = currentPattern;
}
String pattern = patterns[0];
for (int i=1; i<patterns.length; i++) {
pattern += "," + patterns[i];
}
return pattern;
}
public void clearLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt = findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.delete();
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
public void disableLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt = findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.setEnabled(false);
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
public void enableLineBreakpoint(IFile file, int lineNumber) throws CoreException {
try {
IBreakpoint lineBkpt = findStratumBreakpoint(file, lineNumber);
if (lineBkpt != null) {
lineBkpt.setEnabled(true);
}
}
catch (CoreException e) {
e.printStackTrace();
}
}
/**
* Returns a Java line breakpoint that is already registered with the breakpoint
* manager for a type with the given name at the given line number.
*
* @param typeName fully qualified type name
* @param lineNumber line number
* @return a Java line breakpoint that is already registered with the breakpoint
* manager for a type with the given name at the given line number or <code>null</code>
* if no such breakpoint is registered
* @exception CoreException if unable to retrieve the associated marker
* attributes (line number).
*/
public static IJavaLineBreakpoint findStratumBreakpoint(IResource resource, int lineNumber) throws CoreException {
String modelId = JDT_DEBUG_PLUGIN_ID;
String markerType = "org.eclipse.jdt.debug.javaStratumLineBreakpointMarker";
IBreakpointManager manager = DebugPlugin.getDefault().getBreakpointManager();
IBreakpoint[] breakpoints = manager.getBreakpoints(modelId);
for (int i = 0; i < breakpoints.length; i++) {
if (!(breakpoints[i] instanceof IJavaLineBreakpoint)) {
continue;
}
IJavaLineBreakpoint breakpoint = (IJavaLineBreakpoint) breakpoints[i];
IMarker marker = breakpoint.getMarker();
if (marker != null && marker.exists() && marker.getType().equals(markerType)) {
if (breakpoint.getLineNumber() == lineNumber &&
resource.equals(marker.getResource())) {
return breakpoint;
}
}
}
return null;
}
public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) {
return true;
}
public void toggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
}
public boolean canToggleMethodBreakpoints(IWorkbenchPart part, ISelection selection) {
return false;
}
public void toggleWatchpoints(IWorkbenchPart part, ISelection selection) throws CoreException {
}
public boolean canToggleWatchpoints(IWorkbenchPart part, ISelection selection) {
return false;
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IRunToLineTarget#runToLine(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection, org.eclipse.debug.core.model.ISuspendResume)
*/
public void runToLine(IWorkbenchPart part, ISelection selection, final ISuspendResume target) throws CoreException {
doOnBreakpoints(part, selection, new BreakpointAction() {
@Override
public void doIt(final ITextSelection textSelection, final Map.Entry<Integer, Node> firstValidLocation,
final IFile sourceFile) throws CoreException {
final int requestedLineNumber = textSelection.getStartLine();
String errorMessage; //$NON-NLS-1$
if (firstValidLocation != null && requestedLineNumber == firstValidLocation.getKey().intValue()) {
errorMessage = "Unable to locate debug target"; //$NON-NLS-1$
if (target instanceof IAdaptable) {
IDebugTarget debugTarget = (IDebugTarget) ((IAdaptable)target).getAdapter(IDebugTarget.class);
if (debugTarget != null) {
IBreakpoint breakpoint= null;
Map<String, Object> attributes = new HashMap<String, Object>(4);
BreakpointUtils.addRunToLineAttributes(attributes);
breakpoint = createLineBreakpoint(sourceFile, firstValidLocation.getKey() + 1, attributes, true);
RunToLineHandler handler = new RunToLineHandler(debugTarget, target, breakpoint);
handler.run(new NullProgressMonitor());
return;
}
}
} else {
// invalid line
if (textSelection.getLength() > 0) {
errorMessage = "Selected line is not a valid location to run to"; //$NON-NLS-1$
} else {
errorMessage = "Cursor position is not a valid location to run to"; //$NON-NLS-1$
}
}
throw new CoreException(new Status(IStatus.ERROR, JDIDebugUIPlugin.getUniqueIdentifier(), IJavaDebugUIConstants.INTERNAL_ERROR,
errorMessage, null));
}
});
}
/* (non-Javadoc)
* @see org.eclipse.debug.ui.actions.IRunToLineTarget#canRunToLine(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection, org.eclipse.debug.core.model.ISuspendResume)
*/
public boolean canRunToLine(IWorkbenchPart part, ISelection selection, ISuspendResume target) {
if (target instanceof IDebugElement && target.canResume()) {
IDebugElement element = (IDebugElement) target;
IJavaDebugTarget adapter = (IJavaDebugTarget) element.getDebugTarget().getAdapter(IJavaDebugTarget.class);
return adapter != null;
}
return false;
}
}
|
Fix #1541
|
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/editor/ToggleBreakpointAdapter.java
|
Fix #1541
|
<ide><path>lugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/editor/ToggleBreakpointAdapter.java
<ide> import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
<ide> import com.redhat.ceylon.eclipse.core.external.ExternalSourceArchiveManager;
<ide> import com.redhat.ceylon.eclipse.core.model.IResourceAware;
<add>import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
<ide>
<ide> public class ToggleBreakpointAdapter implements IToggleBreakpointsTarget, IRunToLineTarget {
<ide>
<ide>
<ide> if (!emptyLine) {
<ide> Tree.CompilationUnit rootNode = editor.getParseController().getLastCompilationUnit();
<del> location = getFirstValidLocation(rootNode, document, textSel);
<add> if (rootNode != null) {
<add> location = getFirstValidLocation(rootNode, document, textSel);
<add> }
<ide> }
<ide> } catch (Exception e) {
<ide> e.printStackTrace();
<ide> return null;
<ide> }
<ide>
<add>
<add> public static final String ORIGIN = CeylonPlugin.PLUGIN_ID + ".breakpointAttribute.Origin";
<add>
<ide> public IJavaStratumLineBreakpoint createLineBreakpoint(IFile file, int lineNumber, Map<String,Object> attributes, boolean isForRunToLine) throws CoreException {
<ide> String srcFileName = file.getName();
<ide> String srcPath = null;
<ide> if (attributes == null) {
<ide> attributes = new HashMap<String, Object>();
<ide> }
<del>
<add> attributes.put(ORIGIN, CeylonPlugin.PLUGIN_ID);
<add>
<ide> try {
<ide> return JDIDebugModel.createStratumBreakpoint(isForRunToLine ? getWorkspace().getRoot() : file, null, srcFileName,
<ide> srcPath, classnamePattern, lineNumber, -1, -1, 0, !isForRunToLine, attributes);
|
|
Java
|
apache-2.0
|
error: pathspec 'src/main/java/org/jboss/seam/faces/context/conversation/NamedConversationAliasProducer.java' did not match any file(s) known to git
|
706246514c144f36c3d6d825a3dd28bfc4b7e3ba
| 1 |
tremes/seam-faces,seam/faces
|
package org.jboss.seam.faces.context.conversation;
import javax.enterprise.context.Conversation;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.Typed;
import javax.inject.Named;
/**
* Exposes the {@link Conversation} under the simplified name "conversation"
* in addition to the default "javax.enterprise.context.conversation". This
* alias is provided for the page author's convenience.
*
* @author Dan Allen
*/
public class NamedConversationAliasProducer
{
public @Produces @Named @Typed() Conversation getConversation(Conversation conversation)
{
return conversation;
}
}
|
src/main/java/org/jboss/seam/faces/context/conversation/NamedConversationAliasProducer.java
|
assign the alias "conversation" to the build-in Conversation bean
|
src/main/java/org/jboss/seam/faces/context/conversation/NamedConversationAliasProducer.java
|
assign the alias "conversation" to the build-in Conversation bean
|
<ide><path>rc/main/java/org/jboss/seam/faces/context/conversation/NamedConversationAliasProducer.java
<add>package org.jboss.seam.faces.context.conversation;
<add>
<add>import javax.enterprise.context.Conversation;
<add>import javax.enterprise.inject.Produces;
<add>import javax.enterprise.inject.Typed;
<add>import javax.inject.Named;
<add>
<add>/**
<add> * Exposes the {@link Conversation} under the simplified name "conversation"
<add> * in addition to the default "javax.enterprise.context.conversation". This
<add> * alias is provided for the page author's convenience.
<add> *
<add> * @author Dan Allen
<add> */
<add>public class NamedConversationAliasProducer
<add>{
<add> public @Produces @Named @Typed() Conversation getConversation(Conversation conversation)
<add> {
<add> return conversation;
<add> }
<add>}
|
|
Java
|
apache-2.0
|
cbb4a32c3c0d533fd0cb0819060bf5b6985e8108
| 0 |
corneliudascalu/mvp-notes
|
package com.corneliudascalu.mvpnotes.data.interactor.impl;
import com.corneliudascalu.mvpnotes.MVPNotesApp;
import com.corneliudascalu.mvpnotes.common.ObjectGraphHolder;
import com.corneliudascalu.mvpnotes.data.interactor.NoteInteractor;
import com.corneliudascalu.mvpnotes.data.model.DatabaseModule;
import com.corneliudascalu.mvpnotes.data.model.Note;
import com.corneliudascalu.mvpnotes.data.model.SimpleDatabase;
import com.corneliudascalu.mvpnotes.ui.view.main.OnNoteOperationListener;
import android.os.Handler;
import java.util.List;
import java.util.Random;
import javax.inject.Inject;
import dagger.ObjectGraph;
/**
* A very simple implementation of a NoteInteractor, which simulates delayed operations.
* Because this is just a sample, I'm using the SimpleDatabase class directly, not an interface.
* Normally, there should be a ContentProvider there, or something similar.
*
* @author Corneliu Dascalu <[email protected]>
*/
public class NoteInteractorImpl implements NoteInteractor {
private Handler mHandler;
public NoteInteractorImpl(MVPNotesApp app) {
mHandler = new Handler();
ObjectGraph objectGraph = ObjectGraphHolder.createScopedObjectGraph(app)
.plus(DatabaseModule.class);
objectGraph.inject(this);
}
@Inject
SimpleDatabase mSimpleDatabase;
private void simulateExecuteInBackground(Runnable runnable) {
mHandler.postDelayed(runnable, 1000);
}
@Override
public void storeNote(final Note note, final OnNoteOperationListener listener) {
simulateExecuteInBackground(new Runnable() {
@Override
public void run() {
if (new Random().nextInt(5) > 0) {
long id = mSimpleDatabase.addOrReplace(note);
if (id > 0) {
note.id = id;
listener.onNoteAdded(note);
} else {
listener.onNoteAddError(new Note.Error(note, "Note not inserted in db"));
}
} else {
listener.onNoteAddError(new Note.Error(note, "Generic error"));
}
}
});
}
@Override
public void deleteNote(final Note note, final OnNoteOperationListener listener) {
simulateExecuteInBackground(new Runnable() {
@Override
public void run() {
int deleted = mSimpleDatabase.delete(note.id);
if (deleted > 0) {
listener.onNoteDeleted(note);
} else {
listener.onNoteDeleteError(new Note.Error(note, "Note not deleted"));
}
}
});
}
@Override
public void getNote(final long id, final OnNoteOperationListener listener) {
simulateExecuteInBackground(new Runnable() {
@Override
public void run() {
Note note = mSimpleDatabase.get(id);
if (note != null) {
listener.onNoteRetrieved(note);
} else {
listener.onRetrieveError(new Note.Error(id, "Couldn't retrieve note"));
}
}
});
}
@Override
public void getAllNotes(final OnNoteOperationListener listener) {
simulateExecuteInBackground(new Runnable() {
@Override
public void run() {
List<Note> all = mSimpleDatabase.getAll();
listener.onNoteListRetrieved(all);
}
});
}
}
|
app/src/main/java/com/corneliudascalu/mvpnotes/data/interactor/impl/NoteInteractorImpl.java
|
package com.corneliudascalu.mvpnotes.data.interactor.impl;
import com.corneliudascalu.mvpnotes.MVPNotesApp;
import com.corneliudascalu.mvpnotes.common.ObjectGraphHolder;
import com.corneliudascalu.mvpnotes.data.interactor.NoteInteractor;
import com.corneliudascalu.mvpnotes.data.model.DatabaseModule;
import com.corneliudascalu.mvpnotes.data.model.Note;
import com.corneliudascalu.mvpnotes.data.model.SimpleDatabase;
import com.corneliudascalu.mvpnotes.ui.view.main.OnNoteOperationListener;
import android.os.Handler;
import java.util.List;
import java.util.Random;
import javax.inject.Inject;
import dagger.ObjectGraph;
/**
* A very simple implementation of a NoteInteractor.
*
* @author Corneliu Dascalu <[email protected]>
*/
public class NoteInteractorImpl implements NoteInteractor {
private Handler mHandler;
public NoteInteractorImpl(MVPNotesApp app) {
mHandler = new Handler();
ObjectGraph objectGraph = ObjectGraphHolder.createScopedObjectGraph(app)
.plus(DatabaseModule.class);
objectGraph.inject(this);
}
@Inject
SimpleDatabase mSimpleDatabase;
private void simulateExecuteInBackground(Runnable runnable) {
mHandler.postDelayed(runnable, 1000);
}
@Override
public void storeNote(final Note note, final OnNoteOperationListener listener) {
simulateExecuteInBackground(new Runnable() {
@Override
public void run() {
if (new Random().nextInt(5) > 0) {
long id = mSimpleDatabase.addOrReplace(note);
if (id > 0) {
note.id = id;
listener.onNoteAdded(note);
} else {
listener.onNoteAddError(new Note.Error(note, "Note not inserted in db"));
}
} else {
listener.onNoteAddError(new Note.Error(note, "Generic error"));
}
}
});
}
@Override
public void deleteNote(final Note note, final OnNoteOperationListener listener) {
simulateExecuteInBackground(new Runnable() {
@Override
public void run() {
int deleted = mSimpleDatabase.delete(note.id);
if (deleted > 0) {
listener.onNoteDeleted(note);
} else {
listener.onNoteDeleteError(new Note.Error(note, "Note not deleted"));
}
}
});
}
@Override
public void getNote(final long id, final OnNoteOperationListener listener) {
simulateExecuteInBackground(new Runnable() {
@Override
public void run() {
Note note = mSimpleDatabase.get(id);
if (note != null) {
listener.onNoteRetrieved(note);
} else {
listener.onRetrieveError(new Note.Error(id, "Couldn't retrieve note"));
}
}
});
}
@Override
public void getAllNotes(final OnNoteOperationListener listener) {
simulateExecuteInBackground(new Runnable() {
@Override
public void run() {
List<Note> all = mSimpleDatabase.getAll();
listener.onNoteListRetrieved(all);
}
});
}
}
|
Comment for NoteInteractorImpl
|
app/src/main/java/com/corneliudascalu/mvpnotes/data/interactor/impl/NoteInteractorImpl.java
|
Comment for NoteInteractorImpl
|
<ide><path>pp/src/main/java/com/corneliudascalu/mvpnotes/data/interactor/impl/NoteInteractorImpl.java
<ide> import dagger.ObjectGraph;
<ide>
<ide> /**
<del> * A very simple implementation of a NoteInteractor.
<add> * A very simple implementation of a NoteInteractor, which simulates delayed operations.
<add> * Because this is just a sample, I'm using the SimpleDatabase class directly, not an interface.
<add> * Normally, there should be a ContentProvider there, or something similar.
<ide> *
<ide> * @author Corneliu Dascalu <[email protected]>
<ide> */
|
|
JavaScript
|
mit
|
dd2429435a1d22f9cd8c9f3508b7d72bcb785ea7
| 0 |
palashkulsh/bitbucket-cmd
|
/*global requirejs,console,define,fs*/
// Dan Shumaker
// Documentation: https://developer.atlassian.com/bitbucket/api/2/reference/
var BASE_URL = 'https://bitbucket.org/';
define([
'superagent',
'cli-table',
'moment',
'path',
'../../lib/config',
'simple-git',
'colors',
'openurl',
'commander',
'async'
], function (request, Table, moment, path, config, git, colors, openurl, program, async) {
function getPRForCurrentBranch(options, cb){
if(options.__branch){
getPullRequests(options, cb);
} else{
var conf = getConfig();
git(conf.currentPath).status(function (err, statusRes){
if(err){
console.log(err);
return cb();
}
options.__branch = statusRes.current;
return getPullRequests(options, cb);
});
}
}
function createPullReq(options, conf, destBranch, sourceBranch, cb){
console.log("Create Pull Request");
var reviewers = conf.currentConfig.reviewers.length ? conf.currentConfig.reviewers : conf.default.reviewers;
var json_package;
json_package = {
"destination": {
"branch": {
"name": destBranch
}
},
"source": {
"branch": {
"name": sourceBranch
}
},
"title": options.message,
"description": options.message,
"reviewers": reviewers
};
console.log(conf.finalUrl, json_package)
request
.post(conf.finalUrl)
.send(json_package)
.set('Content-Type', 'application/json')
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
console.log(res.text);
//return console.log((res.body.errorMessages || [res.error]).join('\n'));
return cb(new Error((res.body.errorMessages || [res.error]).join('\n')));
}
//return console.log("\n\nView PR @ " + getConfig(null, res.body.id).viewUrl);
return cb(null, "\n\nView PR @ " + getConfig(null, res.body.id).viewUrl)
});
}
function getConfig(type,prId, path){
var currentPath = path || process.cwd() ;
var currentConfig = config.repo_level[currentPath] || config.default;
var endPoint = [currentConfig.auth.team, currentConfig.auth.repo_name].join('/');
var finalUrl = currentConfig.auth.url + endPoint;
var finalToken = new Buffer(currentConfig.auth.token).toString('base64');
var viewUrl = BASE_URL + endPoint;
var urlArr = [];
if (prId){
urlArr.push(prId);
}
if (type){
urlArr.push(type.toLowerCase());
}
viewUrl = [viewUrl, 'pull-requests', urlArr.join('/')].join('/');
finalUrl = [finalUrl, 'pullrequests', urlArr.join('/')].join('/');
return {
repo_name: currentConfig.auth.repo_name,
username: currentConfig.auth.user,
default: config.default,
currentPath: currentPath,
currentConfig: currentConfig,
endPoint: endPoint,
finalUrl: finalUrl,
finalToken: finalToken,
viewUrl: viewUrl
};
}
function getPullRequests(options, callback){
/***
* https://developer.atlassian.com/bitbucket/api/2/reference/meta/filtering
* */
var conf = getConfig(null, null, options.__overridePath);
var query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&q=state="open"';
if (options.list) {
var user = options.list !== true && isNaN(options.list) ? options.list : conf.username;
query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50&q=state="open" AND author.username="'+user+'"';
}
if (options.merged) {
query = '?q=state+%3D+%22MERGED%22&fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50';
}
if (options.review) {
query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50&q=reviewers.username="'+conf.username+'" AND state="OPEN"';
}
if (options.__branch) {
query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50&q=source.branch.name="'+options.__branch+'" AND state="OPEN"';
}
if (options.__pr_id) {
query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50&q=id='+ options.__pr_id;
}
var pullrequests, table;
i = 0;
console.log(conf.finalUrl+query)
request
.get(conf.finalUrl + query)
.set('Content-Type', 'application/json')
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return callback(res.body.errorMessages || [res.error].join('\n'));
}
var pull_requests = res.body.values;
return callback(null, pull_requests);
});
}
var pullrequest = {
getPRForCurrentBranch: function getPRForCurrentBranch(options, cb){
if(options.__branch){
getPullRequests(options, cb);
} else{
var conf = getConfig();
git(conf.currentPath).status(function (err, statusRes){
if(err){
console.log(err);
return cb();
}
options.__branch = statusRes.current;
return getPullRequests(options, function(err, res){
console.log(JSON.stringify( res, null, 4));
return cb(err, res);
});
});
}
},
globalList: function(options, cb){
if(config && config.repo_level){
options.list=1; //to only show my diffs
async.forEachOfSeries(config.repo_level, function(value, key, callback){
options.__overridePath = key;
console.log(options.__overridePath)
pullrequest.list(options, callback);
}, cb)
} else{
return cb();
}
},
list: function (options, cb) {
var conf = getConfig(null, null, options.__overridePath);
git(conf.currentPath).status(function(err, statusRes){
if(err){
console.log('Can not get current working directory status');
return cb();
}
var currentBranch = statusRes.current;
getPullRequests(options, function(err, pull_requests){
if(err){
console.log(err);
return cb();
}
table = new Table({
head: ['ID', 'Author', 'Source', 'Destination', 'Title', 'State', 'Reviewers', 'Url'],
chars: {
'top': '═' ,
'top-mid': '╤' ,
'top-left': '╔' ,
'top-right': '╗',
'bottom': '═' ,
'bottom-mid': '╧' ,
'bottom-left': '╚' ,
'bottom-right': '╝',
'left': '║' ,
'left-mid': '╟' ,
'mid': '─' ,
'mid-mid': '┼',
'right': '║' ,
'right-mid': '╢' ,
'middle': '│'
},
style: {
'padding-left': 1,
'padding-right': 1,
head: ['cyan']
}
});
for (i = 0; i < pull_requests.length; i += 1) {
title = pull_requests[i].title;
reviewers = pull_requests[i].reviewers.map(function (elem) {
return elem.username;
}).join(",");
if (title.length > 50) {
title = title.substr(0, 47) + '...';
}
var color = i % 2==0? 'blue': 'yellow';
if(currentBranch === pull_requests[i].source.branch.name){
pull_requests[i].source.branch.name = '* '+pull_requests[i].source.branch.name.grey;
}
table.push([
pull_requests[i].id.toString()[color],
pull_requests[i].author.username[color],
pull_requests[i].source.branch.name[color],
pull_requests[i].destination.branch.name[color],
title[color],
pull_requests[i].state[color],
reviewers[color],
getConfig(null, pull_requests[i].id).viewUrl[color].underline.red
]);
}
console.log(conf.repo_name.blue)
if (pull_requests.length > 0) {
console.log(table.toString());
} else {
console.log('No pull_requests');
}
return cb();
});
});
},
//MERGE POST https://api.bitbucket.org/2.0/repositories/dan_shumaker/backup_tar_test/pullrequests/3/merge
merge: function (options, cb) {
console.log('getting pull req');
getPRForCurrentBranch(options, function(err, pullreqs){
if(err){
console.log(err);
return cb(err);
}
if(options.merge === true && pullreqs && pullreqs[0]){
options.merge = pullreqs[0].id;
} else {
console.log('invalid pull request provided');
return cb(new Error('invalid pull request provided'));
}
var conf = getConfig('MERGE', options.merge);
var remoteBranch = 'origin';
console.log("merge");
var json_package = {
close_source_branch: true,
message: options.message,
//type: what should be here
merge_strategy: options.merge_strategy || 'squash'
}
console.log(conf.finalUrl)
request
.post(conf.finalUrl)
.send(json_package)
.set('Content-Type', 'application/json')
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
console.log((res.body.errorMessages || [res.error]).join('\n'));
return cb(new Error((res.body.errorMessages || [res.error]).join('\n')));
}
console.log("Merged PR @ " + res.body.links.self.href);
//pulling destination branch after successful merge
if(res.body && res.body.destination && res.body.destination.branch && res.body.destination.branch.name){
var destBranch = res.body.destination.branch.name;
var sourceBranch = res.body.source.branch.name;
git(conf.currentPath).checkout(destBranch, function(err, info){
console.log('checking out to destination branch '+ destBranch);
if(err){
console.log('error checking out to destination branch '+destBranch);
return cb(new Error('error checking out to destination branch '+destBranch));
}
git(conf.currentPath).pull(remoteBranch, destBranch+':'+destBranch, function(err, pull){
console.log('pulling '+remoteBranch+'/'+destBranch);
if(err){
console.log('error pulling '+remoteBranch+'/'+destBranch);
console.log(err);
return cb(err);
}
git(conf.currentPath).branch(['-D', sourceBranch], function(err,res){
console.log('deleting local source branch '+sourceBranch);
if(err){
console.log('error deleting source branch '+sourceBranch);
console.log(err);
return cb(err);
}
console.log('deleted source branch '+sourceBranch);
return cb();
});
});
});
} else{
return cb();
}
});
});
},
create: function (options, cb) {
var conf = getConfig();
git(conf.currentPath).status(function (err, info) {
console.log('running git status for current branch');
if (err) {
console.log('error gettting current branch');
return cb();
}
var sourceBranch, destBranch, remoteBranch;
sourceBranch = options.from || info.current;
destBranch = options.to || 'master';
remoteBranch = 'origin'
var query;
getPRForCurrentBranch(options, function(err, pullreqs){
if(err){
console.log(err);
return cb(err);
}
if(pullreqs && pullreqs[0] && pullreqs[0].id){
options.pullReqId = pullreqs[0].id;
}
git(conf.currentPath).log(['--format=%B', '-n','1'], function(err, res){
console.log('getting latest commit');
if(err){
console.log('error getting git log');
return cb();
}
var latestCommitMsg = res.latest.hash;
git(conf.currentPath).pull(remoteBranch, sourceBranch, function (err, sourcePullRes){
console.log('pulling source branch '+sourceBranch);
if(err){
if(err.indexOf("Couldn't find remote ref")<0){
console.log('error pulling source branch '+sourceBranch);
console.log(err);
console.log('Creating new pull request'.blue);
}else {
console.log('remote branch not present');
console.log('will create new pull request');
options.new=1; //flag to check if its new pull request
}
}
//pulling remote destination branch
git(conf.currentPath).pull(remoteBranch, destBranch, function (err, masterPullRes){
console.log(masterPullRes);
console.log('pulling '+remoteBranch+'/'+destBranch);
if(err){
console.log('error pulling '+remoteBranch+'/'+destBranch);
return cb();
}
//merging remote destination branch to local destination branch
git(conf.currentPath).mergeFromTo(destBranch, sourceBranch, function (err, mergeRes){
console.log('merging '+destBranch+' to '+sourceBranch);
if(err){
console.log('error merging '+destBranch+' to '+sourceBranch);
console.log(err);
return cb();
}
git(conf.currentPath).push(remoteBranch, sourceBranch, function (err, pushRes) {
console.log('pushing the branch to origin');
if (err) {
console.log('error pushing branch to origin');
return cb();
}
if(!options.pullReqId){
var question = 'Please Enter Pull request title [default Title is : '+latestCommitMsg+' ] '+ '(Press enter 2 times)'.red;
question = question.blue;
program.prompt(question, function(answer){
if(!answer){
options.message = latestCommitMsg;
} else {
options.message = answer;
}
console.log('Title is going to be '.red+ options.message);
createPullReq(options, conf, destBranch, sourceBranch, function(err, res){
if(err){
console.log(err);
return cb();
}
console.log(res);
return cb();
});
});
} else{
console.log('updated PR ' + getConfig(null, options.pullReqId).viewUrl);
return cb();
}
});
});
});
});
});
});
//pulling changes from source branch
});
},
decline: function (options) {
var conf = getConfig('DECLINE', options.decline);
console.log("Declining PR " + options.decline);
request
.post(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Declined PR " + options.decline);
});
},
approve: function (options) {
var conf = getConfig('APPROVE', options.approve);
console.log("Approving PR " + options.approve);
request
.post(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Approved PR " + options.approve);
});
},
diff: function (options) {
var conf = getConfig('DIFF', options.diff);
console.log(conf.finalUrl);
console.log("Diffing PR " + options.diff);
request
.get(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Diff PR ", res.text);
});
},
patch: function (options) {
var conf = getConfig('PATCH', options.patch);
console.log(conf.finalUrl);
console.log("Patching PR " + options.patch);
request
.get(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Patch PR " + res.text);
});
},
activity: function (options) {
var conf = getConfig('ACTIVITY', options.activity);
var table;
console.log(conf.finalUrl);
console.log("Activitying PR " + options.activity);
request
.get(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Activity PR " + options.activity);
table = new Table({
head: ['Content', 'User'],
chars: {
'top': '═' ,
'top-mid': '╤' ,
'top-left': '╔' ,
'top-right': '╗',
'bottom': '═' ,
'bottom-mid': '╧' ,
'bottom-left': '╚' ,
'bottom-right': '╝',
'left': '║' ,
'left-mid': '╟' ,
'mid': '─' ,
'mid-mid': '┼',
'right': '║' ,
'right-mid': '╢' ,
'middle': '│'
},
style: {
'padding-left': 1,
'padding-right': 1,
head: ['cyan'],
compact: true
}
});
if (res && res.text) {
res.text = JSON.parse(res.text);
res.text.values.forEach(function (eachValue,index) {
var color = index % 2 ? 'yellow' : 'blue';
if (eachValue.comment && eachValue.comment.content && eachValue.comment.content.raw && eachValue.comment.user && eachValue.comment.user.username) {
table.push([eachValue.comment.content.raw[color], eachValue.comment.user.username[color]]);
}
});
console.log(table.toString());
}
});
},
open: function (options, cb) {
if(options.open === true){
getPRForCurrentBranch(options, function (err, pullReqs){
if(err){
console.log(err);
return cb(err);
}
if(!pullReqs || !pullReqs[0]){
console.log('No pull Req found for current branch');
return cb(new Error('No pull Req found for current branch'));
}
options.open = pullReqs[0].id;
var conf = getConfig(null, options.open);
openurl.open(conf.viewUrl);
return cb();
});
} else {
var conf = getConfig(null, options.open);
openurl.open(conf.viewUrl);
return cb();
}
},
checkout: function (options, cb){
options.__pr_id = options.checkout;
getPullRequests(options, function(err, pullReqs){
var conf = getConfig();
if(err){
return cb(err);
}
if(!pullReqs || !pullReqs[0]){
console.log('No pull Req found for current branch');
return cb(new Error('No pull Req found for current branch'));
}
console.log(pullReqs[0])
var destBranch = pullReqs[0].source.branch.name;
console.log('switching to branch '+destBranch);
//checking if branch is present or not
git(conf.currentPath).revparse(['--verify', destBranch],function (err, rev){
if(err){
//pulling branch from origin if branch not present locally
var remoteBranch = 'origin';
console.log('branch not found, pull from '+remoteBranch);
git(conf.currentPath).pull(remoteBranch+'/'+destBranch, destBranch, function(err,res){
if(err){
return cb(err);
}
//checking out to branch
git(conf.currentPath).checkout(destBranch, function(err, info){
if(err){
console.log(err);
return cb(err);
}
console.log('checked out to branch');
return cb();
});
});
}
//checking out to branch
git(conf.currentPath).checkout(destBranch, function(err, info){
if(err){
console.log(err);
return cb(err);
}
console.log('switched to branch '+destBranch);
cb();
//switching to branch after checkout is complete in async fashion
var remoteBranch = 'origin';
git(conf.currentPath).pull(remoteBranch+'/'+destBranch, destBranch, function(err,res){
if(err){
console.log(err);
return ;
}
});
});
});
});
}
};
return pullrequest;
});
|
lib/bitbucket/pr.js
|
/*global requirejs,console,define,fs*/
// Dan Shumaker
// Documentation: https://developer.atlassian.com/bitbucket/api/2/reference/
var BASE_URL = 'https://bitbucket.org/';
define([
'superagent',
'cli-table',
'moment',
'path',
'../../lib/config',
'simple-git',
'colors',
'openurl',
'commander',
'async'
], function (request, Table, moment, path, config, git, colors, openurl, program, async) {
function getPRForCurrentBranch(options, cb){
if(options.__branch){
getPullRequests(options, cb);
} else{
var conf = getConfig();
git(conf.currentPath).status(function (err, statusRes){
if(err){
console.log(err);
return cb();
}
options.__branch = statusRes.current;
return getPullRequests(options, cb);
});
}
}
function createPullReq(options, conf, destBranch, sourceBranch, cb){
console.log("Create Pull Request");
var reviewers = conf.currentConfig.reviewers.length ? conf.currentConfig.reviewers : conf.default.reviewers;
var json_package;
json_package = {
"destination": {
"branch": {
"name": destBranch
}
},
"source": {
"branch": {
"name": sourceBranch
}
},
"title": options.message,
"description": options.message,
"reviewers": reviewers
};
console.log(conf.finalUrl, json_package)
request
.post(conf.finalUrl)
.send(json_package)
.set('Content-Type', 'application/json')
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
console.log(res.text);
//return console.log((res.body.errorMessages || [res.error]).join('\n'));
return cb(new Error((res.body.errorMessages || [res.error]).join('\n')));
}
//return console.log("\n\nView PR @ " + getConfig(null, res.body.id).viewUrl);
return cb(null, "\n\nView PR @ " + getConfig(null, res.body.id).viewUrl)
});
}
function getConfig(type,prId, path){
var currentPath = path || process.cwd() ;
var currentConfig = config.repo_level[currentPath] || config.default;
var endPoint = [currentConfig.auth.team, currentConfig.auth.repo_name].join('/');
var finalUrl = currentConfig.auth.url + endPoint;
var finalToken = new Buffer(currentConfig.auth.token).toString('base64');
var viewUrl = BASE_URL + endPoint;
var urlArr = [];
if (prId){
urlArr.push(prId);
}
if (type){
urlArr.push(type.toLowerCase());
}
viewUrl = [viewUrl, 'pull-requests', urlArr.join('/')].join('/');
finalUrl = [finalUrl, 'pullrequests', urlArr.join('/')].join('/');
return {
repo_name: currentConfig.auth.repo_name,
username: currentConfig.auth.user,
default: config.default,
currentPath: currentPath,
currentConfig: currentConfig,
endPoint: endPoint,
finalUrl: finalUrl,
finalToken: finalToken,
viewUrl: viewUrl
};
}
function getPullRequests(options, callback){
/***
* https://developer.atlassian.com/bitbucket/api/2/reference/meta/filtering
* */
var conf = getConfig(null, null, options.__overridePath);
var query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&q=state="open"';
if (options.list) {
var user = options.list !== true && isNaN(options.list) ? options.list : conf.username;
query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50&q=state="open" AND author.username="'+user+'"';
}
if (options.merged) {
query = '?q=state+%3D+%22MERGED%22&fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50';
}
if (options.review) {
query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50&q=reviewers.username="'+conf.username+'" AND state="OPEN"';
}
if (options.__branch) {
query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50&q=source.branch.name="'+options.__branch+'" AND state="OPEN"';
}
if (options.__pr_id) {
query = '?fields=%2Bvalues.reviewers.username,values.id,values.title,values.state,values.destination.branch.name,values.source.branch.name,values.author.username&pagelen=50&q=id='+ options.__pr_id;
}
var pullrequests, table;
i = 0;
console.log(conf.finalUrl+query)
request
.get(conf.finalUrl + query)
.set('Content-Type', 'application/json')
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return callback(res.body.errorMessages || [res.error].join('\n'));
}
var pull_requests = res.body.values;
return callback(null, pull_requests);
});
}
var pullrequest = {
getPRForCurrentBranch: function getPRForCurrentBranch(options, cb){
if(options.__branch){
getPullRequests(options, cb);
} else{
var conf = getConfig();
git(conf.currentPath).status(function (err, statusRes){
if(err){
console.log(err);
return cb();
}
options.__branch = statusRes.current;
return getPullRequests(options, function(err, res){
console.log(JSON.stringify( res, null, 4));
return cb(err, res);
});
});
}
},
globalList: function(options, cb){
if(config && config.repo_level){
options.list=1; //to only show my diffs
async.forEachOfSeries(config.repo_level, function(value, key, callback){
options.__overridePath = key;
console.log(options.__overridePath)
pullrequest.list(options, callback);
}, cb)
} else{
return cb();
}
},
list: function (options, cb) {
var conf = getConfig(null, null, options.__overridePath);
git(conf.currentPath).status(function(err, statusRes){
if(err){
console.log('Can not get current working directory status');
return cb();
}
var currentBranch = statusRes.current;
getPullRequests(options, function(err, pull_requests){
if(err){
console.log(err);
return cb();
}
table = new Table({
head: ['ID', 'Author', 'Source', 'Destination', 'Title', 'State', 'Reviewers', 'Url'],
chars: {
'top': '═' ,
'top-mid': '╤' ,
'top-left': '╔' ,
'top-right': '╗',
'bottom': '═' ,
'bottom-mid': '╧' ,
'bottom-left': '╚' ,
'bottom-right': '╝',
'left': '║' ,
'left-mid': '╟' ,
'mid': '─' ,
'mid-mid': '┼',
'right': '║' ,
'right-mid': '╢' ,
'middle': '│'
},
style: {
'padding-left': 1,
'padding-right': 1,
head: ['cyan']
}
});
for (i = 0; i < pull_requests.length; i += 1) {
title = pull_requests[i].title;
reviewers = pull_requests[i].reviewers.map(function (elem) {
return elem.username;
}).join(",");
if (title.length > 50) {
title = title.substr(0, 47) + '...';
}
var color = i % 2==0? 'blue': 'yellow';
if(currentBranch === pull_requests[i].source.branch.name){
pull_requests[i].source.branch.name = '* '+pull_requests[i].source.branch.name.grey;
}
table.push([
pull_requests[i].id.toString()[color],
pull_requests[i].author.username[color],
pull_requests[i].source.branch.name[color],
pull_requests[i].destination.branch.name[color],
title[color],
pull_requests[i].state[color],
reviewers[color],
getConfig(null, pull_requests[i].id).viewUrl[color].underline.red
]);
}
console.log(conf.repo_name.blue)
if (pull_requests.length > 0) {
console.log(table.toString());
} else {
console.log('No pull_requests');
}
return cb();
});
});
},
//MERGE POST https://api.bitbucket.org/2.0/repositories/dan_shumaker/backup_tar_test/pullrequests/3/merge
merge: function (options, cb) {
console.log('getting pull req');
getPRForCurrentBranch(options, function(err, pullreqs){
if(err){
console.log(err);
return cb(err);
}
if(options.merge === true && pullreqs && pullreqs[0]){
options.merge = pullreqs[0].id;
} else {
console.log('invalid pull request provided');
return cb(new Error('invalid pull request provided'));
}
var conf = getConfig('MERGE', options.merge);
var remoteBranch = 'origin';
console.log("merge");
var json_package = {
close_source_branch: true,
message: options.message,
//type: what should be here
merge_strategy: options.merge_strategy || 'squash'
}
console.log(conf.finalUrl)
request
.post(conf.finalUrl)
.send(json_package)
.set('Content-Type', 'application/json')
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
console.log((res.body.errorMessages || [res.error]).join('\n'));
return cb(new Error((res.body.errorMessages || [res.error]).join('\n')));
}
console.log("Merged PR @ " + res.body.links.self.href);
//pulling destination branch after successful merge
if(res.body && res.body.destination && res.body.destination.branch && res.body.destination.branch.name){
var destBranch = res.body.destination.branch.name;
var sourceBranch = res.body.source.branch.name;
git(conf.currentPath).checkout(destBranch, function(err, info){
console.log('checking out to destination branch '+ destBranch);
if(err){
console.log('error checking out to destination branch '+destBranch);
return cb(new Error('error checking out to destination branch '+destBranch));
}
git(conf.currentPath).pull(remoteBranch, destBranch+':'+destBranch, function(err, pull){
console.log('pulling '+remoteBranch+'/'+destBranch);
if(err){
console.log('error pulling '+remoteBranch+'/'+destBranch);
console.log(err);
return cb(err);
}
git(conf.currentPath).branch(['-D', sourceBranch], function(err,res){
console.log('deleting local source branch '+sourceBranch);
if(err){
console.log('error deleting source branch '+sourceBranch);
console.log(err);
return cb(err);
}
console.log('deleted source branch '+sourceBranch);
return cb();
});
});
});
} else{
return cb();
}
});
});
},
create: function (options, cb) {
var conf = getConfig();
git(conf.currentPath).status(function (err, info) {
console.log('running git status for current branch');
if (err) {
console.log('error gettting current branch');
return cb();
}
var sourceBranch, destBranch, remoteBranch;
sourceBranch = options.from || info.current;
destBranch = options.to || 'master';
remoteBranch = 'origin'
var query;
getPRForCurrentBranch(options, function(err, pullreqs){
if(err){
console.log(err);
return cb(err);
}
if(pullreqs && pullreqs[0] && pullreqs[0].id){
options.pullReqId = pullreqs[0].id;
}
git(conf.currentPath).log(['--format=%B', '-n','1'], function(err, res){
console.log('getting latest commit');
if(err){
console.log('error getting git log');
return cb();
}
var latestCommitMsg = res.latest.hash;
git(conf.currentPath).pull(remoteBranch, sourceBranch, function (err, sourcePullRes){
console.log('pulling source branch '+sourceBranch);
if(err){
if(err.indexOf("Couldn't find remote ref")<0){
console.log('error pulling source branch '+sourceBranch);
console.log(err);
console.log('Creating new pull request'.blue);
}else {
console.log('remote branch not present');
console.log('will create new pull request');
options.new=1; //flag to check if its new pull request
}
}
//pulling remote destination branch
git(conf.currentPath).pull(remoteBranch, destBranch, function (err, masterPullRes){
console.log(masterPullRes);
console.log('pulling '+remoteBranch+'/'+destBranch);
if(err){
console.log('error pulling '+remoteBranch+'/'+destBranch);
return cb();
}
//merging remote destination branch to local destination branch
git(conf.currentPath).mergeFromTo(destBranch, sourceBranch, function (err, mergeRes){
console.log('merging '+destBranch+' to '+sourceBranch);
if(err){
console.log('error merging '+destBranch+' to '+sourceBranch);
console.log(err);
return cb();
}
git(conf.currentPath).push(remoteBranch, sourceBranch, function (err, pushRes) {
console.log('pushing the branch to origin');
if (err) {
console.log('error pushing branch to origin');
return cb();
}
if(!options.pullReqId){
var question = 'Please Enter Pull request title [default Title is : '+latestCommitMsg+' ] '+ '(Press enter 2 times)'.red;
question = question.blue;
program.prompt(question, function(answer){
if(!answer){
options.message = latestCommitMsg;
} else {
options.message = answer;
}
console.log('Title is going to be '.red+ options.message);
createPullReq(options, conf, destBranch, sourceBranch, function(err, res){
if(err){
console.log(err);
return cb();
}
console.log(res);
return cb();
});
});
} else{
console.log('updated PR ' + getConfig(null, options.pullReqId).viewUrl);
return cb();
}
});
});
});
});
});
});
//pulling changes from source branch
});
},
decline: function (options) {
var conf = getConfig('DECLINE', options.decline);
console.log("Declining PR " + options.decline);
request
.post(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Declined PR " + options.decline);
});
},
approve: function (options) {
var conf = getConfig('APPROVE', options.approve);
console.log("Approving PR " + options.approve);
request
.post(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Approved PR " + options.approve);
});
},
diff: function (options) {
var conf = getConfig('DIFF', options.diff);
console.log(conf.finalUrl);
console.log("Diffing PR " + options.diff);
request
.get(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Diff PR ", res.text);
});
},
patch: function (options) {
var conf = getConfig('PATCH', options.patch);
console.log(conf.finalUrl);
console.log("Patching PR " + options.patch);
request
.get(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Patch PR " + res.text);
});
},
activity: function (options) {
var conf = getConfig('ACTIVITY', options.activity);
var table;
console.log(conf.finalUrl);
console.log("Activitying PR " + options.activity);
request
.get(conf.finalUrl)
.set('Authorization', 'Basic ' + conf.finalToken)
.end(function (res) {
if (!res.ok) {
return console.log((res.body.errorMessages || [res.error]).join('\n'));
}
console.log("Activity PR " + options.activity);
table = new Table({
head: ['Content', 'User'],
chars: {
'top': '═' ,
'top-mid': '╤' ,
'top-left': '╔' ,
'top-right': '╗',
'bottom': '═' ,
'bottom-mid': '╧' ,
'bottom-left': '╚' ,
'bottom-right': '╝',
'left': '║' ,
'left-mid': '╟' ,
'mid': '─' ,
'mid-mid': '┼',
'right': '║' ,
'right-mid': '╢' ,
'middle': '│'
},
style: {
'padding-left': 1,
'padding-right': 1,
head: ['cyan'],
compact: true
}
});
if (res && res.text) {
res.text = JSON.parse(res.text);
res.text.values.forEach(function (eachValue,index) {
var color = index % 2 ? 'yellow' : 'blue';
if (eachValue.comment && eachValue.comment.content && eachValue.comment.content.raw && eachValue.comment.user && eachValue.comment.user.username) {
table.push([eachValue.comment.content.raw[color], eachValue.comment.user.username[color]]);
}
});
console.log(table.toString());
}
});
},
open: function (options, cb) {
if(options.open === true){
getPRForCurrentBranch(options, function (err, pullReqs){
if(err){
console.log(err);
return cb(err);
}
if(!pullReqs || !pullReqs[0]){
console.log('No pull Req found for current branch');
return cb(new Error('No pull Req found for current branch'));
}
options.open = pullReqs[0].id;
var conf = getConfig(null, options.open);
openurl.open(conf.viewUrl);
return cb();
});
} else {
var conf = getConfig(null, options.open);
openurl.open(conf.viewUrl);
return cb();
}
},
checkout: function (options, cb){
options.__pr_id = options.checkout;
getPullRequests(options, function(err, pullReqs){
var conf = getConfig();
if(err){
return cb(err);
}
if(!pullReqs || !pullReqs[0]){
console.log('No pull Req found for current branch');
return cb(new Error('No pull Req found for current branch'));
}
console.log(pullReqs[0])
var destBranch = pullReqs[0].source.branch.name;
console.log('switching to branch '+destBranch);
//checking if branch is present or not
git(conf.currentPath).revparse(['--verify', destBranch],function (err, rev){
if(err){
//pulling branch from origin if branch not present locally
var remoteBranch = 'origin';
console.log('branch not found, pull from '+remoteBranch);
git(conf.currentPath).pull(remoteBranch+'/'+destBranch, destBranch, function(err,res){
if(err){
return cb(err);
}
//checking out to branch
git(conf.currentPath).checkout(destBranch, function(err, info){
if(err){
console.log(err);
return cb(err);
}
console.log('checked out to branch');
return cb();
});
});
}
//checking out to branch
git(conf.currentPath).checkout(destBranch, function(err, info){
if(err){
console.log(err);
return cb(err);
}
console.log('switched to branch '+destBranch);
cb();
var remoteBranch = 'origin';
git(conf.currentPath).pull(remoteBranch+'/'+destBranch, destBranch, function(err,res){
if(err){
console.log(err);
return ;
}
});
});
});
});
}
};
return pullrequest;
});
|
added comment
|
lib/bitbucket/pr.js
|
added comment
|
<ide><path>ib/bitbucket/pr.js
<ide> }
<ide> console.log('switched to branch '+destBranch);
<ide> cb();
<add> //switching to branch after checkout is complete in async fashion
<ide> var remoteBranch = 'origin';
<ide> git(conf.currentPath).pull(remoteBranch+'/'+destBranch, destBranch, function(err,res){
<ide> if(err){
|
|
Java
|
apache-2.0
|
110f4acd5d8b532ab1fa137456205fde901cfc81
| 0 |
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
|
package uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.statistics;
import uk.ac.ebi.quickgo.annotation.model.StatisticsValue;
import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model.BasicTaxonomyNode;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import uk.ac.ebi.quickgo.rest.search.request.converter.ConvertedFilter;
import uk.ac.ebi.quickgo.rest.search.results.transformer.AbstractValueInjector;
/**
* This class is responsible for supplementing an {@link StatisticsValue} instance, which contains
* a taxonomy identifier (in the key field), with a taxonomy name, through the use of a RESTful service.
*
* Created 04/10/17
* @author Tony Wardell
*/
public class TaxonomyNameInjector extends AbstractValueInjector<BasicTaxonomyNode, StatisticsValue> {
static final String TAXON_NAME = "taxonName";
static final String TAXON_ID = "taxonId";
@Override
public String getId() {
return TAXON_NAME;
}
@Override
public FilterRequest buildFilterRequest(StatisticsValue statisticsValue) {
return FilterRequest.newBuilder()
.addProperty(getId())
.addProperty(TAXON_ID, String.valueOf(statisticsValue.getKey()))
.build();
}
@Override
public void injectValueFromResponse(ConvertedFilter<BasicTaxonomyNode> convertedRequest, StatisticsValue
statisticsValue) {
statisticsValue.setName(convertedRequest.getConvertedValue().getScientificName());
}
}
|
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/service/comm/rest/ontology/transformer/statistics/TaxonomyNameInjector.java
|
package uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.transformer.statistics;
import uk.ac.ebi.quickgo.annotation.model.StatisticsValue;
import uk.ac.ebi.quickgo.annotation.service.comm.rest.ontology.model.BasicTaxonomyNode;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import uk.ac.ebi.quickgo.rest.search.request.converter.ConvertedFilter;
import uk.ac.ebi.quickgo.rest.search.results.transformer.AbstractValueInjector;
/**
* This class is responsible for supplementing an {@link StatisticsValue} instance, which contains
* a taxonomy identifier (in the key field), with a taxonomy name, through the use of a RESTful service.
*
* Created 04/10/17
* @author Tony Wardell
*/
public class TaxonomyNameInjector extends AbstractValueInjector<BasicTaxonomyNode, StatisticsValue> {
private static final String TAXON_NAME = "taxonName";
private static final String TAXON_ID = "taxonId";
@Override
public String getId() {
return TAXON_NAME;
}
@Override
public FilterRequest buildFilterRequest(StatisticsValue statisticsValue) {
return FilterRequest.newBuilder()
.addProperty(getId())
.addProperty(TAXON_ID, String.valueOf(statisticsValue.getKey()))
.build();
}
@Override
public void injectValueFromResponse(ConvertedFilter<BasicTaxonomyNode> convertedRequest, StatisticsValue
statisticsValue) {
statisticsValue.setName(convertedRequest.getConvertedValue().getScientificName());
}
}
|
Make members package-private so available for testing.
|
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/service/comm/rest/ontology/transformer/statistics/TaxonomyNameInjector.java
|
Make members package-private so available for testing.
|
<ide><path>nnotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/service/comm/rest/ontology/transformer/statistics/TaxonomyNameInjector.java
<ide> */
<ide> public class TaxonomyNameInjector extends AbstractValueInjector<BasicTaxonomyNode, StatisticsValue> {
<ide>
<del> private static final String TAXON_NAME = "taxonName";
<del> private static final String TAXON_ID = "taxonId";
<add> static final String TAXON_NAME = "taxonName";
<add> static final String TAXON_ID = "taxonId";
<ide>
<ide> @Override
<ide> public String getId() {
|
|
JavaScript
|
mit
|
c150217eb9cde4d8c4560cdc9b10cf6b4d331fda
| 0 |
vulcan-estudios/vulcanval,vulcan-estudios/vulcanval,vulcan-estudios/vulcanval
|
require('./pre');
const chai = require('chai');
const extend = require('extend');
const vulcanval = require('../../src/js/vulcanval');
const utils = require('../../src/js/utils');
const assert = chai.assert;
const RULE_EMAIL_CONTAINS = 'gmail';
const RULE_USERNAME = 'romel';
const RULE_AGE = 22;
const RULE_IS_LENGTH_MIN = 8;
const RULE_IS_LENGTH_MAX = 16;
const RULE_PASSWORD = '12345678910';
const RULE_PATTERN_MSG = 'The field should contain double AA.';
const fields = {
username: RULE_USERNAME,
age: RULE_AGE,
email: '[email protected]',
password: RULE_PASSWORD
};
const settings = {
validators: {
isTheFieldUpperCase (value, opts) {
return String(value).toUpperCase() === value;
},
areTheFirst4LettersLC (value, opts) {
return String(value).substring(0, 4).toLowerCase() === String(value).substring(0, 4);
},
valSharedValues (value, opts) {
const username = this.get('username');
const age = this.get('age');
return age === RULE_AGE && username === RULE_USERNAME;
}
},
msgs: {
isEqualToField: 'The password must the the same.',
isTheFieldUpperCase: 'The field has to be in upper case.',
areTheFirst4LettersLC: {
en: 'The first four letters have to be lower case.',
es: 'Las primeras 4 letras tienen que estar en minúscula.'
}
},
fields: [{
name: 'username',
required: true
}, {
name: 'age',
required: false
}, {
name: 'email',
required: true,
validators: {
isEmail: true,
contains: RULE_EMAIL_CONTAINS
}
}, {
name: 'bio',
disabled: true,
required: true,
validators: {
isEmail: true,
isFloat: true
}
}, {
name: 'password',
required: false,
validators: {
isLength: {
min: RULE_IS_LENGTH_MIN,
max: RULE_IS_LENGTH_MAX
},
isInt: {
min: 100,
max: 1000000000000
}
}
}, {
name: 'isLengthFail',
required: true,
validators: {
isLength: true
}
}, {
name: 'doubleA',
required: true,
validators: {
matches: {
pattern: /AA/,
msgs: RULE_PATTERN_MSG
}
}
}, {
name: 'matchesFail',
required: true,
validators: {
matches: /abc/
}
}, {
name: 'hasManyDisabledValidators',
validators: {
contains: false,
isInt: false,
isHexColor: false,
isFQDN: false
}
}, {
name: 'repeatPassword',
required: true,
validators: {
isEqualToField: 'password'
}
}, {
name: 'wrongValidators',
required: true,
validators: {
wrong: {},
anotherWrong: true
}
}, {
name: 'fieldUC',
validators: {
isTheFieldUpperCase: true
}
}, {
name: 'first4lc',
validators: {
areTheFirst4LettersLC: true
}
}, {
name: 'shared',
validators: {
valSharedValues: true
}
}, {
name: 'withCondition',
required: true,
onlyIf (value) {
return this.get('username') !== value;
},
validators: {
isEmail: true,
isLength: {
min: 8,
max: 32
}
}
}]
};
var field;
describe('Method validateField()', function () {
describe('General', function () {
it('Field with an invalid validation definition should throw error', function () {
assert.throws(function () {
vulcanval.validateField('fieldName', {
fieldName: 'a value'
}, {
fields: [
{
name: 'aProperField',
required: true
},
'this will trigger the error'
]
});
});
});
it('Field without validators', function () {
field = 'notFoundField';
fields[field] = '';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Field with a wrong validator should throw error', function () {
field = 'wrongValidators';
fields[field] = 'wrong value';
assert.throws(function () {
vulcanval.validateField(field, fields, settings);
});
});
it('A disabled field should not be validated', function () {
field = 'bio';
fields[field] = 'whatever';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Sharing values', function () {
field = 'shared';
fields[field] = 'whatever';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Condition disabled', function () {
field = 'withCondition';
fields[field] = RULE_USERNAME;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Condition enabled', function () {
field = 'withCondition';
fields[field] = 'oh whatever';
assert.isString(vulcanval.validateField(field, fields, settings));
field = 'withCondition';
fields[field] = '[email protected]';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
describe('Required', function () {
describe('With no validators', function () {
it('String with length', function () {
field = 'username';
fields[field] = 'A random value';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Number', function () {
field = 'username';
fields[field] = -157.978;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Boolean true', function () {
field = 'username';
fields[field] = true;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Empty string', function () {
field = 'username';
fields[field] = '';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Boolean false', function () {
field = 'username';
fields[field] = false;
assert.isString(vulcanval.validateField(field, fields, settings));
});
});
describe('Booleans', function () {
it('Required with true', function () {
field = 'username';
fields[field] = true;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Required with false', function () {
field = 'username';
fields[field] = false;
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('No required with true', function () {
field = 'age';
fields[field] = true;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('No required with false', function () {
field = 'age';
fields[field] = false;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
describe('No required with no validators', function () {
it('Empty string', function () {
field = 'lastName';
fields[field] = '';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('String with length', function () {
field = 'lastName';
fields[field] = 'a random value';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Number', function () {
field = 'lastName';
fields[field] = -157.978;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Boolean true', function () {
field = 'lastName';
fields[field] = true;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Boolean false', function () {
field = 'lastName';
fields[field] = false;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
});
describe('Validators', function () {
it('Validator "isLength"', function () {
field = 'isLengthFail';
fields[field] = 'whatever';
assert.throws(function () {
vulcanval.validateField(field, fields, settings);
});
});
it('Validator "matches"', function () {
field = 'doubleA';
fields[field] = 'something AA here';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
field = 'doubleA';
fields[field] = 'something without that';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Many validators but disabled', function () {
field = 'hasManyDisabledValidators';
fields[field] = 'whatever';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
describe('Is required with validators', function () {
it('Empty string', function () {
field = 'email';
fields[field] = '';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Wrong value', function () {
field = 'email';
fields[field] = 'wrong mail';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Multiples validators and partially valid', function () {
field = 'email';
fields[field] = '[email protected]';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Multiples validators and valid', function () {
field = 'email';
fields[field] = '[email protected]';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
it('No required with validators | Validator "isLength"', function () {
it('Empty string', function () {
field = 'password';
fields[field] = '';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Value too short should fail', function () {
field = 'password';
fields[field] = 'wrong';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Value too long should fail', function () {
field = 'password';
fields[field] = 'this is a really long field value';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('The value is not a proper integer so should fail', function () {
field = 'password';
fields[field] = 'almostPass';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Valid', function () {
field = 'password';
fields[field] = '715458484847';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
});
describe('Built-in validators', function () {
describe('Validator "isEqualToField"', function () {
it('Invalid', function () {
field = 'repeatPassword';
fields[field] = 'notEqual123';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Valid', function () {
field = 'repeatPassword';
fields[field] = RULE_PASSWORD;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
});
describe('Custom validators', function () {
it('Part 1', function () {
field = 'fieldUC';
fields[field] = 'notUpperCase';
assert.isString(vulcanval.validateField(field, fields, settings));
field = 'fieldUC';
fields[field] = 'UPPERCASE';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Part 2', function () {
field = 'first4lc';
fields[field] = 'NotLowerCase';
assert.isString(vulcanval.validateField(field, fields, settings));
field = 'first4lc';
fields[field] = 'lowerCASE';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
});
|
test/global/validateField.js
|
require('./pre');
const chai = require('chai');
const extend = require('extend');
const vulcanval = require('../../src/js/vulcanval');
const utils = require('../../src/js/utils');
const assert = chai.assert;
const RULE_EMAIL_CONTAINS = 'gmail';
const RULE_USERNAME = 'romel';
const RULE_AGE = 22;
const RULE_IS_LENGTH_MIN = 8;
const RULE_IS_LENGTH_MAX = 16;
const RULE_PASSWORD = '12345678910';
const RULE_PATTERN_MSG = 'The field should contain double AA.';
const fields = {
username: RULE_USERNAME,
age: RULE_AGE,
email: '[email protected]',
password: RULE_PASSWORD
};
const settings = {
validators: {
isTheFieldUpperCase (value, opts) {
return String(value).toUpperCase() === value;
},
areTheFirst4LettersLC (value, opts) {
return String(value).substring(0, 4).toLowerCase() === String(value).substring(0, 4);
},
valSharedValues (value, opts) {
const username = this.get('username');
const age = this.get('age');
return age === RULE_AGE && username === RULE_USERNAME;
}
},
msgs: {
isEqualToField: 'The password must the the same.',
isTheFieldUpperCase: 'The field has to be in upper case.',
areTheFirst4LettersLC: {
en: 'The first four letters have to be lower case.',
es: 'Las primeras 4 letras tienen que estar en minúscula.'
}
},
fields: [{
name: 'username',
required: true
}, {
name: 'age',
required: false
}, {
name: 'email',
required: true,
validators: {
isEmail: true,
contains: RULE_EMAIL_CONTAINS
}
}, {
name: 'bio',
disabled: true,
required: true,
validators: {
isEmail: true,
isFloat: true
}
}, {
name: 'password',
required: false,
validators: {
isLength: {
min: RULE_IS_LENGTH_MIN,
max: RULE_IS_LENGTH_MAX
},
isInt: {
min: 100,
max: 1000000000000
}
}
}, {
name: 'isLengthFail',
required: true,
validators: {
isLength: true
}
}, {
name: 'doubleA',
required: true,
validators: {
matches: {
pattern: /AA/,
msgs: RULE_PATTERN_MSG
}
}
}, {
name: 'matchesFail',
required: true,
validators: {
matches: /abc/
}
}, {
name: 'hasManyDisabledValidators',
validators: {
contains: false,
isInt: false,
isHexColor: false,
isFQDN: false
}
}, {
name: 'repeatPassword',
required: true,
validators: {
isEqualToField: 'password'
}
}, {
name: 'wrongValidators',
required: true,
validators: {
wrong: {},
anotherWrong: true
}
}, {
name: 'fieldUC',
validators: {
isTheFieldUpperCase: true
}
}, {
name: 'first4lc',
validators: {
areTheFirst4LettersLC: true
}
}, {
name: 'shared',
validators: {
valSharedValues: true
}
}, {
name: 'withCondition',
required: true,
onlyIf (value) {
return this.get('username') !== value;
},
validators: {
isEmail: true,
isLength: {
min: 8,
max: 32
}
}
}]
};
var field;
describe('Method validateField()', function () {
describe('General', function () {
it('Field without validators', function () {
field = 'notFoundField';
fields[field] = '';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Field with a wrong validator should throw error', function () {
field = 'wrongValidators';
fields[field] = 'wrong value';
assert.throws(function () {
vulcanval.validateField(field, fields, settings);
});
});
it('A disabled field should not be validated', function () {
field = 'bio';
fields[field] = 'whatever';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Sharing values', function () {
field = 'shared';
fields[field] = 'whatever';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Condition disabled', function () {
field = 'withCondition';
fields[field] = RULE_USERNAME;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Condition enabled', function () {
field = 'withCondition';
fields[field] = 'oh whatever';
assert.isString(vulcanval.validateField(field, fields, settings));
field = 'withCondition';
fields[field] = '[email protected]';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
describe('Required', function () {
describe('With no validators', function () {
it('String with length', function () {
field = 'username';
fields[field] = 'A random value';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Number', function () {
field = 'username';
fields[field] = -157.978;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Boolean true', function () {
field = 'username';
fields[field] = true;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Empty string', function () {
field = 'username';
fields[field] = '';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Boolean false', function () {
field = 'username';
fields[field] = false;
assert.isString(vulcanval.validateField(field, fields, settings));
});
});
describe('Booleans', function () {
it('Required with true', function () {
field = 'username';
fields[field] = true;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Required with false', function () {
field = 'username';
fields[field] = false;
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('No required with true', function () {
field = 'age';
fields[field] = true;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('No required with false', function () {
field = 'age';
fields[field] = false;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
describe('No required with no validators', function () {
it('Empty string', function () {
field = 'lastName';
fields[field] = '';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('String with length', function () {
field = 'lastName';
fields[field] = 'a random value';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Number', function () {
field = 'lastName';
fields[field] = -157.978;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Boolean true', function () {
field = 'lastName';
fields[field] = true;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Boolean false', function () {
field = 'lastName';
fields[field] = false;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
});
describe('Validators', function () {
it('Validator "isLength"', function () {
field = 'isLengthFail';
fields[field] = 'whatever';
assert.throws(function () {
vulcanval.validateField(field, fields, settings);
});
});
it('Validator "matches"', function () {
field = 'doubleA';
fields[field] = 'something AA here';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
field = 'doubleA';
fields[field] = 'something without that';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Many validators but disabled', function () {
field = 'hasManyDisabledValidators';
fields[field] = 'whatever';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
describe('Is required with validators', function () {
it('Empty string', function () {
field = 'email';
fields[field] = '';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Wrong value', function () {
field = 'email';
fields[field] = 'wrong mail';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Multiples validators and partially valid', function () {
field = 'email';
fields[field] = '[email protected]';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Multiples validators and valid', function () {
field = 'email';
fields[field] = '[email protected]';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
it('No required with validators | Validator "isLength"', function () {
it('Empty string', function () {
field = 'password';
fields[field] = '';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Value too short should fail', function () {
field = 'password';
fields[field] = 'wrong';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Value too long should fail', function () {
field = 'password';
fields[field] = 'this is a really long field value';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('The value is not a proper integer so should fail', function () {
field = 'password';
fields[field] = 'almostPass';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Valid', function () {
field = 'password';
fields[field] = '715458484847';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
});
describe('Built-in validators', function () {
describe('Validator "isEqualToField"', function () {
it('Invalid', function () {
field = 'repeatPassword';
fields[field] = 'notEqual123';
assert.isString(vulcanval.validateField(field, fields, settings));
});
it('Valid', function () {
field = 'repeatPassword';
fields[field] = RULE_PASSWORD;
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
});
describe('Custom validators', function () {
it('Part 1', function () {
field = 'fieldUC';
fields[field] = 'notUpperCase';
assert.isString(vulcanval.validateField(field, fields, settings));
field = 'fieldUC';
fields[field] = 'UPPERCASE';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
it('Part 2', function () {
field = 'first4lc';
fields[field] = 'NotLowerCase';
assert.isString(vulcanval.validateField(field, fields, settings));
field = 'first4lc';
fields[field] = 'lowerCASE';
assert.strictEqual(vulcanval.validateField(field, fields, settings), true);
});
});
});
|
test: validateField cases
|
test/global/validateField.js
|
test: validateField cases
|
<ide><path>est/global/validateField.js
<ide>
<ide> describe('General', function () {
<ide>
<add> it('Field with an invalid validation definition should throw error', function () {
<add> assert.throws(function () {
<add> vulcanval.validateField('fieldName', {
<add> fieldName: 'a value'
<add> }, {
<add> fields: [
<add> {
<add> name: 'aProperField',
<add> required: true
<add> },
<add> 'this will trigger the error'
<add> ]
<add> });
<add> });
<add> });
<add>
<ide> it('Field without validators', function () {
<ide> field = 'notFoundField';
<ide> fields[field] = '';
|
|
Java
|
mit
|
22112b9205f2f40c463ef62e53e926a81adfec59
| 0 |
TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin
|
/*
* The MIT License
*
* Copyright 2017.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.fakekoji.http;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import hudson.plugins.scm.koji.NotProcessedNvrPredicate;
import hudson.plugins.scm.koji.client.BuildMatcher;
import hudson.plugins.scm.koji.client.GlobPredicate;
import hudson.plugins.scm.koji.model.Build;
import hudson.plugins.scm.koji.model.RPM;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.fakekoji.xmlrpc.server.JavaServer;
public class PreviewFakeKoji {
public static URL setUriPort(URL uri, int port) throws MalformedURLException {
URL newUri = new URL(uri.getProtocol(), uri.getHost(), port, uri.getFile());
return newUri;
}
public static void main(String[] args) throws MalformedURLException, IOException {
//defualting to 80 with all consequences
args = new String[]{
"http://hydra.brq.redhat.com/RPC2/",
"http://hydra.brq.redhat.com/",
"/mnt/raid1/upstream-repos",
"/mnt/raid1/local-builds",
"1919"
};
if (args.length < 3) {
System.out.println("Mandatory 4 params: full koji xmlrpc url and koji download url and cloned forests homes and projects homes");
System.out.println("if no port is specified, my favorit XPORT and DPORT are used,");
System.out.println("If only first port is specified, second is deducted from it as for fake-koji");
System.out.println("last param is optional and is port of this service. If missing, 80 is used!");
}
URL xmlrpcurl = new URL(args[0]);
URL download = new URL(args[1]);
File repos = new File(args[2]);
File builds = new File(args[3]);
if (!builds.exists()) {
throw new RuntimeException(builds.getAbsolutePath() + " does not exists.");
}
if (!repos.exists()) {
throw new RuntimeException(repos.getAbsolutePath() + " does not exists.");
}
if (xmlrpcurl.getPort() < 0) {
xmlrpcurl = setUriPort(xmlrpcurl, JavaServer.DFAULT_RP2C_PORT);
}
if (download.getPort() < 0) {
download = setUriPort(download, JavaServer.deductDwPort(xmlrpcurl.getPort()));
}
int PORT = 80;
if (args.length == 5) {
PORT = Integer.valueOf(args[4]);
}
System.err.println("xmlrpc : " + xmlrpcurl);
System.out.println("xmlrpc : " + xmlrpcurl);
System.err.println("dwnld : " + download);
System.out.println("dwnld : " + download);
System.err.println("port : " + PORT);
System.out.println("port : " + PORT);
System.err.println("repos : " + repos);
System.out.println("repos : " + repos);
System.err.println("builds : " + builds);
System.out.println("builds : " + builds);
new FakeKojiPreviewServer(xmlrpcurl, download, PORT, repos, builds).start();
}
private static List<File> filter(File[] candidates) {
List<File> r = new ArrayList<>(candidates.length);
for (File candidate : candidates) {
if (candidate.isDirectory()) {
Path pf = candidate.toPath();
if (!Files.isSymbolicLink(pf)) {
r.add(candidate);
}
}
}
Collections.sort(r);
Collections.reverse(r);
return r;
}
private static class Project extends Product {
public Project(File backedn) {
super(backedn);
}
public static List<Project> FilesToProjects(File dir) {
List<File> candidates = filter(dir.listFiles());
List<Project> r = new ArrayList<>(candidates.size());
for (File f : candidates) {
r.add(new Project(f));
}
return r;
}
public String getSuffixToString() {
String s = getSuffix();
if (s.isEmpty()) {
return getName();
}
return s;
}
public String getSuffix() {
String[] s = getName().split("-");
if (s.length < 3) {
throw new RuntimeException("Strange repo " + getName());
}
if (s.length == 3) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 3; i < s.length; i++) {
sb.append("-").append(s[i]);
}
return sb.substring(1);
}
public String getPrefix() {
String[] s = getName().split("-");
if (s.length < 3) {
throw new RuntimeException("Strange repo " + getName());
}
if (s.length == 3) {
return getName();
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("-").append(s[i]);
}
return sb.substring(1);
}
}
private static class Product {
private final File backend;
public Product(File backend) {
this.backend = backend;
}
public static List<Product> FilesToBuilds(File dir) {
List<File> candidates = filter(dir.listFiles());
List<Product> r = new ArrayList<>(candidates.size());
for (File f : candidates) {
r.add(new Product(f));
}
return r;
}
public File getDir() {
return backend.getAbsoluteFile();
}
public String getName() {
return backend.getName();
}
/*
VERY infrastrucutre specific
*/
public String getJenkinsMapping() {
if (getName().equals("java-1.8.0-openjdk")) {
return "ojdk8";
}
if (getName().equals("java-1.7.0-openjdk")) {
return "ojdk7";
}
if (getName().equals("java-9-openjdk")) {
return "ojdk9";
}
return getName();
}
}
private static class FakeKojiPreviewServer {
private final int port;
private final IndexHtmlHandler ihh;
private final DetailsHtmlHandler dhh;
public FakeKojiPreviewServer(URL xmlrpcurl, URL download, int PORT, File repos, File builds) {
port = PORT;
ihh = new IndexHtmlHandler(xmlrpcurl, download, Project.FilesToProjects(repos), Product.FilesToBuilds(builds), port);
dhh = new DetailsHtmlHandler(xmlrpcurl, download, Project.FilesToProjects(repos), Product.FilesToBuilds(builds), port);
}
private void start() throws IOException {
HttpServer hs = HttpServer.create(new InetSocketAddress(port), 0);
hs.createContext("/", ihh);
hs.createContext("/details.html", dhh);
hs.start();
}
}
public static class IndexHtmlHandler implements HttpHandler {
private final URL xmlrpc;
private final URL dwnld;
private final List<Project> projects;
private final List<Product> products;
private final int port;
private IndexHtmlHandler(URL xmlrpcurl, URL download, List<Project> projects, List<Product> builds, int port) {
xmlrpc = xmlrpcurl;
dwnld = download;
this.projects = projects;
this.products = builds;
this.port = port;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
RequestRunner rr = new RequestRunner(exchange);
new Thread(rr).start();
}
private String getJenkinsUrl() {
return getUrl(8080);
}
private String getUrl() {
return getUrl(port);
}
private String getUrl(int port) {
return dwnld.getProtocol() + "://" + dwnld.getHost() + ":" + port;
}
private class RequestRunner implements Runnable {
private final HttpExchange t;
public RequestRunner(HttpExchange t) {
this.t = t;
}
@Override
public void run() {
try {
runImpl();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void runImpl() throws IOException {
String requestedFile = t.getRequestURI().getPath();
System.out.println(new Date().toString() + "attempting: " + requestedFile);
generateIndex(t);
}
}
private void generateIndex(HttpExchange t) throws IOException {
System.out.println("Regenerating index!");
StringBuilder sb = generateIndex();
String result = sb.toString();
long size = result.length(); //yahnot perfect, ets assuemno one will use this on chinese chars
t.sendResponseHeaders(200, size);
try (OutputStream os = t.getResponseBody()) {
os.write(result.getBytes());
}
}
private StringBuilder generateIndex() throws IOException {
final StringBuilder sb = new StringBuilder();
sb.append("<html>\n");
sb.append(" <body>\n");
sb.append(" <h1>").append("Latest builds of upstream OpenJDK").append("</h1>\n");
for (Product product : products) {
sb.append(" <a href='#").append(product.getName()).append("'>").append(product.getName()).append("</a>\n");
}
sb.append(" <p>")
.append("if you are searching for failed builds or logs or test results, feel free to search directly in <a href='")
.append(getJenkinsUrl())
.append("'>jenkins</a> in connection with direct listing in <a href='")
.append(dwnld.toExternalForm())
.append("'>fake-koji</a>").append("</p>\n");
sb.append(" <p>")
.append("Total ").append(products.size())
.append(" products from ").append(projects.size()).append(" projects.")
.append("</p>\n");
for (Product product : products) {
sb.append("<blockquote>");
//get all products of top-project
Object[] buildObjects = new BuildMatcher(
xmlrpc.toExternalForm(),
new NotProcessedNvrPredicate(new HashSet<>()),
new GlobPredicate("*"),
5000, product.getName(), null).getAll();
sb.append(" <a name='").append(product.getName()).append("'/>\n");
sb.append(" <h2>").append(product.getName()).append("</h2>\n");
int fastdebugs = 0;
for (Object buildObject : buildObjects) {
if (buildObject.toString().contains("fastdebug")) {
fastdebugs++;
}
System.err.println(buildObject);
}
//now this is nasty, and very infrastructure specific
//we have to filter projects valid to producets. Thats doen by prefix
List<Project> validProjects = new ArrayList<>(projects.size());
for (Project project : projects) {
if (project.getPrefix().equals(product.getName())) {
//should be already sorted by string
validProjects.add(project);
}
}
for (Project validProject : validProjects) {
sb.append(" <a href='#PR-").append(validProject.getName()).append("'>").append(validProject.getSuffixToString()).append("</a>\n");
}
sb.append(" <p>")
.append("Found ").append(buildObjects.length)
.append(" successful builds and ").append(validProjects.size()).append(" relevant projects")
.append(" From those ").append(Integer.valueOf(buildObjects.length - fastdebugs)).append(" are normal builds.")
.append(" and ").append(fastdebugs).append(" are fastdebug builds.")
.append("</p>\n");
sb.append(" <p>")
.append("You can see all ").append(buildObjects.length)
.append(" builds details <a href='details.html?list=TODO1'> here</a>.")
.append(" You can jenkins build results in <a href='").append(getJenkinsUrl()).append("/search/?q=build-static-").append(product.getJenkinsMapping()).append("'> here</a>.")
.append(" You can jenkins TEST results in <a href='").append(getJenkinsUrl()).append("/search/?max=2000&q=").append(product.getJenkinsMapping()).append("'> here</a>.")
.append("</p>\n");
List<Build> usedBuilds = new ArrayList<>(buildObjects.length);
//now wee need to filetr only project's products
// the suffix is projected to *release*
//and is behind leading NUMBER. and have all "-" repalced by "."
//in addition we need to strip all keywords. usually usptream or usptream.fastdebug or static
//yes, oh crap
for (Project validProject : validProjects) {
List<Build> projectsBuilds = new ArrayList<>(buildObjects.length);
Map<String, Build> projectsFastdebugBuilds = new HashMap<>(buildObjects.length);
sb.append(" <a name='PR-").append(validProject.getName()).append("'/>");
sb.append(" <h3>").append(validProject.getSuffixToString()).append("</h3>\n");
for (Object object : buildObjects) {
//also we need to remove all fastdebug products and ony offer them together with normal of same VRA
Build built = (Build) object;
String cleanedSuffix = built.getRelease();
cleanedSuffix = cleanedSuffix.replaceAll(".upstream.*", "");
cleanedSuffix = cleanedSuffix.replaceAll(".static.*", "");
String suffixCandidate = "";
if (cleanedSuffix.contains(".")) {
suffixCandidate = cleanedSuffix.substring(cleanedSuffix.indexOf(".") + 1);
}
String relaseLikeSuffix = validProject.getSuffix().replaceAll("-", ".");
if (suffixCandidate.equals(relaseLikeSuffix)) {
usedBuilds.add(built);
if (built.getRelease().contains("fastdebug")) {
projectsFastdebugBuilds.put(built.getNvr().replaceAll(".fastdebug", ""), built);
} else {
projectsBuilds.add(built);
}
}
}
Build build = null;
if (!projectsBuilds.isEmpty()) {
build = projectsBuilds.get(projectsBuilds.size() - 1);
}
offerBuild(build, projectsFastdebugBuilds, sb, projectsBuilds, dwnld);
}
if (usedBuilds.size() != buildObjects.length) {
List<Build> unUsedBuilds = new ArrayList<>(-usedBuilds.size() + buildObjects.length);
for (Object bo : buildObjects) {
if (usedBuilds.contains((Build) bo)) {
} else {
unUsedBuilds.add((Build) bo);
}
}
sb.append(" <h3>There are unsorted ").append(unUsedBuilds.size()).append(" builds: </h3>\n");
sb.append(" <p>")
.append("You can see them <a href='details.html?list=TODO3'> here</a>.")
.append("</p>\n");
}
sb.append("</blockquote>");
}
return sb;
}
}
public static class DetailsHtmlHandler implements HttpHandler {
private final URL xmlrpc;
private final URL dwnld;
private final List<Project> projects;
private final List<Product> products;
private final int port;
private DetailsHtmlHandler(URL xmlrpcurl, URL download, List<Project> projects, List<Product> builds, int port) {
xmlrpc = xmlrpcurl;
dwnld = download;
this.projects = projects;
this.products = builds;
this.port = port;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
RequestRunner rr = new RequestRunner(exchange);
new Thread(rr).start();
}
private class RequestRunner implements Runnable {
private final HttpExchange t;
public RequestRunner(HttpExchange t) {
this.t = t;
}
@Override
public void run() {
try {
runImpl();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void runImpl() throws IOException {
String requestedFile = t.getRequestURI().getPath();
System.out.println(new Date().toString() + "attempting: " + requestedFile);
generateIndex(t);
}
}
private void generateIndex(HttpExchange t) throws IOException {
System.out.println("Regenerating index!");
StringBuilder sb = new StringBuilder("todo: show detaisl of all builds given as &list= parameter");
String result = sb.toString();
long size = result.length(); //yahnot perfect, ets assuemno one will use this on chinese chars
t.sendResponseHeaders(200, size);
try (OutputStream os = t.getResponseBody()) {
os.write(result.getBytes());
}
}
}
private static void offerBuild(Build build, Map<String, Build> projectsFastdebugBuilds, StringBuilder sb, List<Build> projectsBuilds, URL dwnld) {
sb.append("<blockquote>");
if (build == null) {
sb.append(" <p>").append("Sorry, no successful build matches this project. You may check all builds of this product.").append("</p><br/>\n");
} else {
sb.append(" <b>").append(build.getNvr()).append("</b><br/>\n");
sb.append(" <small>").append(build.getCompletionTime()).append("</small><br/>\n");
sb.append(offerDownloads(dwnld.toExternalForm(), build));
Build bb = projectsFastdebugBuilds.get(build.getNvr());
if (bb == null) {
sb.append(" <i>no fast debug build found</i><br/>\n");
} else {
sb.append(" <i>").append(bb.getNvr()).append("</i><br/>\n");
sb.append(" <i><small>").append(bb.getCompletionTime()).append("</small></i><br/>\n");
sb.append("<small>\n");
sb.append(offerDownloads(dwnld.toExternalForm(), bb));
sb.append("</small><br/>\n");
}
if (projectsBuilds != null) {
sb.append(" <p>")
.append("You can see all ").append(projectsBuilds.size())
.append(" builds details (and ").append(projectsFastdebugBuilds.size()).append(" fast builds) <a href='details.html?list=TODO2'> here</a>.")
.append("</p>\n");
}
}
sb.append("</blockquote>");
}
public static String offerDownloads(String baseUrl, Build build) {
List<RPM> rpms = new ArrayList<>(build.getRpms());
Collections.sort(rpms, new Comparator<RPM>() {
@Override
public int compare(RPM o1, RPM o2) {
return o1.getArch().compareTo(o2.getArch());
}
});
String sourceSnapshot = "";
StringBuilder r = new StringBuilder();
r.append("<blockquote>");
for (RPM rpm : rpms) {
if (!baseUrl.endsWith("/")) {
baseUrl = baseUrl + "/";
}
String mainUrl = baseUrl + rpm.getName() + "/" + rpm.getVersion() + "/" + rpm.getRelease();
String archedUrl = mainUrl + "/" + rpm.getArch();
String logsUrl = mainUrl + "/data/logs/" + rpm.getArch();
String filename = rpm.getFilename("tarxz");
String fileUrl = archedUrl + "/" + filename;
if (rpm.getArch().equals("src")) {
sourceSnapshot = "sources: <a href='" + fileUrl + "'>src snapshot</a> <a href='" + logsUrl + "'>hg incomming logs</a><br/>";
} else {
r.append("<b>").append(rpm.getArch()).append("</b>: \n");
r.append("<a href='")
.append(fileUrl)
.append("'>")
.append(filename)
.append("</a> <a href='")
.append(logsUrl)
.append("'>build logs</a><br/>");
}
}
r.append(sourceSnapshot);
r.append("</blockquote>");
return r.toString();
}
}
|
src/main/java/org/fakekoji/http/PreviewFakeKoji.java
|
/*
* The MIT License
*
* Copyright 2017.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.fakekoji.http;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import hudson.plugins.scm.koji.NotProcessedNvrPredicate;
import hudson.plugins.scm.koji.client.BuildMatcher;
import hudson.plugins.scm.koji.client.GlobPredicate;
import hudson.plugins.scm.koji.model.Build;
import hudson.plugins.scm.koji.model.RPM;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.fakekoji.xmlrpc.server.JavaServer;
public class PreviewFakeKoji {
public static URL setUriPort(URL uri, int port) throws MalformedURLException {
URL newUri = new URL(uri.getProtocol(), uri.getHost(), port, uri.getFile());
return newUri;
}
public static void main(String[] args) throws MalformedURLException, IOException {
//defualting to 80 with all consequences
args = new String[]{
"http://hydra.brq.redhat.com/RPC2/",
"http://hydra.brq.redhat.com/",
"/mnt/raid1/upstream-repos",
"/mnt/raid1/local-builds",
//"1919"
};
if (args.length < 3) {
System.out.println("Mandatory 4 params: full koji xmlrpc url and koji download url and cloned forests homes and projects homes");
System.out.println("if no port is specified, my favorit XPORT and DPORT are used,");
System.out.println("If only first port is specified, second is deducted from it as for fake-koji");
System.out.println("last param is optional and is port of this service. If missing, 80 is used!");
}
URL xmlrpcurl = new URL(args[0]);
URL download = new URL(args[1]);
File repos = new File(args[2]);
File builds = new File(args[3]);
if (!builds.exists()) {
throw new RuntimeException(builds.getAbsolutePath() + " does not exists.");
}
if (!repos.exists()) {
throw new RuntimeException(repos.getAbsolutePath() + " does not exists.");
}
if (xmlrpcurl.getPort() < 0) {
xmlrpcurl = setUriPort(xmlrpcurl, JavaServer.DFAULT_RP2C_PORT);
}
if (download.getPort() < 0) {
download = setUriPort(download, JavaServer.deductDwPort(xmlrpcurl.getPort()));
}
int PORT = 80;
if (args.length == 5) {
PORT = Integer.valueOf(args[4]);
}
System.err.println("xmlrpc : " + xmlrpcurl);
System.out.println("xmlrpc : " + xmlrpcurl);
System.err.println("dwnld : " + download);
System.out.println("dwnld : " + download);
System.err.println("port : " + PORT);
System.out.println("port : " + PORT);
System.err.println("repos : " + repos);
System.out.println("repos : " + repos);
System.err.println("builds : " + builds);
System.out.println("builds : " + builds);
new FakeKojiPreviewServer(xmlrpcurl, download, PORT, repos, builds).start();
}
private static List<File> filter(File[] candidates) {
List<File> r = new ArrayList<>(candidates.length);
for (File candidate : candidates) {
if (candidate.isDirectory()) {
Path pf = candidate.toPath();
if (!Files.isSymbolicLink(pf)) {
r.add(candidate);
}
}
}
Collections.sort(r);
Collections.reverse(r);
return r;
}
private static class Project extends Product {
public Project(File backedn) {
super(backedn);
}
public static List<Project> FilesToProjects(File dir) {
List<File> candidates = filter(dir.listFiles());
List<Project> r = new ArrayList<>(candidates.size());
for (File f : candidates) {
r.add(new Project(f));
}
return r;
}
public String getSuffixToString() {
String s = getSuffix();
if (s.isEmpty()) {
return getName();
}
return s;
}
public String getSuffix() {
String[] s = getName().split("-");
if (s.length < 3) {
throw new RuntimeException("Strange repo " + getName());
}
if (s.length == 3) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 3; i < s.length; i++) {
sb.append("-").append(s[i]);
}
return sb.substring(1);
}
public String getPrefix() {
String[] s = getName().split("-");
if (s.length < 3) {
throw new RuntimeException("Strange repo " + getName());
}
if (s.length == 3) {
return getName();
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("-").append(s[i]);
}
return sb.substring(1);
}
}
private static class Product {
private final File backend;
public Product(File backend) {
this.backend = backend;
}
public static List<Product> FilesToBuilds(File dir) {
List<File> candidates = filter(dir.listFiles());
List<Product> r = new ArrayList<>(candidates.size());
for (File f : candidates) {
r.add(new Product(f));
}
return r;
}
public File getDir() {
return backend.getAbsoluteFile();
}
public String getName() {
return backend.getName();
}
/*
VERY infrastrucutre specific
*/
public String getJenkinsMapping() {
if (getName().equals("java-1.8.0-openjdk")) {
return "ojdk8";
}
if (getName().equals("java-1.7.0-openjdk")) {
return "ojdk7";
}
if (getName().equals("java-9-openjdk")) {
return "ojdk9";
}
return getName();
}
}
private static class FakeKojiPreviewServer {
private final int port;
private final IndexHtmlHandler ihh;
private final DetailsHtmlHandler dhh;
public FakeKojiPreviewServer(URL xmlrpcurl, URL download, int PORT, File repos, File builds) {
port = PORT;
ihh = new IndexHtmlHandler(xmlrpcurl, download, Project.FilesToProjects(repos), Product.FilesToBuilds(builds), port);
dhh = new DetailsHtmlHandler(xmlrpcurl, download, Project.FilesToProjects(repos), Product.FilesToBuilds(builds), port);
}
private void start() throws IOException {
HttpServer hs = HttpServer.create(new InetSocketAddress(port), 0);
hs.createContext("/", ihh);
hs.createContext("/details.html", dhh);
hs.start();
}
}
public static class IndexHtmlHandler implements HttpHandler {
private final URL xmlrpc;
private final URL dwnld;
private final List<Project> projects;
private final List<Product> products;
private final int port;
private IndexHtmlHandler(URL xmlrpcurl, URL download, List<Project> projects, List<Product> builds, int port) {
xmlrpc = xmlrpcurl;
dwnld = download;
this.projects = projects;
this.products = builds;
this.port = port;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
RequestRunner rr = new RequestRunner(exchange);
new Thread(rr).start();
}
private String getJenkinsUrl() {
return getUrl(8080);
}
private String getUrl() {
return getUrl(port);
}
private String getUrl(int port) {
return dwnld.getProtocol() + "://" + dwnld.getHost() + ":" + port;
}
private class RequestRunner implements Runnable {
private final HttpExchange t;
public RequestRunner(HttpExchange t) {
this.t = t;
}
@Override
public void run() {
try {
runImpl();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void runImpl() throws IOException {
String requestedFile = t.getRequestURI().getPath();
System.out.println(new Date().toString() + "attempting: " + requestedFile);
generateIndex(t);
}
}
private void generateIndex(HttpExchange t) throws IOException {
System.out.println("Regenerating index!");
StringBuilder sb = generateIndex();
String result = sb.toString();
long size = result.length(); //yahnot perfect, ets assuemno one will use this on chinese chars
t.sendResponseHeaders(200, size);
try (OutputStream os = t.getResponseBody()) {
os.write(result.getBytes());
}
}
private StringBuilder generateIndex() throws IOException {
final StringBuilder sb = new StringBuilder();
sb.append("<html>\n");
sb.append(" <body>\n");
sb.append(" <h1>").append("Latest builds of upstream OpenJDK").append("</h1>\n");
for (Product product : products) {
sb.append(" <a href='#").append(product.getName()).append("'>").append(product.getName()).append("</a>\n");
}
sb.append(" <p>")
.append("if you are searching for failed builds or logs or test results, feel free to search directly in <a href='")
.append(getJenkinsUrl())
.append("'>jenkins</a> in connection with direct listing in <a href='")
.append(dwnld.toExternalForm())
.append("'>fake-koji</a>").append("</p>\n");
sb.append(" <p>")
.append("Total ").append(products.size())
.append(" products from ").append(projects.size()).append(" projects.")
.append("</p>\n");
for (Product product : products) {
sb.append("<blockquote>");
//get all products of top-project
Object[] buildObjects = new BuildMatcher(
xmlrpc.toExternalForm(),
new NotProcessedNvrPredicate(new HashSet<>()),
new GlobPredicate("*"),
5000, product.getName(), null).getAll();
sb.append(" <a name='").append(product.getName()).append("'/>\n");
sb.append(" <h2>").append(product.getName()).append("</h2>\n");
int fastdebugs = 0;
for (Object buildObject : buildObjects) {
if (buildObject.toString().contains("fastdebug")) {
fastdebugs++;
}
System.err.println(buildObject);
}
//now this is nasty, and very infrastructure specific
//we have to filter projects valid to producets. Thats doen by prefix
List<Project> validProjects = new ArrayList<>(projects.size());
for (Project project : projects) {
if (project.getPrefix().equals(product.getName())) {
//should be already sorted by string
validProjects.add(project);
}
}
for (Project validProject : validProjects) {
sb.append(" <a href='#PR-").append(validProject.getName()).append("'>").append(validProject.getSuffixToString()).append("</a>\n");
}
sb.append(" <p>")
.append("Found ").append(buildObjects.length)
.append(" successful builds and ").append(validProjects.size()).append(" relevant projects")
.append(" From those ").append(Integer.valueOf(buildObjects.length - fastdebugs)).append(" are normal builds.")
.append(" and ").append(fastdebugs).append(" are fastdebug builds.")
.append("</p>\n");
sb.append(" <p>")
.append("You can see all ").append(buildObjects.length)
.append(" builds details <a href='details.html?list=TODO1'> here</a>.")
.append(" You can jenkins build results in <a href='").append(getJenkinsUrl()).append("/search/?q=build-static-").append(product.getJenkinsMapping()).append("'> here</a>.")
.append(" You can jenkins TEST results in <a href='").append(getJenkinsUrl()).append("/search/?max=2000&q=").append(product.getJenkinsMapping()).append("'> here</a>.")
.append("</p>\n");
List<Build> usedBuilds = new ArrayList<>(buildObjects.length);
//now wee need to filetr only project's products
// the suffix is projected to *release*
//and is behind leading NUMBER. and have all "-" repalced by "."
//in addition we need to strip all keywords. usually usptream or usptream.fastdebug or static
//yes, oh crap
for (Project validProject : validProjects) {
List<Build> projectsBuilds = new ArrayList<>(buildObjects.length);
Map<String, Build> projectsFastdebugBuilds = new HashMap<>(buildObjects.length);
sb.append(" <a name='PR-").append(validProject.getName()).append("'/>");
sb.append(" <h3>").append(validProject.getSuffixToString()).append("</h3>\n");
for (Object object : buildObjects) {
//also we need to remove all fastdebug products and ony offer them together with normal of same VRA
Build built = (Build) object;
String cleanedSuffix = built.getRelease();
cleanedSuffix = cleanedSuffix.replaceAll(".upstream.*", "");
cleanedSuffix = cleanedSuffix.replaceAll(".static.*", "");
String suffixCandidate = "";
if (cleanedSuffix.contains(".")) {
suffixCandidate = cleanedSuffix.substring(cleanedSuffix.indexOf(".") + 1);
}
String relaseLikeSuffix = validProject.getSuffix().replaceAll("-", ".");
if (suffixCandidate.equals(relaseLikeSuffix)) {
usedBuilds.add(built);
if (built.getRelease().contains("fastdebug")) {
projectsFastdebugBuilds.put(built.getNvr().replaceAll(".fastdebug", ""), built);
} else {
projectsBuilds.add(built);
}
}
}
sb.append("<blockquote>");
if (projectsBuilds.isEmpty()) {
sb.append(" <p>").append("Sorry, no successful build matches this project. You may check all builds of this product.").append("</p><br/>\n");
} else {
Build b = projectsBuilds.get(projectsBuilds.size() - 1);
sb.append(" <b>").append(b.getNvr()).append("</b><br/>\n");
sb.append(" <small>").append(b.getCompletionTime()).append("</small><br/>\n");
sb.append(offerBuild(dwnld.toExternalForm(), b));
Build bb = projectsFastdebugBuilds.get(b.getNvr());
if (bb == null) {
sb.append(" <i>no fast debug build found</i><br/>\n");
} else {
sb.append(" <i>").append(bb.getNvr()).append("</i><br/>\n");
sb.append(" <i><small>").append(bb.getCompletionTime()).append("</small></i><br/>\n");
sb.append("<small>\n");
sb.append(offerBuild(dwnld.toExternalForm(), bb));
sb.append("</small><br/>\n");
}
sb.append(" <p>")
.append("You can see all ").append(projectsBuilds.size())
.append(" builds details (and ").append(projectsFastdebugBuilds.size()).append(" fast builds) <a href='details.html?list=TODO2'> here</a>.")
.append("</p>\n");
}
sb.append("</blockquote>");
}
if (usedBuilds.size() != buildObjects.length) {
List<Build> unUsedBuilds = new ArrayList<>(-usedBuilds.size() + buildObjects.length);
for (Object bo : buildObjects) {
if (usedBuilds.contains((Build) bo)) {
} else {
unUsedBuilds.add((Build) bo);
}
}
sb.append(" <h3>There are unsorted ").append(unUsedBuilds.size()).append(" builds: </h3>\n");
sb.append(" <p>")
.append("You can see them <a href='details.html?list=TODO3'> here</a>.")
.append("</p>\n");
}
sb.append("</blockquote>");
}
return sb;
}
}
public static class DetailsHtmlHandler implements HttpHandler {
private final URL xmlrpc;
private final URL dwnld;
private final List<Project> projects;
private final List<Product> products;
private final int port;
private DetailsHtmlHandler(URL xmlrpcurl, URL download, List<Project> projects, List<Product> builds, int port) {
xmlrpc = xmlrpcurl;
dwnld = download;
this.projects = projects;
this.products = builds;
this.port = port;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
RequestRunner rr = new RequestRunner(exchange);
new Thread(rr).start();
}
private class RequestRunner implements Runnable {
private final HttpExchange t;
public RequestRunner(HttpExchange t) {
this.t = t;
}
@Override
public void run() {
try {
runImpl();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void runImpl() throws IOException {
String requestedFile = t.getRequestURI().getPath();
System.out.println(new Date().toString() + "attempting: " + requestedFile);
generateIndex(t);
}
}
private void generateIndex(HttpExchange t) throws IOException {
System.out.println("Regenerating index!");
StringBuilder sb = new StringBuilder("todo: show detaisl of all builds given as &list= parameter");
String result = sb.toString();
long size = result.length(); //yahnot perfect, ets assuemno one will use this on chinese chars
t.sendResponseHeaders(200, size);
try (OutputStream os = t.getResponseBody()) {
os.write(result.getBytes());
}
}
}
public static String offerBuild(String baseUrl, Build build) {
List<RPM> rpms = new ArrayList<>(build.getRpms());
Collections.sort(rpms, new Comparator<RPM>() {
@Override
public int compare(RPM o1, RPM o2) {
return o1.getArch().compareTo(o2.getArch());
}
});
String sourceSnapshot = "";
StringBuilder r = new StringBuilder();
r.append("<blockquote>");
for (RPM rpm : rpms) {
if (!baseUrl.endsWith("/")) {
baseUrl = baseUrl + "/";
}
String mainUrl = baseUrl + rpm.getName() + "/" + rpm.getVersion() + "/" + rpm.getRelease();
String archedUrl = mainUrl + "/" + rpm.getArch();
String logsUrl = mainUrl + "/data/logs/" + rpm.getArch();
String filename = rpm.getFilename("tarxz");
String fileUrl = archedUrl + "/" + filename;
if (rpm.getArch().equals("src")) {
sourceSnapshot = "sources: <a href='" + fileUrl + "'>src snapshot</a> <a href='" + logsUrl + "'>hg incomming logs</a><br/>";
} else {
r.append("<b>").append(rpm.getArch()).append("</b>: \n");
r.append("<a href='")
.append(fileUrl)
.append("'>")
.append(filename)
.append("</a> <a href='")
.append(logsUrl)
.append("'>build logs</a><br/>");
}
}
r.append(sourceSnapshot);
r.append("</blockquote>");
return r.toString();
}
}
|
Generating of whole build info moved to separate method
|
src/main/java/org/fakekoji/http/PreviewFakeKoji.java
|
Generating of whole build info moved to separate method
|
<ide><path>rc/main/java/org/fakekoji/http/PreviewFakeKoji.java
<ide> "http://hydra.brq.redhat.com/RPC2/",
<ide> "http://hydra.brq.redhat.com/",
<ide> "/mnt/raid1/upstream-repos",
<del> "/mnt/raid1/local-builds",
<del> //"1919"
<add> "/mnt/raid1/local-builds",
<add> "1919"
<ide> };
<ide> if (args.length < 3) {
<ide> System.out.println("Mandatory 4 params: full koji xmlrpc url and koji download url and cloned forests homes and projects homes");
<ide> }
<ide>
<ide> /*
<del> VERY infrastrucutre specific
<add> VERY infrastrucutre specific
<ide> */
<ide> public String getJenkinsMapping() {
<ide> if (getName().equals("java-1.8.0-openjdk")) {
<ide> }
<ide> }
<ide> }
<del> sb.append("<blockquote>");
<del> if (projectsBuilds.isEmpty()) {
<del> sb.append(" <p>").append("Sorry, no successful build matches this project. You may check all builds of this product.").append("</p><br/>\n");
<del> } else {
<del> Build b = projectsBuilds.get(projectsBuilds.size() - 1);
<del> sb.append(" <b>").append(b.getNvr()).append("</b><br/>\n");
<del> sb.append(" <small>").append(b.getCompletionTime()).append("</small><br/>\n");
<del> sb.append(offerBuild(dwnld.toExternalForm(), b));
<del> Build bb = projectsFastdebugBuilds.get(b.getNvr());
<del> if (bb == null) {
<del> sb.append(" <i>no fast debug build found</i><br/>\n");
<del> } else {
<del> sb.append(" <i>").append(bb.getNvr()).append("</i><br/>\n");
<del> sb.append(" <i><small>").append(bb.getCompletionTime()).append("</small></i><br/>\n");
<del> sb.append("<small>\n");
<del> sb.append(offerBuild(dwnld.toExternalForm(), bb));
<del> sb.append("</small><br/>\n");
<del> }
<del> sb.append(" <p>")
<del> .append("You can see all ").append(projectsBuilds.size())
<del> .append(" builds details (and ").append(projectsFastdebugBuilds.size()).append(" fast builds) <a href='details.html?list=TODO2'> here</a>.")
<del> .append("</p>\n");
<add> Build build = null;
<add> if (!projectsBuilds.isEmpty()) {
<add> build = projectsBuilds.get(projectsBuilds.size() - 1);
<ide> }
<del> sb.append("</blockquote>");
<add> offerBuild(build, projectsFastdebugBuilds, sb, projectsBuilds, dwnld);
<add>
<ide> }
<ide> if (usedBuilds.size() != buildObjects.length) {
<ide> List<Build> unUsedBuilds = new ArrayList<>(-usedBuilds.size() + buildObjects.length);
<ide> }
<ide> }
<ide>
<del> public static String offerBuild(String baseUrl, Build build) {
<add> private static void offerBuild(Build build, Map<String, Build> projectsFastdebugBuilds, StringBuilder sb, List<Build> projectsBuilds, URL dwnld) {
<add> sb.append("<blockquote>");
<add> if (build == null) {
<add> sb.append(" <p>").append("Sorry, no successful build matches this project. You may check all builds of this product.").append("</p><br/>\n");
<add> } else {
<add> sb.append(" <b>").append(build.getNvr()).append("</b><br/>\n");
<add> sb.append(" <small>").append(build.getCompletionTime()).append("</small><br/>\n");
<add> sb.append(offerDownloads(dwnld.toExternalForm(), build));
<add> Build bb = projectsFastdebugBuilds.get(build.getNvr());
<add> if (bb == null) {
<add> sb.append(" <i>no fast debug build found</i><br/>\n");
<add> } else {
<add> sb.append(" <i>").append(bb.getNvr()).append("</i><br/>\n");
<add> sb.append(" <i><small>").append(bb.getCompletionTime()).append("</small></i><br/>\n");
<add> sb.append("<small>\n");
<add> sb.append(offerDownloads(dwnld.toExternalForm(), bb));
<add> sb.append("</small><br/>\n");
<add> }
<add> if (projectsBuilds != null) {
<add> sb.append(" <p>")
<add> .append("You can see all ").append(projectsBuilds.size())
<add> .append(" builds details (and ").append(projectsFastdebugBuilds.size()).append(" fast builds) <a href='details.html?list=TODO2'> here</a>.")
<add> .append("</p>\n");
<add> }
<add> }
<add> sb.append("</blockquote>");
<add> }
<add>
<add> public static String offerDownloads(String baseUrl, Build build) {
<ide> List<RPM> rpms = new ArrayList<>(build.getRpms());
<ide> Collections.sort(rpms, new Comparator<RPM>() {
<ide> @Override
|
|
Java
|
bsd-3-clause
|
bcb483fe31d272b962db9c32709af9e839b0d8a3
| 0 |
krishagni/openspecimen,krishagni/openspecimen,asamgir/openspecimen,NCIP/catissue-core,NCIP/catissue-core,NCIP/catissue-core,asamgir/openspecimen,krishagni/openspecimen,asamgir/openspecimen
|
/**
* <p>Title: TransferEventParametersAction Class>
* <p>Description: This class initializes the fields in the TransferEventParameters Add/Edit webpage.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Mandar Deshmukh
* @version 1.00
* Created on Aug 05, 2005
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import edu.wustl.catissuecore.actionForm.TransferEventParametersForm;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.StorageContainerBizLogic;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.util.logger.Logger;
/**
* @author mandar_deshmukh
* This class initializes the fields in the TransferEventParameters Add/Edit webpage.
*/
public class TransferEventParametersAction extends SpecimenEventParametersAction
{
protected void setRequestParameters(HttpServletRequest request) throws Exception
{
TransferEventParametersForm form = (TransferEventParametersForm) request
.getAttribute("transferEventParametersForm");
String operation = request.getParameter(Constants.OPERATION);
StorageContainerBizLogic scbizLogic = (StorageContainerBizLogic) BizLogicFactory
.getInstance().getBizLogic(Constants.STORAGE_CONTAINER_FORM_ID);
Map containerMap = new TreeMap();
Vector initialValues = null;
//
if (operation.equals(Constants.ADD))
{
IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(
Constants.DEFAULT_BIZ_LOGIC);
String identifier = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (identifier == null)
identifier = (String) request.getParameter(Constants.SPECIMEN_ID);
Logger.out.debug("\t\t*******************************SpecimenID : " + identifier);
List specimenList = bizLogic.retrieve(Specimen.class.getName(),
Constants.SYSTEM_IDENTIFIER, identifier);
// ---- chetan 15-06-06 ----
// -------------------------
if (specimenList != null && specimenList.size() != 0)
{
Specimen specimen = (Specimen) specimenList.get(0);
String positionOne = null;
String positionTwo = null;
String storageContainerID = null;
String fromPositionData = "virtual Location";
if (specimen.getStorageContainer() != null)
{
positionOne = specimen.getPositionDimensionOne().toString();
positionTwo = specimen.getPositionDimensionTwo().toString();
StorageContainer container = specimen.getStorageContainer();
storageContainerID = container.getId().toString();
fromPositionData = container.getStorageType().getName() + " : "
+ storageContainerID + " Pos(" + positionOne + "," + positionTwo + ")";
}
//The fromPositionData(storageContainer Info) of specimen of this event.
request.setAttribute(Constants.FROM_POSITION_DATA, fromPositionData);
//POSITION 1
request.setAttribute(Constants.POS_ONE, positionOne);
//POSITION 2
request.setAttribute(Constants.POS_TWO, positionTwo);
//storagecontainer info
request.setAttribute(Constants.STORAGE_CONTAINER_ID, storageContainerID);
Logger.out.info("COllection Protocol Id :"
+ specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration()
.getCollectionProtocol().getId().longValue());
Logger.out.info("Spcimen Class:" + specimen.getClassName());
containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen(specimen
.getSpecimenCollectionGroup().getCollectionProtocolRegistration()
.getCollectionProtocol().getId().longValue(), specimen.getClassName(),0);
initialValues = checkForInitialValues(containerMap);
}
} // operation=add
else
{
Integer id = new Integer(form.getStorageContainer());
String parentContainerName = "";
String valueField1 = "id";
List list = scbizLogic.retrieve(StorageContainer.class.getName(), valueField1,
new Long(form.getStorageContainer()));
if (!list.isEmpty())
{
StorageContainer container = (StorageContainer) list.get(0);
parentContainerName = container.getName();
}
Integer pos1 = new Integer(form.getPositionDimensionOne());
Integer pos2 = new Integer(form.getPositionDimensionTwo());
List pos2List = new ArrayList();
pos2List.add(new NameValueBean(pos2, pos2));
Map pos1Map = new TreeMap();
pos1Map.put(new NameValueBean(pos1, pos1), pos2List);
containerMap.put(new NameValueBean(parentContainerName, id), pos1Map);
String[] startingPoints = new String[]{"-1", "-1", "-1"};
if (form.getStorageContainer() != null && !form.getStorageContainer().equals("-1"))
{
startingPoints[0] = form.getStorageContainer();
}
if (form.getPositionDimensionOne() != null
&& !form.getPositionDimensionOne().equals("-1"))
{
startingPoints[1] = form.getPositionDimensionOne();
}
if (form.getPositionDimensionTwo() != null
&& !form.getPositionDimensionTwo().equals("-1"))
{
startingPoints[2] = form.getPositionDimensionTwo();
}
initialValues = new Vector();
Logger.out.info("Starting points[0]" + startingPoints[0]);
Logger.out.info("Starting points[1]" + startingPoints[1]);
Logger.out.info("Starting points[2]" + startingPoints[2]);
initialValues.add(startingPoints);
}
request.setAttribute("initValues", initialValues);
request.setAttribute(Constants.AVAILABLE_CONTAINER_MAP, containerMap);
}
Vector checkForInitialValues(Map containerMap)
{
Vector initialValues = null;
if (containerMap.size() > 0)
{
String[] startingPoints = new String[3];
Set keySet = containerMap.keySet();
Iterator itr = keySet.iterator();
NameValueBean nvb = (NameValueBean) itr.next();
startingPoints[0] = nvb.getValue();
Map map1 = (Map) containerMap.get(nvb);
keySet = map1.keySet();
itr = keySet.iterator();
nvb = (NameValueBean) itr.next();
startingPoints[1] = nvb.getValue();
List list = (List) map1.get(nvb);
nvb = (NameValueBean) list.get(0);
startingPoints[2] = nvb.getValue();
Logger.out.info("Starting points[0]" + startingPoints[0]);
Logger.out.info("Starting points[1]" + startingPoints[1]);
Logger.out.info("Starting points[2]" + startingPoints[2]);
initialValues = new Vector();
initialValues.add(startingPoints);
}
return initialValues;
//request.setAttribute("initValues", initialValues);
}
}
|
WEB-INF/src/edu/wustl/catissuecore/action/TransferEventParametersAction.java
|
/**
* <p>Title: TransferEventParametersAction Class>
* <p>Description: This class initializes the fields in the TransferEventParameters Add/Edit webpage.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Mandar Deshmukh
* @version 1.00
* Created on Aug 05, 2005
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import edu.wustl.catissuecore.actionForm.NewSpecimenForm;
import edu.wustl.catissuecore.actionForm.TransferEventParametersForm;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.StorageContainerBizLogic;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.util.logger.Logger;
/**
* @author mandar_deshmukh
* This class initializes the fields in the TransferEventParameters Add/Edit webpage.
*/
public class TransferEventParametersAction extends SpecimenEventParametersAction
{
protected void setRequestParameters(HttpServletRequest request) throws Exception
{
TransferEventParametersForm form = (TransferEventParametersForm) request
.getAttribute("transferEventParametersForm");
String operation = request.getParameter(Constants.OPERATION);
StorageContainerBizLogic scbizLogic = (StorageContainerBizLogic) BizLogicFactory
.getInstance().getBizLogic(Constants.STORAGE_CONTAINER_FORM_ID);
Map containerMap = new TreeMap();
Vector initialValues = null;
//
if (operation.equals(Constants.ADD))
{
IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(
Constants.DEFAULT_BIZ_LOGIC);
String identifier = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (identifier == null)
identifier = (String) request.getParameter(Constants.SPECIMEN_ID);
Logger.out.debug("\t\t*******************************SpecimenID : " + identifier);
List specimenList = bizLogic.retrieve(Specimen.class.getName(),
Constants.SYSTEM_IDENTIFIER, identifier);
// ---- chetan 15-06-06 ----
// -------------------------
if (specimenList != null && specimenList.size() != 0)
{
Specimen specimen = (Specimen) specimenList.get(0);
String positionOne = null;
String positionTwo = null;
String storageContainerID = null;
String fromPositionData = "virtual Location";
if (specimen.getStorageContainer() != null)
{
positionOne = specimen.getPositionDimensionOne().toString();
positionTwo = specimen.getPositionDimensionTwo().toString();
StorageContainer container = specimen.getStorageContainer();
storageContainerID = container.getId().toString();
fromPositionData = container.getStorageType().getName() + " : "
+ storageContainerID + " Pos(" + positionOne + "," + positionTwo + ")";
}
//The fromPositionData(storageContainer Info) of specimen of this event.
request.setAttribute(Constants.FROM_POSITION_DATA, fromPositionData);
//POSITION 1
request.setAttribute(Constants.POS_ONE, positionOne);
//POSITION 2
request.setAttribute(Constants.POS_TWO, positionTwo);
//storagecontainer info
request.setAttribute(Constants.STORAGE_CONTAINER_ID, storageContainerID);
Logger.out.info("COllection Protocol Id :"
+ specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration()
.getCollectionProtocol().getId().longValue());
Logger.out.info("Spcimen Class:" + specimen.getClassName());
containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen(specimen
.getSpecimenCollectionGroup().getCollectionProtocolRegistration()
.getCollectionProtocol().getId().longValue(), specimen.getClassName());
initialValues = checkForInitialValues(containerMap);
}
} // operation=add
else
{
Integer id = new Integer(form.getStorageContainer());
String parentContainerName = "";
String valueField1 = "id";
List list = scbizLogic.retrieve(StorageContainer.class.getName(), valueField1,
new Long(form.getStorageContainer()));
if (!list.isEmpty())
{
StorageContainer container = (StorageContainer) list.get(0);
parentContainerName = container.getName();
}
Integer pos1 = new Integer(form.getPositionDimensionOne());
Integer pos2 = new Integer(form.getPositionDimensionTwo());
List pos2List = new ArrayList();
pos2List.add(new NameValueBean(pos2, pos2));
Map pos1Map = new TreeMap();
pos1Map.put(new NameValueBean(pos1, pos1), pos2List);
containerMap.put(new NameValueBean(parentContainerName, id), pos1Map);
String[] startingPoints = new String[]{"-1", "-1", "-1"};
if (form.getStorageContainer() != null && !form.getStorageContainer().equals("-1"))
{
startingPoints[0] = form.getStorageContainer();
}
if (form.getPositionDimensionOne() != null
&& !form.getPositionDimensionOne().equals("-1"))
{
startingPoints[1] = form.getPositionDimensionOne();
}
if (form.getPositionDimensionTwo() != null
&& !form.getPositionDimensionTwo().equals("-1"))
{
startingPoints[2] = form.getPositionDimensionTwo();
}
initialValues = new Vector();
Logger.out.info("Starting points[0]" + startingPoints[0]);
Logger.out.info("Starting points[1]" + startingPoints[1]);
Logger.out.info("Starting points[2]" + startingPoints[2]);
initialValues.add(startingPoints);
}
request.setAttribute("initValues", initialValues);
request.setAttribute(Constants.AVAILABLE_CONTAINER_MAP, containerMap);
}
Vector checkForInitialValues(Map containerMap)
{
Vector initialValues = null;
if (containerMap.size() > 0)
{
String[] startingPoints = new String[3];
Set keySet = containerMap.keySet();
Iterator itr = keySet.iterator();
NameValueBean nvb = (NameValueBean) itr.next();
startingPoints[0] = nvb.getValue();
Map map1 = (Map) containerMap.get(nvb);
keySet = map1.keySet();
itr = keySet.iterator();
nvb = (NameValueBean) itr.next();
startingPoints[1] = nvb.getValue();
List list = (List) map1.get(nvb);
nvb = (NameValueBean) list.get(0);
startingPoints[2] = nvb.getValue();
Logger.out.info("Starting points[0]" + startingPoints[0]);
Logger.out.info("Starting points[1]" + startingPoints[1]);
Logger.out.info("Starting points[2]" + startingPoints[2]);
initialValues = new Vector();
initialValues.add(startingPoints);
}
return initialValues;
//request.setAttribute("initValues", initialValues);
}
}
|
added parameter while calling for getAllocatedContaienrMapForSpecimen
SVN-Revision: 4160
|
WEB-INF/src/edu/wustl/catissuecore/action/TransferEventParametersAction.java
|
added parameter while calling for getAllocatedContaienrMapForSpecimen
|
<ide><path>EB-INF/src/edu/wustl/catissuecore/action/TransferEventParametersAction.java
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<del>import edu.wustl.catissuecore.actionForm.NewSpecimenForm;
<ide> import edu.wustl.catissuecore.actionForm.TransferEventParametersForm;
<ide> import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
<ide> import edu.wustl.catissuecore.bizlogic.StorageContainerBizLogic;
<ide> Logger.out.info("Spcimen Class:" + specimen.getClassName());
<ide> containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen(specimen
<ide> .getSpecimenCollectionGroup().getCollectionProtocolRegistration()
<del> .getCollectionProtocol().getId().longValue(), specimen.getClassName());
<add> .getCollectionProtocol().getId().longValue(), specimen.getClassName(),0);
<ide> initialValues = checkForInitialValues(containerMap);
<ide>
<ide> }
|
|
Java
|
lgpl-2.1
|
error: pathspec 'src/ch/unizh/ini/jaer/projects/virtualslotcar/ThrottleInterface.java' did not match any file(s) known to git
|
65d888f3797de56a0532138a9406f3efd787c198
| 1 |
viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.virtualslotcar;
/**
* The interface to the throttle of the slot car; either of physical slot car controller or virtual slot car.
* @author tobi
*/
public interface ThrottleInterface {
/**
* @return the last speed that was set.
*/
float getThrottle ();
/**
* Set the speed and returns success.
* @param speed the speed to set.
* @return true if interface was open.
*/
boolean setThrottle (float speed);
}
|
src/ch/unizh/ini/jaer/projects/virtualslotcar/ThrottleInterface.java
|
added throttle interface
git-svn-id: e3d3b427d532171a6bd7557d8a4952a393b554a2@2067 b7f4320f-462c-0410-a916-d9f35bb82d52
|
src/ch/unizh/ini/jaer/projects/virtualslotcar/ThrottleInterface.java
|
added throttle interface
|
<ide><path>rc/ch/unizh/ini/jaer/projects/virtualslotcar/ThrottleInterface.java
<add>/*
<add> * To change this template, choose Tools | Templates
<add> * and open the template in the editor.
<add> */
<add>
<add>package ch.unizh.ini.jaer.projects.virtualslotcar;
<add>
<add>/**
<add> * The interface to the throttle of the slot car; either of physical slot car controller or virtual slot car.
<add> * @author tobi
<add> */
<add>public interface ThrottleInterface {
<add>
<add> /**
<add> * @return the last speed that was set.
<add> */
<add> float getThrottle ();
<add>
<add> /**
<add> * Set the speed and returns success.
<add> * @param speed the speed to set.
<add> * @return true if interface was open.
<add> */
<add> boolean setThrottle (float speed);
<add>
<add>}
|
|
JavaScript
|
apache-2.0
|
c84bf612411b91e1a272e2ab5feb81dfeb5f65b1
| 0 |
palominolabs/senchatouch-parse-sdk
|
/**
* Copyright 2013-2014 Palomino Labs, 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.
*/
/**
* A singleton for uploading files to Parse.
*
* @author Hayden Gomes
*/
Ext.define('Ext.ux.parse.util.File', {
singleton: true,
requires: [
'Ext.ux.parse.ParseAjax'
],
FILE_URL_PATH: '/files/',
/**
*
* @param {File} file a Javascript File object to be uploaded
* @param {Object} [options] Options including all standards supported by Ext.data.Connection.request
*/
uploadFile: function (file, options) {
if (file && file.name && file.type) {
var requestOptions = {
url: this.FILE_URL_PATH + file.name,
headers: {
'Content-Type': file.type
},
method: 'POST'
};
if (file.slice && typeof file.slice === 'function') {
requestOptions.binaryData = file.slice();
} else if (file.webkitSlice && typeof file.webkitSlice === 'function') {
requestOptions.binaryData = file.webkitSlice();
} else if (options.failure) {
options.failure("Unable to splice blob from file", options);
return;
}
Ext.applyIf(requestOptions, options);
Ext.ux.parse.ParseAjax.request(requestOptions);
} else {
if (options.failure) {
options.failure("ParseLibError: Unable to parse file", options);
}
}
},
generateImageField: function (imageName, imageUrl) {
return {
name: imageName,
url: imageUrl,
__type: 'File'
}
}
});
|
util/File.js
|
/**
* Copyright 2013-2014 Palomino Labs, 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.
*/
/**
* A singleton for uploading files to Parse.
*
* @author Hayden Gomes
*/
Ext.define('Ext.ux.parse.util.File', {
singleton: true,
requires: [
'Ext.ux.parse.ParseAjax'
],
FILE_URL_PATH: '/files/',
/**
*
* @param {File} file a Javascript File object to be uploaded
* @param {Object} [options] Options including all standards supported by Ext.data.Connection.request
*/
uploadFile: function (file, options) {
if (file && file.name && file.type) {
var requestOptions = {
url: this.FILE_URL_PATH + file.name,
headers: {
'Content-Type': file.type
},
method: 'POST',
binaryData: file.slice()
};
Ext.applyIf(requestOptions, options);
Ext.ux.parse.ParseAjax.request(requestOptions);
} else {
if (options.failure) {
options.failure("ParseLibError: Unable to parse file", options);
}
}
},
generateImageField: function (imageName, imageUrl) {
return {
name: imageName,
url: imageUrl,
__type: 'File'
}
}
});
|
Add support for alternative file splicing function (iOS 6 support)
|
util/File.js
|
Add support for alternative file splicing function (iOS 6 support)
|
<ide><path>til/File.js
<ide> headers: {
<ide> 'Content-Type': file.type
<ide> },
<del> method: 'POST',
<del> binaryData: file.slice()
<add> method: 'POST'
<ide> };
<add>
<add> if (file.slice && typeof file.slice === 'function') {
<add> requestOptions.binaryData = file.slice();
<add> } else if (file.webkitSlice && typeof file.webkitSlice === 'function') {
<add> requestOptions.binaryData = file.webkitSlice();
<add> } else if (options.failure) {
<add> options.failure("Unable to splice blob from file", options);
<add> return;
<add> }
<ide>
<ide> Ext.applyIf(requestOptions, options);
<ide> Ext.ux.parse.ParseAjax.request(requestOptions);
|
|
Java
|
apache-2.0
|
71953aee21e10ee19ccafab19d4ba3344f5f1435
| 0 |
manl1100/zxing,BraveAction/zxing,rustemferreira/zxing-projectx,kharohiy/zxing,wangjun/zxing,mecury/zxing,rustemferreira/zxing-projectx,ouyangkongtong/zxing,ZhernakovMikhail/zxing,917386389/zxing,Kevinsu917/zxing,irfanah/zxing,joni1408/zxing,JerryChin/zxing,mig1098/zxing,ren545457803/zxing,sunil1989/zxing,Peter32/zxing,hgl888/zxing,peterdocter/zxing,saif-hmk/zxing,Akylas/zxing,whycode/zxing,reidwooten99/zxing,nickperez1285/zxing,zootsuitbrian/zxing,huangzl233/zxing,juoni/zxing,bestwpw/zxing,easycold/zxing,mecury/zxing,Solvoj/zxing,Kevinsu917/zxing,l-dobrev/zxing,whycode/zxing,wirthandrel/zxing,ssakitha/QR-Code-Reader,eddyb/zxing,ale13jo/zxing,krishnanMurali/zxing,layeka/zxing,WB-ZZ-TEAM/zxing,praveen062/zxing,shwethamallya89/zxing,allenmo/zxing,zilaiyedaren/zxing,YLBFDEV/zxing,keqingyuan/zxing,fhchina/zxing,GeorgeMe/zxing,sitexa/zxing,sitexa/zxing,lvbaosong/zxing,Matrix44/zxing,TestSmirk/zxing,wangdoubleyan/zxing,menglifei/zxing,iris-iriswang/zxing,layeka/zxing,huopochuan/zxing,zootsuitbrian/zxing,tks-dp/zxing,mayfourth/zxing,RatanPaul/zxing,krishnanMurali/zxing,irwinai/zxing,yuanhuihui/zxing,peterdocter/zxing,Solvoj/zxing,danielZhang0601/zxing,MonkeyZZZZ/Zxing,zhangyihao/zxing,micwallace/webscanner,zonamovil/zxing,cnbin/zxing,ikenneth/zxing,HiWong/zxing,ouyangkongtong/zxing,huangzl233/zxing,Luise-li/zxing,sysujzh/zxing,wirthandrel/zxing,qianchenglenger/zxing,DavidLDawes/zxing,ssakitha/sakisolutions,10045125/zxing,WB-ZZ-TEAM/zxing,micwallace/webscanner,Akylas/zxing,ctoliver/zxing,wanjingyan001/zxing,ChristingKim/zxing,shixingxing/zxing,eight-pack-abdominals/ZXing,mayfourth/zxing,cnbin/zxing,0111001101111010/zxing,reidwooten99/zxing,zxing/zxing,FloatingGuy/zxing,qianchenglenger/zxing,sunil1989/zxing,graug/zxing,ctoliver/zxing,lijian17/zxing,zilaiyedaren/zxing,liboLiao/zxing,projectocolibri/zxing,east119/zxing,Luise-li/zxing,peterdocter/zxing,BraveAction/zxing,lijian17/zxing,roudunyy/zxing,wangxd1213/zxing,juoni/zxing,irwinai/zxing,1yvT0s/zxing,bittorrent/zxing,TestSmirk/zxing,OnecloudVideo/zxing,manl1100/zxing,daverix/zxing,1yvT0s/zxing,kyosho81/zxing,daverix/zxing,Kabele/zxing,gank0326/zxing,projectocolibri/zxing,hgl888/zxing,zjcscut/zxing,menglifei/zxing,fhchina/zxing,MonkeyZZZZ/Zxing,Matrix44/zxing,eddyb/zxing,DONIKAN/zxing,ssakitha/sakisolutions,ren545457803/zxing,todotobe1/zxing,DavidLDawes/zxing,cncomer/zxing,angrilove/zxing,HiWong/zxing,lvbaosong/zxing,kailIII/zxing,Yi-Kun/zxing,kharohiy/zxing,GeorgeMe/zxing,GeekHades/zxing,andyao/zxing,GeekHades/zxing,YongHuiLuo/zxing,yuanhuihui/zxing,huopochuan/zxing,daverix/zxing,roadrunner1987/zxing,liboLiao/zxing,geeklain/zxing,bestwpw/zxing,peterdocter/zxing,ptrnov/zxing,geeklain/zxing,befairyliu/zxing,1shawn/zxing,Akylas/zxing,zzhui1988/zxing,ale13jo/zxing,nickperez1285/zxing,joni1408/zxing,JerryChin/zxing,andyshao/zxing,Matrix44/zxing,keqingyuan/zxing,JasOXIII/zxing,bittorrent/zxing,ptrnov/zxing,meixililu/zxing,Fedhaier/zxing,Akylas/zxing,liuchaoya/zxing,east119/zxing,jianwoo/zxing,catalindavid/zxing,huihui4045/zxing,YongHuiLuo/zxing,YuYongzhi/zxing,ChanJLee/zxing,RatanPaul/zxing,ikenneth/zxing,shixingxing/zxing,huihui4045/zxing,praveen062/zxing,huangsongyan/zxing,Akylas/zxing,geeklain/zxing,loaf/zxing,FloatingGuy/zxing,SriramRamesh/zxing,erbear/zxing,ChristingKim/zxing,zootsuitbrian/zxing,zjcscut/zxing,liuchaoya/zxing,Fedhaier/zxing,tanelihuuskonen/zxing,ForeverLucky/zxing,jianwoo/zxing,cncomer/zxing,slayerlp/zxing,JasOXIII/zxing,0111001101111010/zxing,wangjun/zxing,zonamovil/zxing,917386389/zxing,t123yh/zxing,Akylas/zxing,ChanJLee/zxing,eight-pack-abdominals/ZXing,finch0219/zxing,roudunyy/zxing,catalindavid/zxing,erbear/zxing,qingsong-xu/zxing,wanjingyan001/zxing,allenmo/zxing,Matrix44/zxing,peterdocter/zxing,irfanah/zxing,zhangyihao/zxing,peterdocter/zxing,easycold/zxing,graug/zxing,shwethamallya89/zxing,daverix/zxing,kyosho81/zxing,0111001101111010/zxing,loaf/zxing,wangdoubleyan/zxing,freakynit/zxing,zootsuitbrian/zxing,zootsuitbrian/zxing,0111001101111010/zxing,Peter32/zxing,angrilove/zxing,tanelihuuskonen/zxing,danielZhang0601/zxing,sysujzh/zxing,iris-iriswang/zxing,ssakitha/QR-Code-Reader,peterdocter/zxing,ZhernakovMikhail/zxing,ForeverLucky/zxing,YuYongzhi/zxing,kailIII/zxing,Kabele/zxing,befairyliu/zxing,daverix/zxing,saif-hmk/zxing,l-dobrev/zxing,1shawn/zxing,micwallace/webscanner,YLBFDEV/zxing,zootsuitbrian/zxing,freakynit/zxing,hiagodotme/zxing,qingsong-xu/zxing,Akylas/zxing,peterdocter/zxing,slayerlp/zxing,meixililu/zxing,andyao/zxing,zootsuitbrian/zxing,SriramRamesh/zxing,todotobe1/zxing,zzhui1988/zxing,tks-dp/zxing,mig1098/zxing,DONIKAN/zxing,andyshao/zxing,zxing/zxing,finch0219/zxing,huangsongyan/zxing,Yi-Kun/zxing,OnecloudVideo/zxing,roadrunner1987/zxing,hiagodotme/zxing,t123yh/zxing,wangxd1213/zxing
|
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.encode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.R;
import com.google.zxing.client.result.AddressBookParsedResult;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.ResultParser;
import com.google.zxing.common.BitMatrix;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
/**
* This class does the work of decoding the user's request and extracting all the data
* to be encoded in a barcode.
*
* @author [email protected] (Daniel Switkin)
*/
final class QRCodeEncoder {
private static final String TAG = QRCodeEncoder.class.getSimpleName();
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
private final Activity activity;
private String contents;
private String displayContents;
private String title;
private BarcodeFormat format;
private final int dimension;
QRCodeEncoder(Activity activity, Intent intent, int dimension) {
this.activity = activity;
if (intent == null) {
throw new IllegalArgumentException("No valid data to encode.");
}
String action = intent.getAction();
if (action.equals(Intents.Encode.ACTION)) {
if (!encodeContentsFromZXingIntent(intent)) {
throw new IllegalArgumentException("No valid data to encode.");
}
} else if (action.equals(Intent.ACTION_SEND)) {
if (!encodeContentsFromShareIntent(intent)) {
throw new IllegalArgumentException("No valid data to encode.");
}
}
this.dimension = dimension;
}
public String getContents() {
return contents;
}
public String getDisplayContents() {
return displayContents;
}
public String getTitle() {
return title;
}
// It would be nice if the string encoding lived in the core ZXing library,
// but we use platform specific code like PhoneNumberUtils, so it can't.
private boolean encodeContentsFromZXingIntent(Intent intent) {
// Default to QR_CODE if no format given.
String formatString = intent.getStringExtra(Intents.Encode.FORMAT);
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
format = null;
}
if (format == null || BarcodeFormat.QR_CODE.equals(format)) {
String type = intent.getStringExtra(Intents.Encode.TYPE);
if (type == null || type.length() == 0) {
return false;
}
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(intent, type);
} else {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = activity.getString(R.string.contents_text);
}
}
return contents != null && contents.length() > 0;
}
// Handles send intents from multitude of Android applications
private boolean encodeContentsFromShareIntent(Intent intent) {
// Check if this is a plain text encoding, or contact
if (intent.hasExtra(Intent.EXTRA_TEXT)) {
return encodeContentsFromShareIntentPlainText(intent);
}
// Attempt default sharing.
return encodeContentsFromShareIntentDefault(intent);
}
private boolean encodeContentsFromShareIntentPlainText(Intent intent) {
// Notice: Google Maps shares both URL and details in one text, bummer!
contents = intent.getStringExtra(Intent.EXTRA_TEXT);
// We only support non-empty and non-blank texts.
// Trim text to avoid URL breaking.
if (contents == null) {
return false;
}
contents = contents.trim();
if (contents.length() == 0) {
return false;
}
// We only do QR code.
format = BarcodeFormat.QR_CODE;
if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
displayContents = intent.getStringExtra(Intent.EXTRA_SUBJECT);
} else if (intent.hasExtra(Intent.EXTRA_TITLE)) {
displayContents = intent.getStringExtra(Intent.EXTRA_TITLE);
} else {
displayContents = contents;
}
title = activity.getString(R.string.contents_text);
return true;
}
// Handles send intents from the Contacts app, retrieving a contact as a VCARD.
// Note: Does not work on HTC devices due to broken custom Contacts application.
private boolean encodeContentsFromShareIntentDefault(Intent intent) {
format = BarcodeFormat.QR_CODE;
try {
Uri uri = (Uri)intent.getExtras().getParcelable(Intent.EXTRA_STREAM);
InputStream stream = activity.getContentResolver().openInputStream(uri);
int length = stream.available();
if (length <= 0) {
Log.w(TAG, "Content stream is empty");
return false;
}
byte[] vcard = new byte[length];
int bytesRead = stream.read(vcard, 0, length);
if (bytesRead < length) {
Log.w(TAG, "Unable to fully read available bytes from content stream");
return false;
}
String vcardString = new String(vcard, 0, bytesRead, "UTF-8");
Log.d(TAG, "Encoding share intent content:");
Log.d(TAG, vcardString);
Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
ParsedResult parsedResult = ResultParser.parseResult(result);
if (!(parsedResult instanceof AddressBookParsedResult)) {
Log.d(TAG, "Result was not an address");
return false;
}
if (!encodeQRCodeContents((AddressBookParsedResult) parsedResult)) {
Log.d(TAG, "Unable to encode contents");
return false;
}
} catch (IOException e) {
Log.w(TAG, e);
return false;
} catch (NullPointerException e) {
Log.w(TAG, e);
// In case the uri was not found in the Intent.
return false;
}
return contents != null && contents.length() > 0;
}
private void encodeQRCodeContents(Intent intent, String type) {
if (type.equals(Contents.Type.TEXT)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = activity.getString(R.string.contents_text);
}
} else if (type.equals(Contents.Type.EMAIL)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = activity.getString(R.string.contents_email);
}
} else if (type.equals(Contents.Type.PHONE)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = activity.getString(R.string.contents_phone);
}
} else if (type.equals(Contents.Type.SMS)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = activity.getString(R.string.contents_sms);
}
} else if (type.equals(Contents.Type.CONTACT)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String name = trim(bundle.getString(Contacts.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
String address = trim(bundle.getString(Contacts.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
uniquePhones.add(phone);
}
}
for (String phone : uniquePhones) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
uniqueEmails.add(email);
}
}
for (String email : uniqueEmails) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = activity.getString(R.string.contents_contact);
} else {
contents = null;
displayContents = null;
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = activity.getString(R.string.contents_location);
}
}
}
}
private boolean encodeQRCodeContents(AddressBookParsedResult contact) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String[] names = contact.getNames();
if (names != null && names.length > 0) {
String name = trim(names[0]);
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
}
for (String address : trimAndDeduplicate(contact.getAddresses())) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
for (String phone : trimAndDeduplicate(contact.getPhoneNumbers())) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
for (String email : trimAndDeduplicate(contact.getEmails())) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
String url = trim(contact.getURL());
if (url != null) {
newContents.append("URL:").append(escapeMECARD(url)).append(';');
newDisplayContents.append('\n').append(url);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = activity.getString(R.string.contents_contact);
return true;
} else {
contents = null;
displayContents = null;
return false;
}
}
private static Iterable<String> trimAndDeduplicate(String[] values) {
if (values == null || values.length == 0) {
return Collections.emptySet();
}
Collection<String> uniqueValues = new HashSet<String>(values.length);
for (String value : values) {
uniqueValues.add(trim(value));
}
return uniqueValues;
}
Bitmap encodeAsBitmap() throws WriterException {
Hashtable<EncodeHintType,Object> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new Hashtable<EncodeHintType,Object>(2);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
private static String trim(String s) {
if (s == null) {
return null;
}
s = s.trim();
return s.length() == 0 ? null : s;
}
private static String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) {
return input;
}
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}
|
android/src/com/google/zxing/client/android/encode/QRCodeEncoder.java
|
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.encode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.android.Contents;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.R;
import com.google.zxing.client.result.AddressBookParsedResult;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.ResultParser;
import com.google.zxing.common.BitMatrix;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
/**
* This class does the work of decoding the user's request and extracting all the data
* to be encoded in a barcode.
*
* @author [email protected] (Daniel Switkin)
*/
final class QRCodeEncoder {
private static final String TAG = QRCodeEncoder.class.getSimpleName();
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
private final Activity activity;
private String contents;
private String displayContents;
private String title;
private BarcodeFormat format;
private final int dimension;
QRCodeEncoder(Activity activity, Intent intent, int dimension) {
this.activity = activity;
if (intent == null) {
throw new IllegalArgumentException("No valid data to encode.");
}
String action = intent.getAction();
if (action.equals(Intents.Encode.ACTION)) {
if (!encodeContentsFromZXingIntent(intent)) {
throw new IllegalArgumentException("No valid data to encode.");
}
} else if (action.equals(Intent.ACTION_SEND)) {
if (!encodeContentsFromShareIntent(intent)) {
throw new IllegalArgumentException("No valid data to encode.");
}
}
this.dimension = dimension;
}
public String getContents() {
return contents;
}
public String getDisplayContents() {
return displayContents;
}
public String getTitle() {
return title;
}
// It would be nice if the string encoding lived in the core ZXing library,
// but we use platform specific code like PhoneNumberUtils, so it can't.
private boolean encodeContentsFromZXingIntent(Intent intent) {
// Default to QR_CODE if no format given.
String formatString = intent.getStringExtra(Intents.Encode.FORMAT);
try {
format = BarcodeFormat.valueOf(formatString);
} catch (IllegalArgumentException iae) {
// Ignore it then
format = null;
}
if (format == null || BarcodeFormat.QR_CODE.equals(format)) {
String type = intent.getStringExtra(Intents.Encode.TYPE);
if (type == null || type.length() == 0) {
return false;
}
this.format = BarcodeFormat.QR_CODE;
encodeQRCodeContents(intent, type);
} else {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = activity.getString(R.string.contents_text);
}
}
return contents != null && contents.length() > 0;
}
// Handles send intents from multitude of Android applications
private boolean encodeContentsFromShareIntent(Intent intent) {
// Check if this is a plain text encoding, or contact
if (intent.hasExtra(Intent.EXTRA_TEXT)) {
return encodeContentsFromShareIntentPlainText(intent);
}
// Attempt default sharing.
return encodeContentsFromShareIntentDefault(intent);
}
private boolean encodeContentsFromShareIntentPlainText(Intent intent) {
// Notice: Google Maps shares both URL and details in one text, bummer!
contents = intent.getStringExtra(Intent.EXTRA_TEXT);
// We only support non-empty and non-blank texts.
// Trim text to avoid URL breaking.
if (contents == null) {
return false;
}
contents = contents.trim();
if (contents.length() == 0) {
return false;
}
// We only do QR code.
format = BarcodeFormat.QR_CODE;
if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
displayContents = intent.getStringExtra(Intent.EXTRA_SUBJECT);
} else if (intent.hasExtra(Intent.EXTRA_TITLE)) {
displayContents = intent.getStringExtra(Intent.EXTRA_TITLE);
} else {
displayContents = contents;
}
title = activity.getString(R.string.contents_text);
return true;
}
// Handles send intents from the Contacts app, retrieving a contact as a VCARD.
// Note: Does not work on HTC devices due to broken custom Contacts application.
private boolean encodeContentsFromShareIntentDefault(Intent intent) {
format = BarcodeFormat.QR_CODE;
try {
Uri uri = (Uri)intent.getExtras().getParcelable(Intent.EXTRA_STREAM);
InputStream stream = activity.getContentResolver().openInputStream(uri);
int length = stream.available();
if (length <= 0) {
Log.w(TAG, "Content stream is empty");
return false;
}
byte[] vcard = new byte[length];
int bytesRead = stream.read(vcard, 0, length);
if (bytesRead < length) {
Log.w(TAG, "Unable to fully read available bytes from content stream");
return false;
}
String vcardString = new String(vcard, 0, bytesRead, "UTF-8");
Log.d(TAG, "Encoding share intent content:");
Log.d(TAG, vcardString);
Result result = new Result(vcardString, vcard, null, BarcodeFormat.QR_CODE);
ParsedResult parsedResult = ResultParser.parseResult(result);
if (!(parsedResult instanceof AddressBookParsedResult)) {
Log.d(TAG, "Result was not an address");
return false;
}
if (!encodeQRCodeContents((AddressBookParsedResult) parsedResult)) {
Log.d(TAG, "Unable to encode contents");
return false;
}
} catch (IOException e) {
Log.w(TAG, e);
return false;
} catch (NullPointerException e) {
Log.w(TAG, e);
// In case the uri was not found in the Intent.
return false;
}
return contents != null && contents.length() > 0;
}
private void encodeQRCodeContents(Intent intent, String type) {
if (type.equals(Contents.Type.TEXT)) {
String data = intent.getStringExtra(Intents.Encode.DATA);
if (data != null && data.length() > 0) {
contents = data;
displayContents = data;
title = activity.getString(R.string.contents_text);
}
} else if (type.equals(Contents.Type.EMAIL)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "mailto:" + data;
displayContents = data;
title = activity.getString(R.string.contents_email);
}
} else if (type.equals(Contents.Type.PHONE)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "tel:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = activity.getString(R.string.contents_phone);
}
} else if (type.equals(Contents.Type.SMS)) {
String data = trim(intent.getStringExtra(Intents.Encode.DATA));
if (data != null) {
contents = "sms:" + data;
displayContents = PhoneNumberUtils.formatNumber(data);
title = activity.getString(R.string.contents_sms);
}
} else if (type.equals(Contents.Type.CONTACT)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String name = trim(bundle.getString(Contacts.Intents.Insert.NAME));
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
String address = trim(bundle.getString(Contacts.Intents.Insert.POSTAL));
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
if (phone != null) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
}
for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
if (email != null) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = activity.getString(R.string.contents_contact);
} else {
contents = null;
displayContents = null;
}
}
} else if (type.equals(Contents.Type.LOCATION)) {
Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
if (bundle != null) {
// These must use Bundle.getFloat(), not getDouble(), it's part of the API.
float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
contents = "geo:" + latitude + ',' + longitude;
displayContents = latitude + "," + longitude;
title = activity.getString(R.string.contents_location);
}
}
}
}
private boolean encodeQRCodeContents(AddressBookParsedResult contact) {
StringBuilder newContents = new StringBuilder(100);
StringBuilder newDisplayContents = new StringBuilder(100);
newContents.append("MECARD:");
String[] names = contact.getNames();
if (names != null && names.length > 0) {
String name = trim(names[0]);
if (name != null) {
newContents.append("N:").append(escapeMECARD(name)).append(';');
newDisplayContents.append(name);
}
}
String[] addresses = contact.getAddresses();
if (addresses != null) {
for (String address : addresses) {
address = trim(address);
if (address != null) {
newContents.append("ADR:").append(escapeMECARD(address)).append(';');
newDisplayContents.append('\n').append(address);
}
}
}
String[] phoneNumbers = contact.getPhoneNumbers();
if (phoneNumbers != null) {
for (String phone : phoneNumbers) {
phone = trim(phone);
if (phone != null) {
newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
}
}
}
String[] emails = contact.getEmails();
if (emails != null) {
for (String email : emails) {
email = trim(email);
if (email != null) {
newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
newDisplayContents.append('\n').append(email);
}
}
}
String url = trim(contact.getURL());
if (url != null) {
newContents.append("URL:").append(escapeMECARD(url)).append(';');
newDisplayContents.append('\n').append(url);
}
// Make sure we've encoded at least one field.
if (newDisplayContents.length() > 0) {
newContents.append(';');
contents = newContents.toString();
displayContents = newDisplayContents.toString();
title = activity.getString(R.string.contents_contact);
return true;
} else {
contents = null;
displayContents = null;
return false;
}
}
Bitmap encodeAsBitmap() throws WriterException {
Hashtable<EncodeHintType,Object> hints = null;
String encoding = guessAppropriateEncoding(contents);
if (encoding != null) {
hints = new Hashtable<EncodeHintType,Object>(2);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
private static String trim(String s) {
if (s == null) {
return null;
}
s = s.trim();
return s.length() == 0 ? null : s;
}
private static String escapeMECARD(String input) {
if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) {
return input;
}
int length = input.length();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
if (c == ':' || c == ';') {
result.append('\\');
}
result.append(c);
}
return result.toString();
}
}
|
Issue 924 avoid encoding duplicate fields
git-svn-id: b10e9e05a96f28f96949e4aa4212c55f640c8f96@1868 59b500cc-1b3d-0410-9834-0bbf25fbcc57
|
android/src/com/google/zxing/client/android/encode/QRCodeEncoder.java
|
Issue 924 avoid encoding duplicate fields
|
<ide><path>ndroid/src/com/google/zxing/client/android/encode/QRCodeEncoder.java
<ide>
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<add>import java.util.Collection;
<add>import java.util.Collections;
<add>import java.util.HashSet;
<ide> import java.util.Hashtable;
<ide>
<ide> /**
<ide> title = activity.getString(R.string.contents_sms);
<ide> }
<ide> } else if (type.equals(Contents.Type.CONTACT)) {
<add>
<ide> Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
<ide> if (bundle != null) {
<add>
<ide> StringBuilder newContents = new StringBuilder(100);
<ide> StringBuilder newDisplayContents = new StringBuilder(100);
<add>
<ide> newContents.append("MECARD:");
<add>
<ide> String name = trim(bundle.getString(Contacts.Intents.Insert.NAME));
<ide> if (name != null) {
<ide> newContents.append("N:").append(escapeMECARD(name)).append(';');
<ide> newDisplayContents.append(name);
<ide> }
<add>
<ide> String address = trim(bundle.getString(Contacts.Intents.Insert.POSTAL));
<ide> if (address != null) {
<ide> newContents.append("ADR:").append(escapeMECARD(address)).append(';');
<ide> newDisplayContents.append('\n').append(address);
<ide> }
<add>
<add> Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
<ide> for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
<ide> String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
<ide> if (phone != null) {
<del> newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
<del> newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
<add> uniquePhones.add(phone);
<ide> }
<ide> }
<add> for (String phone : uniquePhones) {
<add> newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
<add> newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
<add> }
<add>
<add> Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
<ide> for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
<ide> String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
<ide> if (email != null) {
<del> newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
<del> newDisplayContents.append('\n').append(email);
<add> uniqueEmails.add(email);
<ide> }
<ide> }
<add> for (String email : uniqueEmails) {
<add> newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
<add> newDisplayContents.append('\n').append(email);
<add> }
<add>
<ide> // Make sure we've encoded at least one field.
<ide> if (newDisplayContents.length() > 0) {
<ide> newContents.append(';');
<ide> contents = null;
<ide> displayContents = null;
<ide> }
<del> }
<add>
<add> }
<add>
<ide> } else if (type.equals(Contents.Type.LOCATION)) {
<ide> Bundle bundle = intent.getBundleExtra(Intents.Encode.DATA);
<ide> if (bundle != null) {
<ide> }
<ide>
<ide> private boolean encodeQRCodeContents(AddressBookParsedResult contact) {
<add>
<ide> StringBuilder newContents = new StringBuilder(100);
<ide> StringBuilder newDisplayContents = new StringBuilder(100);
<add>
<ide> newContents.append("MECARD:");
<add>
<ide> String[] names = contact.getNames();
<ide> if (names != null && names.length > 0) {
<ide> String name = trim(names[0]);
<ide> newDisplayContents.append(name);
<ide> }
<ide> }
<del> String[] addresses = contact.getAddresses();
<del> if (addresses != null) {
<del> for (String address : addresses) {
<del> address = trim(address);
<del> if (address != null) {
<del> newContents.append("ADR:").append(escapeMECARD(address)).append(';');
<del> newDisplayContents.append('\n').append(address);
<del> }
<del> }
<del> }
<del> String[] phoneNumbers = contact.getPhoneNumbers();
<del> if (phoneNumbers != null) {
<del> for (String phone : phoneNumbers) {
<del> phone = trim(phone);
<del> if (phone != null) {
<del> newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
<del> newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
<del> }
<del> }
<del> }
<del> String[] emails = contact.getEmails();
<del> if (emails != null) {
<del> for (String email : emails) {
<del> email = trim(email);
<del> if (email != null) {
<del> newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
<del> newDisplayContents.append('\n').append(email);
<del> }
<del> }
<del> }
<add>
<add> for (String address : trimAndDeduplicate(contact.getAddresses())) {
<add> newContents.append("ADR:").append(escapeMECARD(address)).append(';');
<add> newDisplayContents.append('\n').append(address);
<add> }
<add>
<add> for (String phone : trimAndDeduplicate(contact.getPhoneNumbers())) {
<add> newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
<add> newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
<add> }
<add>
<add> for (String email : trimAndDeduplicate(contact.getEmails())) {
<add> newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
<add> newDisplayContents.append('\n').append(email);
<add> }
<add>
<ide> String url = trim(contact.getURL());
<ide> if (url != null) {
<ide> newContents.append("URL:").append(escapeMECARD(url)).append(';');
<ide> newDisplayContents.append('\n').append(url);
<ide> }
<add>
<ide> // Make sure we've encoded at least one field.
<ide> if (newDisplayContents.length() > 0) {
<ide> newContents.append(';');
<ide> }
<ide> }
<ide>
<add> private static Iterable<String> trimAndDeduplicate(String[] values) {
<add> if (values == null || values.length == 0) {
<add> return Collections.emptySet();
<add> }
<add> Collection<String> uniqueValues = new HashSet<String>(values.length);
<add> for (String value : values) {
<add> uniqueValues.add(trim(value));
<add> }
<add> return uniqueValues;
<add> }
<add>
<ide> Bitmap encodeAsBitmap() throws WriterException {
<ide> Hashtable<EncodeHintType,Object> hints = null;
<ide> String encoding = guessAppropriateEncoding(contents);
|
|
Java
|
apache-2.0
|
86dfc59122b7763fffb6149c0874ab7fe2849de0
| 0 |
GOGO98901/RorysMod
|
/*
Copyright 2016 Rory Claasen
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.roryclaasen.asm.rorysmodcore.transformer;
import java.util.Iterator;
import net.minecraft.launchwrapper.IClassTransformer;
import net.roryclaasen.rorysmod.util.RMLog;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
public class WorldServerTransformer implements IClassTransformer {
@Override
public byte[] transform(String arg0, String arg1, byte[] arg2) {
byte[] data = arg2;
try {
if (arg0.equals("mt")) {
RMLog.info("About to patch WorldServer [mt]", true);
data = patchWakeAllPlayers(arg0, data, true);
data = patchTick(arg0, data, true);
}
if (arg0.equals("net.minecraft.world.WorldServer")) {
RMLog.info("About to patch WorldServer [net.minecraft.world.WorldServer]", true);
data = patchWakeAllPlayers(arg0, data, false);
data = patchTick(arg0, data, false);
}
} catch (Exception e) {
RMLog.warn("Patch failed!", true);
e.printStackTrace();
}
if (data != arg2) {
RMLog.info("Finnished Patching! and applied changes", true);
}
return data;
}
public byte[] patchTick(String name, byte[] bytes, boolean obfuscated) {
RMLog.info("[tick] Patching", true);
String targetMethodName = "";
if (obfuscated == true) targetMethodName = "b";
else targetMethodName = "tick";
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
Iterator<MethodNode> methods = classNode.methods.iterator();
while (methods.hasNext()) {
MethodNode method = methods.next();
int invok_index = -1;
if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
AbstractInsnNode currentNode = null;
AbstractInsnNode targetNode = null;
Iterator<AbstractInsnNode> iter = method.instructions.iterator();
int index = -1;
int INVOKEVIRTUAL_COUNT = 0;
while (iter.hasNext()) {
index++;
currentNode = iter.next();
if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
INVOKEVIRTUAL_COUNT++;
if (INVOKEVIRTUAL_COUNT == 9) {
targetNode = currentNode;
invok_index = index;
break;
}
}
}
if (targetNode == null || invok_index == -1) {
RMLog.info("Did not find all necessary target nodes! ABANDON CLASS!");
return bytes;
}
AbstractInsnNode p1 = method.instructions.get(invok_index);
MethodInsnNode a1 = new MethodInsnNode(Opcodes.INVOKESPECIAL, "net/minecraft/world/WorldServer", "resetRainAndThunder", "()V", false);
method.instructions.set(p1, a1);
break;
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
public byte[] patchWakeAllPlayers(String name, byte[] bytes, boolean obfuscated) {
RMLog.info("[wakeAllPlayers] Patching", true);
String targetMethodName = "";
if (obfuscated == true) targetMethodName = "d";
else targetMethodName = "wakeAllPlayers";
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
Iterator<MethodNode> methods = classNode.methods.iterator();
while (methods.hasNext()) {
MethodNode method = methods.next();
int invok_index = -1;
if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
AbstractInsnNode currentNode = null;
AbstractInsnNode targetNode = null;
Iterator<AbstractInsnNode> iter = method.instructions.iterator();
int index = -1;
while (iter.hasNext()) {
index++;
currentNode = iter.next();
if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
invok_index = index;
targetNode = currentNode;
break;
}
}
if (targetNode == null || invok_index == -1) {
RMLog.info("Did not find all necessary target nodes! ABANDON CLASS!");
return bytes;
}
AbstractInsnNode p1 = method.instructions.get(invok_index);
MethodInsnNode p2 = new MethodInsnNode(Opcodes.INVOKESTATIC, "net/roryclaasen/asm/rorysmodcore/transformer/StaticClass", "shouldWakeUp", "()Z", false);
method.instructions.set(p1, p2);
method.instructions.remove(method.instructions.get(invok_index - 1));
break;
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
}
|
src/main/java/net/roryclaasen/asm/rorysmodcore/transformer/WorldServerTransformer.java
|
/*
Copyright 2016 Rory Claasen
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.roryclaasen.asm.rorysmodcore.transformer;
import java.util.Iterator;
import net.minecraft.launchwrapper.IClassTransformer;
import net.roryclaasen.rorysmod.util.RMLog;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
public class WorldServerTransformer implements IClassTransformer {
@Override
public byte[] transform(String arg0, String arg1, byte[] arg2) {
byte[] data = arg2;
try {
if (arg0.equals("mt")) {
RMLog.info("About to patch WorldServer [mt]", true);
data = patchWakeAllPlayers(arg0, data, true);
data = patchTick(arg0, data, true);
}
if (arg0.equals("net.minecraft.world.WorldServer")) {
RMLog.info("About to patch WorldServer [net.minecraft.world.WorldServer]", true);
data = patchWakeAllPlayers(arg0, data, false);
data = patchTick(arg0, data, false);
}
} catch (Exception e) {
RMLog.warn("Patch failed!", true);
e.printStackTrace();
}
if (data != arg2) {
RMLog.info("Finnished Patching! and applied changes", true);
}
return data;
}
public byte[] patchTick(String name, byte[] bytes, boolean obfuscated) {
RMLog.info("[tick] Patching", true);
String targetMethodName = "";
if (obfuscated == true) targetMethodName = "b";
else targetMethodName = "tick";
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
Iterator<MethodNode> methods = classNode.methods.iterator();
while (methods.hasNext()) {
MethodNode method = methods.next();
int invok_index = -1;
if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
AbstractInsnNode currentNode = null;
AbstractInsnNode targetNode = null;
Iterator<AbstractInsnNode> iter = method.instructions.iterator();
int index = -1;
int INVOKEVIRTUAL_COUNT = 0;
while (iter.hasNext()) {
index++;
currentNode = iter.next();
if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
INVOKEVIRTUAL_COUNT++;
targetNode = currentNode;
invok_index = index;
if (INVOKEVIRTUAL_COUNT == 9) break;
}
}
if (targetNode == null || invok_index == -1) {
RMLog.info("Did not find all necessary target nodes! ABANDON CLASS!");
return bytes;
}
AbstractInsnNode p1 = method.instructions.get(invok_index);
MethodInsnNode a1 = new MethodInsnNode(Opcodes.INVOKESPECIAL, "net/minecraft/world/WorldServer", "resetRainAndThunder", "()V", false);
method.instructions.set(p1, a1);
break;
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
public byte[] patchWakeAllPlayers(String name, byte[] bytes, boolean obfuscated) {
RMLog.info("[wakeAllPlayers] Patching", true);
String targetMethodName = "";
if (obfuscated == true) targetMethodName = "d";
else targetMethodName = "wakeAllPlayers";
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
Iterator<MethodNode> methods = classNode.methods.iterator();
while (methods.hasNext()) {
MethodNode method = methods.next();
int invok_index = -1;
if ((method.name.equals(targetMethodName) && method.desc.equals("()V"))) {
AbstractInsnNode currentNode = null;
AbstractInsnNode targetNode = null;
Iterator<AbstractInsnNode> iter = method.instructions.iterator();
int index = -1;
while (iter.hasNext()) {
index++;
currentNode = iter.next();
if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
invok_index = index;
targetNode = currentNode;
break;
}
}
if (targetNode == null || invok_index == -1) {
RMLog.info("Did not find all necessary target nodes! ABANDON CLASS!");
return bytes;
}
AbstractInsnNode p1 = method.instructions.get(invok_index);
MethodInsnNode p2 = new MethodInsnNode(Opcodes.INVOKESTATIC, "net/roryclaasen/asm/rorysmodcore/transformer/StaticClass", "shouldWakeUp", "()Z", false);
method.instructions.set(p1, p2);
method.instructions.remove(method.instructions.get(invok_index - 1));
break;
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
}
|
Fix null check
|
src/main/java/net/roryclaasen/asm/rorysmodcore/transformer/WorldServerTransformer.java
|
Fix null check
|
<ide><path>rc/main/java/net/roryclaasen/asm/rorysmodcore/transformer/WorldServerTransformer.java
<ide> currentNode = iter.next();
<ide> if (currentNode.getOpcode() == Opcodes.INVOKEVIRTUAL) {
<ide> INVOKEVIRTUAL_COUNT++;
<del> targetNode = currentNode;
<del> invok_index = index;
<del> if (INVOKEVIRTUAL_COUNT == 9) break;
<add> if (INVOKEVIRTUAL_COUNT == 9) {
<add> targetNode = currentNode;
<add> invok_index = index;
<add> break;
<add> }
<ide> }
<ide> }
<ide> if (targetNode == null || invok_index == -1) {
|
|
JavaScript
|
mit
|
fc1887df497da2b5d29a7e8be6a4c090d08e8ad4
| 0 |
santilland/plotty,santilland/plotty
|
export const colorscales = {
viridis: new Uint8Array([68,1,84,255,68,2,86,255,69,4,87,255,69,5,89,255,70,7,90,255,70,8,92,255,70,10,93,255,70,11,94,255,71,13,96,255,71,14,97,255,71,16,99,255,71,17,100,255,71,19,101,255,72,20,103,255,72,22,104,255,72,23,105,255,72,24,106,255,72,26,108,255,72,27,109,255,72,28,110,255,72,29,111,255,72,31,112,255,72,32,113,255,72,33,115,255,72,35,116,255,72,36,117,255,72,37,118,255,72,38,119,255,72,40,120,255,72,41,121,255,71,42,122,255,71,44,122,255,71,45,123,255,71,46,124,255,71,47,125,255,70,48,126,255,70,50,126,255,70,51,127,255,70,52,128,255,69,53,129,255,69,55,129,255,69,56,130,255,68,57,131,255,68,58,131,255,68,59,132,255,67,61,132,255,67,62,133,255,66,63,133,255,66,64,134,255,66,65,134,255,65,66,135,255,65,68,135,255,64,69,136,255,64,70,136,255,63,71,136,255,63,72,137,255,62,73,137,255,62,74,137,255,62,76,138,255,61,77,138,255,61,78,138,255,60,79,138,255,60,80,139,255,59,81,139,255,59,82,139,255,58,83,139,255,58,84,140,255,57,85,140,255,57,86,140,255,56,88,140,255,56,89,140,255,55,90,140,255,55,91,141,255,54,92,141,255,54,93,141,255,53,94,141,255,53,95,141,255,52,96,141,255,52,97,141,255,51,98,141,255,51,99,141,255,50,100,142,255,50,101,142,255,49,102,142,255,49,103,142,255,49,104,142,255,48,105,142,255,48,106,142,255,47,107,142,255,47,108,142,255,46,109,142,255,46,110,142,255,46,111,142,255,45,112,142,255,45,113,142,255,44,113,142,255,44,114,142,255,44,115,142,255,43,116,142,255,43,117,142,255,42,118,142,255,42,119,142,255,42,120,142,255,41,121,142,255,41,122,142,255,41,123,142,255,40,124,142,255,40,125,142,255,39,126,142,255,39,127,142,255,39,128,142,255,38,129,142,255,38,130,142,255,38,130,142,255,37,131,142,255,37,132,142,255,37,133,142,255,36,134,142,255,36,135,142,255,35,136,142,255,35,137,142,255,35,138,141,255,34,139,141,255,34,140,141,255,34,141,141,255,33,142,141,255,33,143,141,255,33,144,141,255,33,145,140,255,32,146,140,255,32,146,140,255,32,147,140,255,31,148,140,255,31,149,139,255,31,150,139,255,31,151,139,255,31,152,139,255,31,153,138,255,31,154,138,255,30,155,138,255,30,156,137,255,30,157,137,255,31,158,137,255,31,159,136,255,31,160,136,255,31,161,136,255,31,161,135,255,31,162,135,255,32,163,134,255,32,164,134,255,33,165,133,255,33,166,133,255,34,167,133,255,34,168,132,255,35,169,131,255,36,170,131,255,37,171,130,255,37,172,130,255,38,173,129,255,39,173,129,255,40,174,128,255,41,175,127,255,42,176,127,255,44,177,126,255,45,178,125,255,46,179,124,255,47,180,124,255,49,181,123,255,50,182,122,255,52,182,121,255,53,183,121,255,55,184,120,255,56,185,119,255,58,186,118,255,59,187,117,255,61,188,116,255,63,188,115,255,64,189,114,255,66,190,113,255,68,191,112,255,70,192,111,255,72,193,110,255,74,193,109,255,76,194,108,255,78,195,107,255,80,196,106,255,82,197,105,255,84,197,104,255,86,198,103,255,88,199,101,255,90,200,100,255,92,200,99,255,94,201,98,255,96,202,96,255,99,203,95,255,101,203,94,255,103,204,92,255,105,205,91,255,108,205,90,255,110,206,88,255,112,207,87,255,115,208,86,255,117,208,84,255,119,209,83,255,122,209,81,255,124,210,80,255,127,211,78,255,129,211,77,255,132,212,75,255,134,213,73,255,137,213,72,255,139,214,70,255,142,214,69,255,144,215,67,255,147,215,65,255,149,216,64,255,152,216,62,255,155,217,60,255,157,217,59,255,160,218,57,255,162,218,55,255,165,219,54,255,168,219,52,255,170,220,50,255,173,220,48,255,176,221,47,255,178,221,45,255,181,222,43,255,184,222,41,255,186,222,40,255,189,223,38,255,192,223,37,255,194,223,35,255,197,224,33,255,200,224,32,255,202,225,31,255,205,225,29,255,208,225,28,255,210,226,27,255,213,226,26,255,216,226,25,255,218,227,25,255,221,227,24,255,223,227,24,255,226,228,24,255,229,228,25,255,231,228,25,255,234,229,26,255,236,229,27,255,239,229,28,255,241,229,29,255,244,230,30,255,246,230,32,255,248,230,33,255,251,231,35,255,253,231,37,255]),
inferno: new Uint8Array([0,0,4,255,1,0,5,255,1,1,6,255,1,1,8,255,2,1,10,255,2,2,12,255,2,2,14,255,3,2,16,255,4,3,18,255,4,3,20,255,5,4,23,255,6,4,25,255,7,5,27,255,8,5,29,255,9,6,31,255,10,7,34,255,11,7,36,255,12,8,38,255,13,8,41,255,14,9,43,255,16,9,45,255,17,10,48,255,18,10,50,255,20,11,52,255,21,11,55,255,22,11,57,255,24,12,60,255,25,12,62,255,27,12,65,255,28,12,67,255,30,12,69,255,31,12,72,255,33,12,74,255,35,12,76,255,36,12,79,255,38,12,81,255,40,11,83,255,41,11,85,255,43,11,87,255,45,11,89,255,47,10,91,255,49,10,92,255,50,10,94,255,52,10,95,255,54,9,97,255,56,9,98,255,57,9,99,255,59,9,100,255,61,9,101,255,62,9,102,255,64,10,103,255,66,10,104,255,68,10,104,255,69,10,105,255,71,11,106,255,73,11,106,255,74,12,107,255,76,12,107,255,77,13,108,255,79,13,108,255,81,14,108,255,82,14,109,255,84,15,109,255,85,15,109,255,87,16,110,255,89,16,110,255,90,17,110,255,92,18,110,255,93,18,110,255,95,19,110,255,97,19,110,255,98,20,110,255,100,21,110,255,101,21,110,255,103,22,110,255,105,22,110,255,106,23,110,255,108,24,110,255,109,24,110,255,111,25,110,255,113,25,110,255,114,26,110,255,116,26,110,255,117,27,110,255,119,28,109,255,120,28,109,255,122,29,109,255,124,29,109,255,125,30,109,255,127,30,108,255,128,31,108,255,130,32,108,255,132,32,107,255,133,33,107,255,135,33,107,255,136,34,106,255,138,34,106,255,140,35,105,255,141,35,105,255,143,36,105,255,144,37,104,255,146,37,104,255,147,38,103,255,149,38,103,255,151,39,102,255,152,39,102,255,154,40,101,255,155,41,100,255,157,41,100,255,159,42,99,255,160,42,99,255,162,43,98,255,163,44,97,255,165,44,96,255,166,45,96,255,168,46,95,255,169,46,94,255,171,47,94,255,173,48,93,255,174,48,92,255,176,49,91,255,177,50,90,255,179,50,90,255,180,51,89,255,182,52,88,255,183,53,87,255,185,53,86,255,186,54,85,255,188,55,84,255,189,56,83,255,191,57,82,255,192,58,81,255,193,58,80,255,195,59,79,255,196,60,78,255,198,61,77,255,199,62,76,255,200,63,75,255,202,64,74,255,203,65,73,255,204,66,72,255,206,67,71,255,207,68,70,255,208,69,69,255,210,70,68,255,211,71,67,255,212,72,66,255,213,74,65,255,215,75,63,255,216,76,62,255,217,77,61,255,218,78,60,255,219,80,59,255,221,81,58,255,222,82,56,255,223,83,55,255,224,85,54,255,225,86,53,255,226,87,52,255,227,89,51,255,228,90,49,255,229,92,48,255,230,93,47,255,231,94,46,255,232,96,45,255,233,97,43,255,234,99,42,255,235,100,41,255,235,102,40,255,236,103,38,255,237,105,37,255,238,106,36,255,239,108,35,255,239,110,33,255,240,111,32,255,241,113,31,255,241,115,29,255,242,116,28,255,243,118,27,255,243,120,25,255,244,121,24,255,245,123,23,255,245,125,21,255,246,126,20,255,246,128,19,255,247,130,18,255,247,132,16,255,248,133,15,255,248,135,14,255,248,137,12,255,249,139,11,255,249,140,10,255,249,142,9,255,250,144,8,255,250,146,7,255,250,148,7,255,251,150,6,255,251,151,6,255,251,153,6,255,251,155,6,255,251,157,7,255,252,159,7,255,252,161,8,255,252,163,9,255,252,165,10,255,252,166,12,255,252,168,13,255,252,170,15,255,252,172,17,255,252,174,18,255,252,176,20,255,252,178,22,255,252,180,24,255,251,182,26,255,251,184,29,255,251,186,31,255,251,188,33,255,251,190,35,255,250,192,38,255,250,194,40,255,250,196,42,255,250,198,45,255,249,199,47,255,249,201,50,255,249,203,53,255,248,205,55,255,248,207,58,255,247,209,61,255,247,211,64,255,246,213,67,255,246,215,70,255,245,217,73,255,245,219,76,255,244,221,79,255,244,223,83,255,244,225,86,255,243,227,90,255,243,229,93,255,242,230,97,255,242,232,101,255,242,234,105,255,241,236,109,255,241,237,113,255,241,239,117,255,241,241,121,255,242,242,125,255,242,244,130,255,243,245,134,255,243,246,138,255,244,248,142,255,245,249,146,255,246,250,150,255,248,251,154,255,249,252,157,255,250,253,161,255,252,255,164,255]),
rainbow: {
colors: ['#96005A','#0000C8','#0019FF','#0098FF','#2CFF96','#97FF00','#FFEA00','#FF6F00','#FF0000'],
positions: [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1]
},
jet: {
colors: ['#000083','#003CAA','#05FFFF','#FFFF00','#FA0000','#800000'],
positions: [0, 0.125, 0.375, 0.625, 0.875, 1]
},
hsv: {
colors: ['#ff0000','#fdff02','#f7ff02','#00fc04','#00fc0a','#01f9ff','#0200fd','#0800fd','#ff00fb','#ff00f5','#ff0006'],
positions: [0,0.169,0.173,0.337,0.341,0.506,0.671,0.675,0.839,0.843,1]
},
hot: {
colors: ['#000000','#e60000','#ffd200','#ffffff'],
positions: [0,0.3,0.6,1]
},
cool: {
colors: ['#00ffff','#ff00ff'],
positions: [0,1]
},
spring: {
colors: ['#ff00ff','#ffff00'],
positions: [0,1]
},
summer: {
colors: ['#008066','#ffff66'],
positions: [0,1]
},
autumn: {
colors: ['#ff0000','#ffff00'],
positions: [0,1]
},
winter: {
colors: ['#0000ff','#00ff80'],
positions: [0,1]
},
bone: {
colors: ['#000000','#545474','#a9c8c8','#ffffff'],
positions: [0,0.376,0.753,1]
},
copper: {
colors: ['#000000','#ffa066','#ffc77f'],
positions: [0,0.804,1]
},
greys: {
colors: ['#000000','#ffffff'],
positions: [0,1]
},
yignbu: {
colors: ['#081d58','#253494','#225ea8','#1d91c0','#41b6c4','#7fcdbb','#c7e9b4','#edf8d9','#ffffd9'],
positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
},
greens: {
colors: ['#00441b','#006d2c','#238b45','#41ab5d','#74c476','#a1d99b','#c7e9c0','#e5f5e0','#f7fcf5'],
positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
},
yiorrd: {
colors: ['#800026','#bd0026','#e31a1c','#fc4e2a','#fd8d3c','#feb24c','#fed976','#ffeda0','#ffffcc'],
positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
},
bluered: {
colors: ['#0000ff','#ff0000'],
positions: [0,1]
},
rdbu: {
colors: ['#050aac','#6a89f7','#bebebe','#dcaa84','#e6915a','#b20a1c'],
positions: [0,0.35,0.5,0.6,0.7,1]
},
picnic: {
colors: ['#0000ff','#3399ff','#66ccff','#99ccff','#ccccff','#ffffff','#ffccff','#ff99ff','#ff66cc','#ff6666','#ff0000'],
positions: [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
},
portland: {
colors: ['#0c3383','#0a88ba','#f2d338','#f28f38','#d91e1e'],
positions: [0,0.25,0.5,0.75,1]
},
blackbody: {
colors: ['#000000','#e60000','#e6d200','#ffffff','#a0c8ff'],
positions: [0,0.2,0.4,0.7,1]
},
earth: {
colors: ['#000082','#00b4b4','#28d228','#e6e632','#784614','#ffffff'],
positions: [0,0.1,0.2,0.4,0.6,1]
},
electric: {
colors: ['#000000','#1e0064','#780064','#a05a00','#e6c800','#fffadc'],
positions: [0,0.15,0.4,0.6,0.8,1]
},
magma: new Uint8Array([0,0,4,255,1,0,5,255,1,1,6,255,1,1,8,255,2,1,9,255,2,2,11,255,2,2,13,255,3,3,15,255,3,3,18,255,4,4,20,255,5,4,22,255,6,5,24,255,6,5,26,255,7,6,28,255,8,7,30,255,9,7,32,255,10,8,34,255,11,9,36,255,12,9,38,255,13,10,41,255,14,11,43,255,16,11,45,255,17,12,47,255,18,13,49,255,19,13,52,255,20,14,54,255,21,14,56,255,22,15,59,255,24,15,61,255,25,16,63,255,26,16,66,255,28,16,68,255,29,17,71,255,30,17,73,255,32,17,75,255,33,17,78,255,34,17,80,255,36,18,83,255,37,18,85,255,39,18,88,255,41,17,90,255,42,17,92,255,44,17,95,255,45,17,97,255,47,17,99,255,49,17,101,255,51,16,103,255,52,16,105,255,54,16,107,255,56,16,108,255,57,15,110,255,59,15,112,255,61,15,113,255,63,15,114,255,64,15,116,255,66,15,117,255,68,15,118,255,69,16,119,255,71,16,120,255,73,16,120,255,74,16,121,255,76,17,122,255,78,17,123,255,79,18,123,255,81,18,124,255,82,19,124,255,84,19,125,255,86,20,125,255,87,21,126,255,89,21,126,255,90,22,126,255,92,22,127,255,93,23,127,255,95,24,127,255,96,24,128,255,98,25,128,255,100,26,128,255,101,26,128,255,103,27,128,255,104,28,129,255,106,28,129,255,107,29,129,255,109,29,129,255,110,30,129,255,112,31,129,255,114,31,129,255,115,32,129,255,117,33,129,255,118,33,129,255,120,34,129,255,121,34,130,255,123,35,130,255,124,35,130,255,126,36,130,255,128,37,130,255,129,37,129,255,131,38,129,255,132,38,129,255,134,39,129,255,136,39,129,255,137,40,129,255,139,41,129,255,140,41,129,255,142,42,129,255,144,42,129,255,145,43,129,255,147,43,128,255,148,44,128,255,150,44,128,255,152,45,128,255,153,45,128,255,155,46,127,255,156,46,127,255,158,47,127,255,160,47,127,255,161,48,126,255,163,48,126,255,165,49,126,255,166,49,125,255,168,50,125,255,170,51,125,255,171,51,124,255,173,52,124,255,174,52,123,255,176,53,123,255,178,53,123,255,179,54,122,255,181,54,122,255,183,55,121,255,184,55,121,255,186,56,120,255,188,57,120,255,189,57,119,255,191,58,119,255,192,58,118,255,194,59,117,255,196,60,117,255,197,60,116,255,199,61,115,255,200,62,115,255,202,62,114,255,204,63,113,255,205,64,113,255,207,64,112,255,208,65,111,255,210,66,111,255,211,67,110,255,213,68,109,255,214,69,108,255,216,69,108,255,217,70,107,255,219,71,106,255,220,72,105,255,222,73,104,255,223,74,104,255,224,76,103,255,226,77,102,255,227,78,101,255,228,79,100,255,229,80,100,255,231,82,99,255,232,83,98,255,233,84,98,255,234,86,97,255,235,87,96,255,236,88,96,255,237,90,95,255,238,91,94,255,239,93,94,255,240,95,94,255,241,96,93,255,242,98,93,255,242,100,92,255,243,101,92,255,244,103,92,255,244,105,92,255,245,107,92,255,246,108,92,255,246,110,92,255,247,112,92,255,247,114,92,255,248,116,92,255,248,118,92,255,249,120,93,255,249,121,93,255,249,123,93,255,250,125,94,255,250,127,94,255,250,129,95,255,251,131,95,255,251,133,96,255,251,135,97,255,252,137,97,255,252,138,98,255,252,140,99,255,252,142,100,255,252,144,101,255,253,146,102,255,253,148,103,255,253,150,104,255,253,152,105,255,253,154,106,255,253,155,107,255,254,157,108,255,254,159,109,255,254,161,110,255,254,163,111,255,254,165,113,255,254,167,114,255,254,169,115,255,254,170,116,255,254,172,118,255,254,174,119,255,254,176,120,255,254,178,122,255,254,180,123,255,254,182,124,255,254,183,126,255,254,185,127,255,254,187,129,255,254,189,130,255,254,191,132,255,254,193,133,255,254,194,135,255,254,196,136,255,254,198,138,255,254,200,140,255,254,202,141,255,254,204,143,255,254,205,144,255,254,207,146,255,254,209,148,255,254,211,149,255,254,213,151,255,254,215,153,255,254,216,154,255,253,218,156,255,253,220,158,255,253,222,160,255,253,224,161,255,253,226,163,255,253,227,165,255,253,229,167,255,253,231,169,255,253,233,170,255,253,235,172,255,252,236,174,255,252,238,176,255,252,240,178,255,252,242,180,255,252,244,182,255,252,246,184,255,252,247,185,255,252,249,187,255,252,251,189,255,252,253,191,255]),
plasma: new Uint8Array([13,8,135,255,16,7,136,255,19,7,137,255,22,7,138,255,25,6,140,255,27,6,141,255,29,6,142,255,32,6,143,255,34,6,144,255,36,6,145,255,38,5,145,255,40,5,146,255,42,5,147,255,44,5,148,255,46,5,149,255,47,5,150,255,49,5,151,255,51,5,151,255,53,4,152,255,55,4,153,255,56,4,154,255,58,4,154,255,60,4,155,255,62,4,156,255,63,4,156,255,65,4,157,255,67,3,158,255,68,3,158,255,70,3,159,255,72,3,159,255,73,3,160,255,75,3,161,255,76,2,161,255,78,2,162,255,80,2,162,255,81,2,163,255,83,2,163,255,85,2,164,255,86,1,164,255,88,1,164,255,89,1,165,255,91,1,165,255,92,1,166,255,94,1,166,255,96,1,166,255,97,0,167,255,99,0,167,255,100,0,167,255,102,0,167,255,103,0,168,255,105,0,168,255,106,0,168,255,108,0,168,255,110,0,168,255,111,0,168,255,113,0,168,255,114,1,168,255,116,1,168,255,117,1,168,255,119,1,168,255,120,1,168,255,122,2,168,255,123,2,168,255,125,3,168,255,126,3,168,255,128,4,168,255,129,4,167,255,131,5,167,255,132,5,167,255,134,6,166,255,135,7,166,255,136,8,166,255,138,9,165,255,139,10,165,255,141,11,165,255,142,12,164,255,143,13,164,255,145,14,163,255,146,15,163,255,148,16,162,255,149,17,161,255,150,19,161,255,152,20,160,255,153,21,159,255,154,22,159,255,156,23,158,255,157,24,157,255,158,25,157,255,160,26,156,255,161,27,155,255,162,29,154,255,163,30,154,255,165,31,153,255,166,32,152,255,167,33,151,255,168,34,150,255,170,35,149,255,171,36,148,255,172,38,148,255,173,39,147,255,174,40,146,255,176,41,145,255,177,42,144,255,178,43,143,255,179,44,142,255,180,46,141,255,181,47,140,255,182,48,139,255,183,49,138,255,184,50,137,255,186,51,136,255,187,52,136,255,188,53,135,255,189,55,134,255,190,56,133,255,191,57,132,255,192,58,131,255,193,59,130,255,194,60,129,255,195,61,128,255,196,62,127,255,197,64,126,255,198,65,125,255,199,66,124,255,200,67,123,255,201,68,122,255,202,69,122,255,203,70,121,255,204,71,120,255,204,73,119,255,205,74,118,255,206,75,117,255,207,76,116,255,208,77,115,255,209,78,114,255,210,79,113,255,211,81,113,255,212,82,112,255,213,83,111,255,213,84,110,255,214,85,109,255,215,86,108,255,216,87,107,255,217,88,106,255,218,90,106,255,218,91,105,255,219,92,104,255,220,93,103,255,221,94,102,255,222,95,101,255,222,97,100,255,223,98,99,255,224,99,99,255,225,100,98,255,226,101,97,255,226,102,96,255,227,104,95,255,228,105,94,255,229,106,93,255,229,107,93,255,230,108,92,255,231,110,91,255,231,111,90,255,232,112,89,255,233,113,88,255,233,114,87,255,234,116,87,255,235,117,86,255,235,118,85,255,236,119,84,255,237,121,83,255,237,122,82,255,238,123,81,255,239,124,81,255,239,126,80,255,240,127,79,255,240,128,78,255,241,129,77,255,241,131,76,255,242,132,75,255,243,133,75,255,243,135,74,255,244,136,73,255,244,137,72,255,245,139,71,255,245,140,70,255,246,141,69,255,246,143,68,255,247,144,68,255,247,145,67,255,247,147,66,255,248,148,65,255,248,149,64,255,249,151,63,255,249,152,62,255,249,154,62,255,250,155,61,255,250,156,60,255,250,158,59,255,251,159,58,255,251,161,57,255,251,162,56,255,252,163,56,255,252,165,55,255,252,166,54,255,252,168,53,255,252,169,52,255,253,171,51,255,253,172,51,255,253,174,50,255,253,175,49,255,253,177,48,255,253,178,47,255,253,180,47,255,253,181,46,255,254,183,45,255,254,184,44,255,254,186,44,255,254,187,43,255,254,189,42,255,254,190,42,255,254,192,41,255,253,194,41,255,253,195,40,255,253,197,39,255,253,198,39,255,253,200,39,255,253,202,38,255,253,203,38,255,252,205,37,255,252,206,37,255,252,208,37,255,252,210,37,255,251,211,36,255,251,213,36,255,251,215,36,255,250,216,36,255,250,218,36,255,249,220,36,255,249,221,37,255,248,223,37,255,248,225,37,255,247,226,37,255,247,228,37,255,246,230,38,255,246,232,38,255,245,233,38,255,245,235,39,255,244,237,39,255,243,238,39,255,243,240,39,255,242,242,39,255,241,244,38,255,241,245,37,255,240,247,36,255,240,249,33,255]),
redblue: {
colors: ['#ff0000', '#0000ff'],
positions: [0,1]
},
coolwarm: {
colors: ['#0000ff', '#ffffff', '#ff0000'],
positions: [0,0.5,1]
},
diverging_1: {
colors: ['#400040','#3b004d','#36005b','#320068','#2d0076','#290084','#240091','#20009f','#1b00ad','#1600ba','#1200c8','#0d00d6','#0900e3','#0400f1','#0000ff','#0217ff','#042eff','#0645ff','#095cff','#0b73ff','#0d8bff','#10a2ff','#12b9ff','#14d0ff','#17e7ff','#19ffff','#3fffff','#66ffff','#8cffff','#b2ffff','#d8ffff','#ffffff','#ffffd4','#ffffaa','#ffff7f','#ffff54','#ffff2a','#ffff00','#ffed00','#ffdd00','#ffcc00','#ffba00','#ffaa00','#ff9900','#ff8700','#ff7700','#ff6600','#ff5400','#ff4400','#ff3300','#ff2100','#ff1100','#ff0000','#ff0017','#ff002e','#ff0045','#ff005c','#ff0073','#ff008b','#ff00a2','#ff00b9','#ff00d0','#ff00e7','#ff00ff'],
positions: [0.0,0.01587301587,0.03174603174,0.04761904761,0.06349206348,0.07936507935,0.09523809522,0.11111111109,0.12698412696,0.14285714283,0.15873015870,0.17460317457,0.19047619044,0.20634920631,0.22222222218,0.23809523805,0.25396825392,0.26984126979,0.28571428566,0.30158730153,0.31746031740,0.33333333327,0.34920634914,0.36507936501,0.38095238088,0.39682539675,0.41269841262,0.42857142849,0.44444444436,0.46031746023,0.47619047610,0.49206349197,0.50793650784,0.52380952371,0.53968253958,0.55555555545,0.57142857132,0.58730158719,0.60317460306,0.61904761893,0.63492063480,0.65079365067,0.66666666654,0.68253968241,0.69841269828,0.71428571415,0.73015873002,0.74603174589,0.76190476176,0.77777777763,0.79365079350,0.80952380937,0.82539682524,0.84126984111,0.85714285698,0.87301587285,0.88888888872,0.90476190459,0.92063492046,0.93650793633,0.95238095220,0.96825396807,0.98412698394,1]
},
diverging_2: {
colors: ['#000000','#030aff','#204aff','#3c8aff','#77c4ff','#f0ffff','#f0ffff','#f2ff7f','#ffff00','#ff831e','#ff083d','#ff00ff'],
positions: [0,0.0000000001,0.1,0.2,0.3333,0.4666,0.5333,0.6666,0.8,0.9,0.999999999999,1]
},
blackwhite: {
colors: ['#000000','#ffffff'],
positions: [0,1]
},
ylgnbu: {
colors: ['#081d58','#253494','#225ea8','#1d91c0','#41b6c4','#7fcdbb','#c7e9b4','#edf8d9','#ffffd9'],
positions: [1,0.875,0.75,0.625,0.5,0.375,0.25,0.125,0]
},
ylorrd: {
colors: ['#800026','#bd0026','#e31a1c','#fc4e2a','#fd8d3c','#feb24c','#fed976','#ffeda0','#ffffcc'],
positions: [1,0.875,0.75,0.625,0.5,0.375,0.25,0.125,0]
},
twilight: {
colors: ['#E2D9E2', '#E0D9E2', '#DDD9E0', '#DAD8DF', '#D6D7DD', '#D2D5DB', '#CDD3D8', '#C8D0D6', '#C2CED4', '#BCCBD1', '#B6C8CF', '#B0C5CD', '#AAC2CC', '#A4BECA', '#9EBBC9', '#99B8C8', '#93B4C6', '#8EB1C5', '#89ADC5', '#85A9C4', '#80A5C3', '#7CA2C2', '#789EC2', '#759AC1', '#7196C1', '#6E92C0', '#6C8EBF', '#698ABF', '#6786BE', '#6682BD', '#647DBC', '#6379BB', '#6275BA', '#6170B9', '#606CB8', '#6067B6', '#5F62B4', '#5F5EB3', '#5F59B1', '#5E54AE', '#5E4FAC', '#5E4BA9', '#5E46A6', '#5D41A3', '#5D3CA0', '#5C379C', '#5B3298', '#5A2E93', '#59298E', '#572588', '#562182', '#531E7C', '#511A75', '#4E186F', '#4B1668', '#471461', '#44135A', '#411254', '#3D114E', '#3A1149', '#371144', '#351140', '#33113C', '#311339', '#301437', '#331237', '#351138', '#381139', '#3B113B', '#3F123D', '#43123E', '#481341', '#4D1443', '#521545', '#571647', '#5C1749', '#61184B', '#67194C', '#6C1B4E', '#711D4F', '#761F4F', '#7B2150', '#802350', '#852650', '#8A2950', '#8E2C50', '#922F50', '#963350', '#9A3750', '#9E3B50', '#A13F50', '#A54350', '#A84750', '#AB4B50', '#AE5051', '#B15452', '#B35953', '#B65D54', '#B86255', '#BA6657', '#BC6B59', '#BE705B', '#C0755E', '#C27A61', '#C37F64', '#C58468', '#C6896C', '#C78E71', '#C89275', '#C9977B', '#CA9C80', '#CCA186', '#CDA68C', '#CEAB92', '#CFAF99', '#D1B4A0', '#D2B8A7', '#D4BDAD', '#D6C1B4', '#D8C5BB', '#D9C9C2', '#DBCCC8', '#DDD0CE', '#DED3D3', '#DFD5D8', '#E0D7DB', '#E1D8DF', '#E2D9E1'],
positions: [0.0000000000, 0.0078740157, 0.0157480315, 0.0236220472, 0.0314960630, 0.0393700787, 0.0472440945, 0.0551181102, 0.0629921260, 0.0708661417, 0.0787401575, 0.0866141732, 0.0944881890, 0.1023622047, 0.1102362205, 0.1181102362, 0.1259842520, 0.1338582677, 0.1417322835, 0.1496062992, 0.1574803150, 0.1653543307, 0.1732283465, 0.1811023622, 0.1889763780, 0.1968503937, 0.2047244094, 0.2125984252, 0.2204724409, 0.2283464567, 0.2362204724, 0.2440944882, 0.2519685039, 0.2598425197, 0.2677165354, 0.2755905512, 0.2834645669, 0.2913385827, 0.2992125984, 0.3070866142, 0.3149606299, 0.3228346457, 0.3307086614, 0.3385826772, 0.3464566929, 0.3543307087, 0.3622047244, 0.3700787402, 0.3779527559, 0.3858267717, 0.3937007874, 0.4015748031, 0.4094488189, 0.4173228346, 0.4251968504, 0.4330708661, 0.4409448819, 0.4488188976, 0.4566929134, 0.4645669291, 0.4724409449, 0.4803149606, 0.4881889764, 0.4960629921, 0.5039370079, 0.5118110236, 0.5196850394, 0.5275590551, 0.5354330709, 0.5433070866, 0.5511811024, 0.5590551181, 0.5669291339, 0.5748031496, 0.5826771654, 0.5905511811, 0.5984251969, 0.6062992126, 0.6141732283, 0.6220472441, 0.6299212598, 0.6377952756, 0.6456692913, 0.6535433071, 0.6614173228, 0.6692913386, 0.6771653543, 0.6850393701, 0.6929133858, 0.7007874016, 0.7086614173, 0.7165354331, 0.7244094488, 0.7322834646, 0.7401574803, 0.7480314961, 0.7559055118, 0.7637795276, 0.7716535433, 0.7795275591, 0.7874015748, 0.7952755906, 0.8031496063, 0.8110236220, 0.8188976378, 0.8267716535, 0.8346456693, 0.8425196850, 0.8503937008, 0.8582677165, 0.8661417323, 0.8740157480, 0.8818897638, 0.8897637795, 0.8976377953, 0.9055118110, 0.9133858268, 0.9212598425, 0.9291338583, 0.9370078740, 0.9448818898, 0.9527559055, 0.9606299213, 0.9685039370, 0.9763779528, 0.9842519685, 0.9921259843, 1.0000000000]
},
twilight_shifted: {
colors: ['#301437', '#32123A', '#34113E', '#361142', '#391146', '#3C114B', '#3F1251', '#421257', '#46145E', '#491564', '#4C176B', '#4F1972', '#521C79', '#551F7F', '#572385', '#58278B', '#5A2B90', '#5B3095', '#5C359A', '#5D3A9E', '#5D3EA1', '#5E43A5', '#5E48A8', '#5E4DAB', '#5E52AD', '#5F57B0', '#5F5BB2', '#5F60B4', '#5F65B5', '#6069B7', '#606EB8', '#6172BA', '#6277BB', '#637BBC', '#657FBD', '#6684BD', '#6888BE', '#6B8CBF', '#6D90C0', '#7094C0', '#7398C1', '#769CC1', '#7AA0C2', '#7EA4C3', '#82A7C3', '#87ABC4', '#8CAFC5', '#91B2C6', '#96B6C7', '#9CB9C8', '#A1BDC9', '#A7C0CB', '#ADC3CD', '#B3C6CE', '#B9C9D0', '#BFCCD3', '#C5CFD5', '#CBD2D7', '#D0D4D9', '#D4D6DC', '#D8D8DE', '#DCD9DF', '#DED9E1', '#E1D9E2', '#E2D9E1', '#E1D8DF', '#E0D7DB', '#DFD5D8', '#DED3D3', '#DDD0CE', '#DBCCC8', '#D9C9C2', '#D8C5BB', '#D6C1B4', '#D4BDAD', '#D2B8A7', '#D1B4A0', '#CFAF99', '#CEAB92', '#CDA68C', '#CCA186', '#CA9C80', '#C9977B', '#C89275', '#C78E71', '#C6896C', '#C58468', '#C37F64', '#C27A61', '#C0755E', '#BE705B', '#BC6B59', '#BA6657', '#B86255', '#B65D54', '#B35953', '#B15452', '#AE5051', '#AB4B50', '#A84750', '#A54350', '#A13F50', '#9E3B50', '#9A3750', '#963350', '#922F50', '#8E2C50', '#8A2950', '#852650', '#802350', '#7B2150', '#761F4F', '#711D4F', '#6C1B4E', '#67194C', '#61184B', '#5C1749', '#571647', '#521545', '#4D1443', '#481341', '#43123E', '#3F123D', '#3B113B', '#381139', '#351138', '#331237', '#301437'],
positions: [0.0000000000, 0.0078740157, 0.0157480315, 0.0236220472, 0.0314960630, 0.0393700787, 0.0472440945, 0.0551181102, 0.0629921260, 0.0708661417, 0.0787401575, 0.0866141732, 0.0944881890, 0.1023622047, 0.1102362205, 0.1181102362, 0.1259842520, 0.1338582677, 0.1417322835, 0.1496062992, 0.1574803150, 0.1653543307, 0.1732283465, 0.1811023622, 0.1889763780, 0.1968503937, 0.2047244094, 0.2125984252, 0.2204724409, 0.2283464567, 0.2362204724, 0.2440944882, 0.2519685039, 0.2598425197, 0.2677165354, 0.2755905512, 0.2834645669, 0.2913385827, 0.2992125984, 0.3070866142, 0.3149606299, 0.3228346457, 0.3307086614, 0.3385826772, 0.3464566929, 0.3543307087, 0.3622047244, 0.3700787402, 0.3779527559, 0.3858267717, 0.3937007874, 0.4015748031, 0.4094488189, 0.4173228346, 0.4251968504, 0.4330708661, 0.4409448819, 0.4488188976, 0.4566929134, 0.4645669291, 0.4724409449, 0.4803149606, 0.4881889764, 0.4960629921, 0.5039370079, 0.5118110236, 0.5196850394, 0.5275590551, 0.5354330709, 0.5433070866, 0.5511811024, 0.5590551181, 0.5669291339, 0.5748031496, 0.5826771654, 0.5905511811, 0.5984251969, 0.6062992126, 0.6141732283, 0.6220472441, 0.6299212598, 0.6377952756, 0.6456692913, 0.6535433071, 0.6614173228, 0.6692913386, 0.6771653543, 0.6850393701, 0.6929133858, 0.7007874016, 0.7086614173, 0.7165354331, 0.7244094488, 0.7322834646, 0.7401574803, 0.7480314961, 0.7559055118, 0.7637795276, 0.7716535433, 0.7795275591, 0.7874015748, 0.7952755906, 0.8031496063, 0.8110236220, 0.8188976378, 0.8267716535, 0.8346456693, 0.8425196850, 0.8503937008, 0.8582677165, 0.8661417323, 0.8740157480, 0.8818897638, 0.8897637795, 0.8976377953, 0.9055118110, 0.9133858268, 0.9212598425, 0.9291338583, 0.9370078740, 0.9448818898, 0.9527559055, 0.9606299213, 0.9685039370, 0.9763779528, 0.9842519685, 0.9921259843, 1.0000000000]
},
};
|
src/colorscales.js
|
export const colorscales = {
"viridis": new Uint8Array([68,1,84,255,68,2,86,255,69,4,87,255,69,5,89,255,70,7,90,255,70,8,92,255,70,10,93,255,70,11,94,255,71,13,96,255,71,14,97,255,71,16,99,255,71,17,100,255,71,19,101,255,72,20,103,255,72,22,104,255,72,23,105,255,72,24,106,255,72,26,108,255,72,27,109,255,72,28,110,255,72,29,111,255,72,31,112,255,72,32,113,255,72,33,115,255,72,35,116,255,72,36,117,255,72,37,118,255,72,38,119,255,72,40,120,255,72,41,121,255,71,42,122,255,71,44,122,255,71,45,123,255,71,46,124,255,71,47,125,255,70,48,126,255,70,50,126,255,70,51,127,255,70,52,128,255,69,53,129,255,69,55,129,255,69,56,130,255,68,57,131,255,68,58,131,255,68,59,132,255,67,61,132,255,67,62,133,255,66,63,133,255,66,64,134,255,66,65,134,255,65,66,135,255,65,68,135,255,64,69,136,255,64,70,136,255,63,71,136,255,63,72,137,255,62,73,137,255,62,74,137,255,62,76,138,255,61,77,138,255,61,78,138,255,60,79,138,255,60,80,139,255,59,81,139,255,59,82,139,255,58,83,139,255,58,84,140,255,57,85,140,255,57,86,140,255,56,88,140,255,56,89,140,255,55,90,140,255,55,91,141,255,54,92,141,255,54,93,141,255,53,94,141,255,53,95,141,255,52,96,141,255,52,97,141,255,51,98,141,255,51,99,141,255,50,100,142,255,50,101,142,255,49,102,142,255,49,103,142,255,49,104,142,255,48,105,142,255,48,106,142,255,47,107,142,255,47,108,142,255,46,109,142,255,46,110,142,255,46,111,142,255,45,112,142,255,45,113,142,255,44,113,142,255,44,114,142,255,44,115,142,255,43,116,142,255,43,117,142,255,42,118,142,255,42,119,142,255,42,120,142,255,41,121,142,255,41,122,142,255,41,123,142,255,40,124,142,255,40,125,142,255,39,126,142,255,39,127,142,255,39,128,142,255,38,129,142,255,38,130,142,255,38,130,142,255,37,131,142,255,37,132,142,255,37,133,142,255,36,134,142,255,36,135,142,255,35,136,142,255,35,137,142,255,35,138,141,255,34,139,141,255,34,140,141,255,34,141,141,255,33,142,141,255,33,143,141,255,33,144,141,255,33,145,140,255,32,146,140,255,32,146,140,255,32,147,140,255,31,148,140,255,31,149,139,255,31,150,139,255,31,151,139,255,31,152,139,255,31,153,138,255,31,154,138,255,30,155,138,255,30,156,137,255,30,157,137,255,31,158,137,255,31,159,136,255,31,160,136,255,31,161,136,255,31,161,135,255,31,162,135,255,32,163,134,255,32,164,134,255,33,165,133,255,33,166,133,255,34,167,133,255,34,168,132,255,35,169,131,255,36,170,131,255,37,171,130,255,37,172,130,255,38,173,129,255,39,173,129,255,40,174,128,255,41,175,127,255,42,176,127,255,44,177,126,255,45,178,125,255,46,179,124,255,47,180,124,255,49,181,123,255,50,182,122,255,52,182,121,255,53,183,121,255,55,184,120,255,56,185,119,255,58,186,118,255,59,187,117,255,61,188,116,255,63,188,115,255,64,189,114,255,66,190,113,255,68,191,112,255,70,192,111,255,72,193,110,255,74,193,109,255,76,194,108,255,78,195,107,255,80,196,106,255,82,197,105,255,84,197,104,255,86,198,103,255,88,199,101,255,90,200,100,255,92,200,99,255,94,201,98,255,96,202,96,255,99,203,95,255,101,203,94,255,103,204,92,255,105,205,91,255,108,205,90,255,110,206,88,255,112,207,87,255,115,208,86,255,117,208,84,255,119,209,83,255,122,209,81,255,124,210,80,255,127,211,78,255,129,211,77,255,132,212,75,255,134,213,73,255,137,213,72,255,139,214,70,255,142,214,69,255,144,215,67,255,147,215,65,255,149,216,64,255,152,216,62,255,155,217,60,255,157,217,59,255,160,218,57,255,162,218,55,255,165,219,54,255,168,219,52,255,170,220,50,255,173,220,48,255,176,221,47,255,178,221,45,255,181,222,43,255,184,222,41,255,186,222,40,255,189,223,38,255,192,223,37,255,194,223,35,255,197,224,33,255,200,224,32,255,202,225,31,255,205,225,29,255,208,225,28,255,210,226,27,255,213,226,26,255,216,226,25,255,218,227,25,255,221,227,24,255,223,227,24,255,226,228,24,255,229,228,25,255,231,228,25,255,234,229,26,255,236,229,27,255,239,229,28,255,241,229,29,255,244,230,30,255,246,230,32,255,248,230,33,255,251,231,35,255,253,231,37,255]),
"inferno": new Uint8Array([0,0,4,255,1,0,5,255,1,1,6,255,1,1,8,255,2,1,10,255,2,2,12,255,2,2,14,255,3,2,16,255,4,3,18,255,4,3,20,255,5,4,23,255,6,4,25,255,7,5,27,255,8,5,29,255,9,6,31,255,10,7,34,255,11,7,36,255,12,8,38,255,13,8,41,255,14,9,43,255,16,9,45,255,17,10,48,255,18,10,50,255,20,11,52,255,21,11,55,255,22,11,57,255,24,12,60,255,25,12,62,255,27,12,65,255,28,12,67,255,30,12,69,255,31,12,72,255,33,12,74,255,35,12,76,255,36,12,79,255,38,12,81,255,40,11,83,255,41,11,85,255,43,11,87,255,45,11,89,255,47,10,91,255,49,10,92,255,50,10,94,255,52,10,95,255,54,9,97,255,56,9,98,255,57,9,99,255,59,9,100,255,61,9,101,255,62,9,102,255,64,10,103,255,66,10,104,255,68,10,104,255,69,10,105,255,71,11,106,255,73,11,106,255,74,12,107,255,76,12,107,255,77,13,108,255,79,13,108,255,81,14,108,255,82,14,109,255,84,15,109,255,85,15,109,255,87,16,110,255,89,16,110,255,90,17,110,255,92,18,110,255,93,18,110,255,95,19,110,255,97,19,110,255,98,20,110,255,100,21,110,255,101,21,110,255,103,22,110,255,105,22,110,255,106,23,110,255,108,24,110,255,109,24,110,255,111,25,110,255,113,25,110,255,114,26,110,255,116,26,110,255,117,27,110,255,119,28,109,255,120,28,109,255,122,29,109,255,124,29,109,255,125,30,109,255,127,30,108,255,128,31,108,255,130,32,108,255,132,32,107,255,133,33,107,255,135,33,107,255,136,34,106,255,138,34,106,255,140,35,105,255,141,35,105,255,143,36,105,255,144,37,104,255,146,37,104,255,147,38,103,255,149,38,103,255,151,39,102,255,152,39,102,255,154,40,101,255,155,41,100,255,157,41,100,255,159,42,99,255,160,42,99,255,162,43,98,255,163,44,97,255,165,44,96,255,166,45,96,255,168,46,95,255,169,46,94,255,171,47,94,255,173,48,93,255,174,48,92,255,176,49,91,255,177,50,90,255,179,50,90,255,180,51,89,255,182,52,88,255,183,53,87,255,185,53,86,255,186,54,85,255,188,55,84,255,189,56,83,255,191,57,82,255,192,58,81,255,193,58,80,255,195,59,79,255,196,60,78,255,198,61,77,255,199,62,76,255,200,63,75,255,202,64,74,255,203,65,73,255,204,66,72,255,206,67,71,255,207,68,70,255,208,69,69,255,210,70,68,255,211,71,67,255,212,72,66,255,213,74,65,255,215,75,63,255,216,76,62,255,217,77,61,255,218,78,60,255,219,80,59,255,221,81,58,255,222,82,56,255,223,83,55,255,224,85,54,255,225,86,53,255,226,87,52,255,227,89,51,255,228,90,49,255,229,92,48,255,230,93,47,255,231,94,46,255,232,96,45,255,233,97,43,255,234,99,42,255,235,100,41,255,235,102,40,255,236,103,38,255,237,105,37,255,238,106,36,255,239,108,35,255,239,110,33,255,240,111,32,255,241,113,31,255,241,115,29,255,242,116,28,255,243,118,27,255,243,120,25,255,244,121,24,255,245,123,23,255,245,125,21,255,246,126,20,255,246,128,19,255,247,130,18,255,247,132,16,255,248,133,15,255,248,135,14,255,248,137,12,255,249,139,11,255,249,140,10,255,249,142,9,255,250,144,8,255,250,146,7,255,250,148,7,255,251,150,6,255,251,151,6,255,251,153,6,255,251,155,6,255,251,157,7,255,252,159,7,255,252,161,8,255,252,163,9,255,252,165,10,255,252,166,12,255,252,168,13,255,252,170,15,255,252,172,17,255,252,174,18,255,252,176,20,255,252,178,22,255,252,180,24,255,251,182,26,255,251,184,29,255,251,186,31,255,251,188,33,255,251,190,35,255,250,192,38,255,250,194,40,255,250,196,42,255,250,198,45,255,249,199,47,255,249,201,50,255,249,203,53,255,248,205,55,255,248,207,58,255,247,209,61,255,247,211,64,255,246,213,67,255,246,215,70,255,245,217,73,255,245,219,76,255,244,221,79,255,244,223,83,255,244,225,86,255,243,227,90,255,243,229,93,255,242,230,97,255,242,232,101,255,242,234,105,255,241,236,109,255,241,237,113,255,241,239,117,255,241,241,121,255,242,242,125,255,242,244,130,255,243,245,134,255,243,246,138,255,244,248,142,255,245,249,146,255,246,250,150,255,248,251,154,255,249,252,157,255,250,253,161,255,252,255,164,255]),
"rainbow": {
colors: ["#96005A","#0000C8","#0019FF","#0098FF","#2CFF96","#97FF00","#FFEA00","#FF6F00","#FF0000"],
positions: [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1]
},
"jet": {
colors: ["#000083","#003CAA","#05FFFF","#FFFF00","#FA0000","#800000"],
positions: [0, 0.125, 0.375, 0.625, 0.875, 1]
},
"hsv": {
colors: ["#ff0000","#fdff02","#f7ff02","#00fc04","#00fc0a","#01f9ff","#0200fd","#0800fd","#ff00fb","#ff00f5","#ff0006"],
positions: [0,0.169,0.173,0.337,0.341,0.506,0.671,0.675,0.839,0.843,1]
},
"hot": {
colors: ["#000000","#e60000","#ffd200","#ffffff"],
positions: [0,0.3,0.6,1]
},
"cool": {
colors: ["#00ffff","#ff00ff"],
positions: [0,1]
},
"spring": {
colors: ["#ff00ff","#ffff00"],
positions: [0,1]
},
"summer": {
colors: ["#008066","#ffff66"],
positions: [0,1]
},
"autumn": {
colors: ["#ff0000","#ffff00"],
positions: [0,1]
},
"winter": {
colors: ["#0000ff","#00ff80"],
positions: [0,1]
},
"bone": {
colors: ["#000000","#545474","#a9c8c8","#ffffff"],
positions: [0,0.376,0.753,1]
},
"copper": {
colors: ["#000000","#ffa066","#ffc77f"],
positions: [0,0.804,1]
},
"greys": {
colors: ["#000000","#ffffff"],
positions: [0,1]
},
"yignbu": {
colors: ["#081d58","#253494","#225ea8","#1d91c0","#41b6c4","#7fcdbb","#c7e9b4","#edf8d9","#ffffd9"],
positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
},
"greens": {
colors: ["#00441b","#006d2c","#238b45","#41ab5d","#74c476","#a1d99b","#c7e9c0","#e5f5e0","#f7fcf5"],
positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
},
"yiorrd": {
colors: ["#800026","#bd0026","#e31a1c","#fc4e2a","#fd8d3c","#feb24c","#fed976","#ffeda0","#ffffcc"],
positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
},
"bluered": {
colors: ["#0000ff","#ff0000"],
positions: [0,1]
},
"rdbu": {
colors: ["#050aac","#6a89f7","#bebebe","#dcaa84","#e6915a","#b20a1c"],
positions: [0,0.35,0.5,0.6,0.7,1]
},
"picnic": {
colors: ["#0000ff","#3399ff","#66ccff","#99ccff","#ccccff","#ffffff","#ffccff","#ff99ff","#ff66cc","#ff6666","#ff0000"],
positions: [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
},
"portland": {
colors: ["#0c3383","#0a88ba","#f2d338","#f28f38","#d91e1e"],
positions: [0,0.25,0.5,0.75,1]
},
"blackbody": {
colors: ["#000000","#e60000","#e6d200","#ffffff","#a0c8ff"],
positions: [0,0.2,0.4,0.7,1]
},
"earth": {
colors: ["#000082","#00b4b4","#28d228","#e6e632","#784614","#ffffff"],
positions: [0,0.1,0.2,0.4,0.6,1]
},
"electric": {
colors: ["#000000","#1e0064","#780064","#a05a00","#e6c800","#fffadc"],
positions: [0,0.15,0.4,0.6,0.8,1]
},
"magma": new Uint8Array([0,0,4,255,1,0,5,255,1,1,6,255,1,1,8,255,2,1,9,255,2,2,11,255,2,2,13,255,3,3,15,255,3,3,18,255,4,4,20,255,5,4,22,255,6,5,24,255,6,5,26,255,7,6,28,255,8,7,30,255,9,7,32,255,10,8,34,255,11,9,36,255,12,9,38,255,13,10,41,255,14,11,43,255,16,11,45,255,17,12,47,255,18,13,49,255,19,13,52,255,20,14,54,255,21,14,56,255,22,15,59,255,24,15,61,255,25,16,63,255,26,16,66,255,28,16,68,255,29,17,71,255,30,17,73,255,32,17,75,255,33,17,78,255,34,17,80,255,36,18,83,255,37,18,85,255,39,18,88,255,41,17,90,255,42,17,92,255,44,17,95,255,45,17,97,255,47,17,99,255,49,17,101,255,51,16,103,255,52,16,105,255,54,16,107,255,56,16,108,255,57,15,110,255,59,15,112,255,61,15,113,255,63,15,114,255,64,15,116,255,66,15,117,255,68,15,118,255,69,16,119,255,71,16,120,255,73,16,120,255,74,16,121,255,76,17,122,255,78,17,123,255,79,18,123,255,81,18,124,255,82,19,124,255,84,19,125,255,86,20,125,255,87,21,126,255,89,21,126,255,90,22,126,255,92,22,127,255,93,23,127,255,95,24,127,255,96,24,128,255,98,25,128,255,100,26,128,255,101,26,128,255,103,27,128,255,104,28,129,255,106,28,129,255,107,29,129,255,109,29,129,255,110,30,129,255,112,31,129,255,114,31,129,255,115,32,129,255,117,33,129,255,118,33,129,255,120,34,129,255,121,34,130,255,123,35,130,255,124,35,130,255,126,36,130,255,128,37,130,255,129,37,129,255,131,38,129,255,132,38,129,255,134,39,129,255,136,39,129,255,137,40,129,255,139,41,129,255,140,41,129,255,142,42,129,255,144,42,129,255,145,43,129,255,147,43,128,255,148,44,128,255,150,44,128,255,152,45,128,255,153,45,128,255,155,46,127,255,156,46,127,255,158,47,127,255,160,47,127,255,161,48,126,255,163,48,126,255,165,49,126,255,166,49,125,255,168,50,125,255,170,51,125,255,171,51,124,255,173,52,124,255,174,52,123,255,176,53,123,255,178,53,123,255,179,54,122,255,181,54,122,255,183,55,121,255,184,55,121,255,186,56,120,255,188,57,120,255,189,57,119,255,191,58,119,255,192,58,118,255,194,59,117,255,196,60,117,255,197,60,116,255,199,61,115,255,200,62,115,255,202,62,114,255,204,63,113,255,205,64,113,255,207,64,112,255,208,65,111,255,210,66,111,255,211,67,110,255,213,68,109,255,214,69,108,255,216,69,108,255,217,70,107,255,219,71,106,255,220,72,105,255,222,73,104,255,223,74,104,255,224,76,103,255,226,77,102,255,227,78,101,255,228,79,100,255,229,80,100,255,231,82,99,255,232,83,98,255,233,84,98,255,234,86,97,255,235,87,96,255,236,88,96,255,237,90,95,255,238,91,94,255,239,93,94,255,240,95,94,255,241,96,93,255,242,98,93,255,242,100,92,255,243,101,92,255,244,103,92,255,244,105,92,255,245,107,92,255,246,108,92,255,246,110,92,255,247,112,92,255,247,114,92,255,248,116,92,255,248,118,92,255,249,120,93,255,249,121,93,255,249,123,93,255,250,125,94,255,250,127,94,255,250,129,95,255,251,131,95,255,251,133,96,255,251,135,97,255,252,137,97,255,252,138,98,255,252,140,99,255,252,142,100,255,252,144,101,255,253,146,102,255,253,148,103,255,253,150,104,255,253,152,105,255,253,154,106,255,253,155,107,255,254,157,108,255,254,159,109,255,254,161,110,255,254,163,111,255,254,165,113,255,254,167,114,255,254,169,115,255,254,170,116,255,254,172,118,255,254,174,119,255,254,176,120,255,254,178,122,255,254,180,123,255,254,182,124,255,254,183,126,255,254,185,127,255,254,187,129,255,254,189,130,255,254,191,132,255,254,193,133,255,254,194,135,255,254,196,136,255,254,198,138,255,254,200,140,255,254,202,141,255,254,204,143,255,254,205,144,255,254,207,146,255,254,209,148,255,254,211,149,255,254,213,151,255,254,215,153,255,254,216,154,255,253,218,156,255,253,220,158,255,253,222,160,255,253,224,161,255,253,226,163,255,253,227,165,255,253,229,167,255,253,231,169,255,253,233,170,255,253,235,172,255,252,236,174,255,252,238,176,255,252,240,178,255,252,242,180,255,252,244,182,255,252,246,184,255,252,247,185,255,252,249,187,255,252,251,189,255,252,253,191,255]),
"plasma": new Uint8Array([13,8,135,255,16,7,136,255,19,7,137,255,22,7,138,255,25,6,140,255,27,6,141,255,29,6,142,255,32,6,143,255,34,6,144,255,36,6,145,255,38,5,145,255,40,5,146,255,42,5,147,255,44,5,148,255,46,5,149,255,47,5,150,255,49,5,151,255,51,5,151,255,53,4,152,255,55,4,153,255,56,4,154,255,58,4,154,255,60,4,155,255,62,4,156,255,63,4,156,255,65,4,157,255,67,3,158,255,68,3,158,255,70,3,159,255,72,3,159,255,73,3,160,255,75,3,161,255,76,2,161,255,78,2,162,255,80,2,162,255,81,2,163,255,83,2,163,255,85,2,164,255,86,1,164,255,88,1,164,255,89,1,165,255,91,1,165,255,92,1,166,255,94,1,166,255,96,1,166,255,97,0,167,255,99,0,167,255,100,0,167,255,102,0,167,255,103,0,168,255,105,0,168,255,106,0,168,255,108,0,168,255,110,0,168,255,111,0,168,255,113,0,168,255,114,1,168,255,116,1,168,255,117,1,168,255,119,1,168,255,120,1,168,255,122,2,168,255,123,2,168,255,125,3,168,255,126,3,168,255,128,4,168,255,129,4,167,255,131,5,167,255,132,5,167,255,134,6,166,255,135,7,166,255,136,8,166,255,138,9,165,255,139,10,165,255,141,11,165,255,142,12,164,255,143,13,164,255,145,14,163,255,146,15,163,255,148,16,162,255,149,17,161,255,150,19,161,255,152,20,160,255,153,21,159,255,154,22,159,255,156,23,158,255,157,24,157,255,158,25,157,255,160,26,156,255,161,27,155,255,162,29,154,255,163,30,154,255,165,31,153,255,166,32,152,255,167,33,151,255,168,34,150,255,170,35,149,255,171,36,148,255,172,38,148,255,173,39,147,255,174,40,146,255,176,41,145,255,177,42,144,255,178,43,143,255,179,44,142,255,180,46,141,255,181,47,140,255,182,48,139,255,183,49,138,255,184,50,137,255,186,51,136,255,187,52,136,255,188,53,135,255,189,55,134,255,190,56,133,255,191,57,132,255,192,58,131,255,193,59,130,255,194,60,129,255,195,61,128,255,196,62,127,255,197,64,126,255,198,65,125,255,199,66,124,255,200,67,123,255,201,68,122,255,202,69,122,255,203,70,121,255,204,71,120,255,204,73,119,255,205,74,118,255,206,75,117,255,207,76,116,255,208,77,115,255,209,78,114,255,210,79,113,255,211,81,113,255,212,82,112,255,213,83,111,255,213,84,110,255,214,85,109,255,215,86,108,255,216,87,107,255,217,88,106,255,218,90,106,255,218,91,105,255,219,92,104,255,220,93,103,255,221,94,102,255,222,95,101,255,222,97,100,255,223,98,99,255,224,99,99,255,225,100,98,255,226,101,97,255,226,102,96,255,227,104,95,255,228,105,94,255,229,106,93,255,229,107,93,255,230,108,92,255,231,110,91,255,231,111,90,255,232,112,89,255,233,113,88,255,233,114,87,255,234,116,87,255,235,117,86,255,235,118,85,255,236,119,84,255,237,121,83,255,237,122,82,255,238,123,81,255,239,124,81,255,239,126,80,255,240,127,79,255,240,128,78,255,241,129,77,255,241,131,76,255,242,132,75,255,243,133,75,255,243,135,74,255,244,136,73,255,244,137,72,255,245,139,71,255,245,140,70,255,246,141,69,255,246,143,68,255,247,144,68,255,247,145,67,255,247,147,66,255,248,148,65,255,248,149,64,255,249,151,63,255,249,152,62,255,249,154,62,255,250,155,61,255,250,156,60,255,250,158,59,255,251,159,58,255,251,161,57,255,251,162,56,255,252,163,56,255,252,165,55,255,252,166,54,255,252,168,53,255,252,169,52,255,253,171,51,255,253,172,51,255,253,174,50,255,253,175,49,255,253,177,48,255,253,178,47,255,253,180,47,255,253,181,46,255,254,183,45,255,254,184,44,255,254,186,44,255,254,187,43,255,254,189,42,255,254,190,42,255,254,192,41,255,253,194,41,255,253,195,40,255,253,197,39,255,253,198,39,255,253,200,39,255,253,202,38,255,253,203,38,255,252,205,37,255,252,206,37,255,252,208,37,255,252,210,37,255,251,211,36,255,251,213,36,255,251,215,36,255,250,216,36,255,250,218,36,255,249,220,36,255,249,221,37,255,248,223,37,255,248,225,37,255,247,226,37,255,247,228,37,255,246,230,38,255,246,232,38,255,245,233,38,255,245,235,39,255,244,237,39,255,243,238,39,255,243,240,39,255,242,242,39,255,241,244,38,255,241,245,37,255,240,247,36,255,240,249,33,255]),
"redblue": {
colors: ["#ff0000", "#0000ff"],
positions: [0,1]
},
"coolwarm": {
colors: ["#0000ff", "#ffffff", "#ff0000"],
positions: [0,0.5,1]
},
"diverging_1": {
colors: ["#400040","#3b004d","#36005b","#320068","#2d0076","#290084","#240091","#20009f","#1b00ad","#1600ba","#1200c8","#0d00d6","#0900e3","#0400f1","#0000ff","#0217ff","#042eff","#0645ff","#095cff","#0b73ff","#0d8bff","#10a2ff","#12b9ff","#14d0ff","#17e7ff","#19ffff","#3fffff","#66ffff","#8cffff","#b2ffff","#d8ffff","#ffffff","#ffffd4","#ffffaa","#ffff7f","#ffff54","#ffff2a","#ffff00","#ffed00","#ffdd00","#ffcc00","#ffba00","#ffaa00","#ff9900","#ff8700","#ff7700","#ff6600","#ff5400","#ff4400","#ff3300","#ff2100","#ff1100","#ff0000","#ff0017","#ff002e","#ff0045","#ff005c","#ff0073","#ff008b","#ff00a2","#ff00b9","#ff00d0","#ff00e7","#ff00ff"],
positions: [0.0,0.01587301587,0.03174603174,0.04761904761,0.06349206348,0.07936507935,0.09523809522,0.11111111109,0.12698412696,0.14285714283,0.15873015870,0.17460317457,0.19047619044,0.20634920631,0.22222222218,0.23809523805,0.25396825392,0.26984126979,0.28571428566,0.30158730153,0.31746031740,0.33333333327,0.34920634914,0.36507936501,0.38095238088,0.39682539675,0.41269841262,0.42857142849,0.44444444436,0.46031746023,0.47619047610,0.49206349197,0.50793650784,0.52380952371,0.53968253958,0.55555555545,0.57142857132,0.58730158719,0.60317460306,0.61904761893,0.63492063480,0.65079365067,0.66666666654,0.68253968241,0.69841269828,0.71428571415,0.73015873002,0.74603174589,0.76190476176,0.77777777763,0.79365079350,0.80952380937,0.82539682524,0.84126984111,0.85714285698,0.87301587285,0.88888888872,0.90476190459,0.92063492046,0.93650793633,0.95238095220,0.96825396807,0.98412698394,1]
},
"diverging_2": {
colors: ["#000000","#030aff","#204aff","#3c8aff","#77c4ff","#f0ffff","#f0ffff","#f2ff7f","#ffff00","#ff831e","#ff083d","#ff00ff"],
positions: [0,0.0000000001,0.1,0.2,0.3333,0.4666,0.5333,0.6666,0.8,0.9,0.999999999999,1]
},
"blackwhite": {
colors: ["#000000","#ffffff"],
positions: [0,1]
},
"ylgnbu": {
colors: ["#081d58","#253494","#225ea8","#1d91c0","#41b6c4","#7fcdbb","#c7e9b4","#edf8d9","#ffffd9"],
positions: [1,0.875,0.75,0.625,0.5,0.375,0.25,0.125,0]
},
"ylorrd": {
colors: ["#800026","#bd0026","#e31a1c","#fc4e2a","#fd8d3c","#feb24c","#fed976","#ffeda0","#ffffcc"],
positions: [1,0.875,0.75,0.625,0.5,0.375,0.25,0.125,0]
},
"twilight": {
colors: ["#E2D9E2", "#E0D9E2", "#DDD9E0", "#DAD8DF", "#D6D7DD", "#D2D5DB", "#CDD3D8", "#C8D0D6", "#C2CED4", "#BCCBD1", "#B6C8CF", "#B0C5CD", "#AAC2CC", "#A4BECA", "#9EBBC9", "#99B8C8", "#93B4C6", "#8EB1C5", "#89ADC5", "#85A9C4", "#80A5C3", "#7CA2C2", "#789EC2", "#759AC1", "#7196C1", "#6E92C0", "#6C8EBF", "#698ABF", "#6786BE", "#6682BD", "#647DBC", "#6379BB", "#6275BA", "#6170B9", "#606CB8", "#6067B6", "#5F62B4", "#5F5EB3", "#5F59B1", "#5E54AE", "#5E4FAC", "#5E4BA9", "#5E46A6", "#5D41A3", "#5D3CA0", "#5C379C", "#5B3298", "#5A2E93", "#59298E", "#572588", "#562182", "#531E7C", "#511A75", "#4E186F", "#4B1668", "#471461", "#44135A", "#411254", "#3D114E", "#3A1149", "#371144", "#351140", "#33113C", "#311339", "#301437", "#331237", "#351138", "#381139", "#3B113B", "#3F123D", "#43123E", "#481341", "#4D1443", "#521545", "#571647", "#5C1749", "#61184B", "#67194C", "#6C1B4E", "#711D4F", "#761F4F", "#7B2150", "#802350", "#852650", "#8A2950", "#8E2C50", "#922F50", "#963350", "#9A3750", "#9E3B50", "#A13F50", "#A54350", "#A84750", "#AB4B50", "#AE5051", "#B15452", "#B35953", "#B65D54", "#B86255", "#BA6657", "#BC6B59", "#BE705B", "#C0755E", "#C27A61", "#C37F64", "#C58468", "#C6896C", "#C78E71", "#C89275", "#C9977B", "#CA9C80", "#CCA186", "#CDA68C", "#CEAB92", "#CFAF99", "#D1B4A0", "#D2B8A7", "#D4BDAD", "#D6C1B4", "#D8C5BB", "#D9C9C2", "#DBCCC8", "#DDD0CE", "#DED3D3", "#DFD5D8", "#E0D7DB", "#E1D8DF", "#E2D9E1"],
positions: [0.0000000000, 0.0078740157, 0.0157480315, 0.0236220472, 0.0314960630, 0.0393700787, 0.0472440945, 0.0551181102, 0.0629921260, 0.0708661417, 0.0787401575, 0.0866141732, 0.0944881890, 0.1023622047, 0.1102362205, 0.1181102362, 0.1259842520, 0.1338582677, 0.1417322835, 0.1496062992, 0.1574803150, 0.1653543307, 0.1732283465, 0.1811023622, 0.1889763780, 0.1968503937, 0.2047244094, 0.2125984252, 0.2204724409, 0.2283464567, 0.2362204724, 0.2440944882, 0.2519685039, 0.2598425197, 0.2677165354, 0.2755905512, 0.2834645669, 0.2913385827, 0.2992125984, 0.3070866142, 0.3149606299, 0.3228346457, 0.3307086614, 0.3385826772, 0.3464566929, 0.3543307087, 0.3622047244, 0.3700787402, 0.3779527559, 0.3858267717, 0.3937007874, 0.4015748031, 0.4094488189, 0.4173228346, 0.4251968504, 0.4330708661, 0.4409448819, 0.4488188976, 0.4566929134, 0.4645669291, 0.4724409449, 0.4803149606, 0.4881889764, 0.4960629921, 0.5039370079, 0.5118110236, 0.5196850394, 0.5275590551, 0.5354330709, 0.5433070866, 0.5511811024, 0.5590551181, 0.5669291339, 0.5748031496, 0.5826771654, 0.5905511811, 0.5984251969, 0.6062992126, 0.6141732283, 0.6220472441, 0.6299212598, 0.6377952756, 0.6456692913, 0.6535433071, 0.6614173228, 0.6692913386, 0.6771653543, 0.6850393701, 0.6929133858, 0.7007874016, 0.7086614173, 0.7165354331, 0.7244094488, 0.7322834646, 0.7401574803, 0.7480314961, 0.7559055118, 0.7637795276, 0.7716535433, 0.7795275591, 0.7874015748, 0.7952755906, 0.8031496063, 0.8110236220, 0.8188976378, 0.8267716535, 0.8346456693, 0.8425196850, 0.8503937008, 0.8582677165, 0.8661417323, 0.8740157480, 0.8818897638, 0.8897637795, 0.8976377953, 0.9055118110, 0.9133858268, 0.9212598425, 0.9291338583, 0.9370078740, 0.9448818898, 0.9527559055, 0.9606299213, 0.9685039370, 0.9763779528, 0.9842519685, 0.9921259843, 1.0000000000]
},
"twilight_shifted": {
colors: ["#301437", "#32123A", "#34113E", "#361142", "#391146", "#3C114B", "#3F1251", "#421257", "#46145E", "#491564", "#4C176B", "#4F1972", "#521C79", "#551F7F", "#572385", "#58278B", "#5A2B90", "#5B3095", "#5C359A", "#5D3A9E", "#5D3EA1", "#5E43A5", "#5E48A8", "#5E4DAB", "#5E52AD", "#5F57B0", "#5F5BB2", "#5F60B4", "#5F65B5", "#6069B7", "#606EB8", "#6172BA", "#6277BB", "#637BBC", "#657FBD", "#6684BD", "#6888BE", "#6B8CBF", "#6D90C0", "#7094C0", "#7398C1", "#769CC1", "#7AA0C2", "#7EA4C3", "#82A7C3", "#87ABC4", "#8CAFC5", "#91B2C6", "#96B6C7", "#9CB9C8", "#A1BDC9", "#A7C0CB", "#ADC3CD", "#B3C6CE", "#B9C9D0", "#BFCCD3", "#C5CFD5", "#CBD2D7", "#D0D4D9", "#D4D6DC", "#D8D8DE", "#DCD9DF", "#DED9E1", "#E1D9E2", "#E2D9E1", "#E1D8DF", "#E0D7DB", "#DFD5D8", "#DED3D3", "#DDD0CE", "#DBCCC8", "#D9C9C2", "#D8C5BB", "#D6C1B4", "#D4BDAD", "#D2B8A7", "#D1B4A0", "#CFAF99", "#CEAB92", "#CDA68C", "#CCA186", "#CA9C80", "#C9977B", "#C89275", "#C78E71", "#C6896C", "#C58468", "#C37F64", "#C27A61", "#C0755E", "#BE705B", "#BC6B59", "#BA6657", "#B86255", "#B65D54", "#B35953", "#B15452", "#AE5051", "#AB4B50", "#A84750", "#A54350", "#A13F50", "#9E3B50", "#9A3750", "#963350", "#922F50", "#8E2C50", "#8A2950", "#852650", "#802350", "#7B2150", "#761F4F", "#711D4F", "#6C1B4E", "#67194C", "#61184B", "#5C1749", "#571647", "#521545", "#4D1443", "#481341", "#43123E", "#3F123D", "#3B113B", "#381139", "#351138", "#331237", "#301437"],
positions: [0.0000000000, 0.0078740157, 0.0157480315, 0.0236220472, 0.0314960630, 0.0393700787, 0.0472440945, 0.0551181102, 0.0629921260, 0.0708661417, 0.0787401575, 0.0866141732, 0.0944881890, 0.1023622047, 0.1102362205, 0.1181102362, 0.1259842520, 0.1338582677, 0.1417322835, 0.1496062992, 0.1574803150, 0.1653543307, 0.1732283465, 0.1811023622, 0.1889763780, 0.1968503937, 0.2047244094, 0.2125984252, 0.2204724409, 0.2283464567, 0.2362204724, 0.2440944882, 0.2519685039, 0.2598425197, 0.2677165354, 0.2755905512, 0.2834645669, 0.2913385827, 0.2992125984, 0.3070866142, 0.3149606299, 0.3228346457, 0.3307086614, 0.3385826772, 0.3464566929, 0.3543307087, 0.3622047244, 0.3700787402, 0.3779527559, 0.3858267717, 0.3937007874, 0.4015748031, 0.4094488189, 0.4173228346, 0.4251968504, 0.4330708661, 0.4409448819, 0.4488188976, 0.4566929134, 0.4645669291, 0.4724409449, 0.4803149606, 0.4881889764, 0.4960629921, 0.5039370079, 0.5118110236, 0.5196850394, 0.5275590551, 0.5354330709, 0.5433070866, 0.5511811024, 0.5590551181, 0.5669291339, 0.5748031496, 0.5826771654, 0.5905511811, 0.5984251969, 0.6062992126, 0.6141732283, 0.6220472441, 0.6299212598, 0.6377952756, 0.6456692913, 0.6535433071, 0.6614173228, 0.6692913386, 0.6771653543, 0.6850393701, 0.6929133858, 0.7007874016, 0.7086614173, 0.7165354331, 0.7244094488, 0.7322834646, 0.7401574803, 0.7480314961, 0.7559055118, 0.7637795276, 0.7716535433, 0.7795275591, 0.7874015748, 0.7952755906, 0.8031496063, 0.8110236220, 0.8188976378, 0.8267716535, 0.8346456693, 0.8425196850, 0.8503937008, 0.8582677165, 0.8661417323, 0.8740157480, 0.8818897638, 0.8897637795, 0.8976377953, 0.9055118110, 0.9133858268, 0.9212598425, 0.9291338583, 0.9370078740, 0.9448818898, 0.9527559055, 0.9606299213, 0.9685039370, 0.9763779528, 0.9842519685, 0.9921259843, 1.0000000000]
},
};
|
replacing double quotes with single
|
src/colorscales.js
|
replacing double quotes with single
|
<ide><path>rc/colorscales.js
<ide> export const colorscales = {
<del> "viridis": new Uint8Array([68,1,84,255,68,2,86,255,69,4,87,255,69,5,89,255,70,7,90,255,70,8,92,255,70,10,93,255,70,11,94,255,71,13,96,255,71,14,97,255,71,16,99,255,71,17,100,255,71,19,101,255,72,20,103,255,72,22,104,255,72,23,105,255,72,24,106,255,72,26,108,255,72,27,109,255,72,28,110,255,72,29,111,255,72,31,112,255,72,32,113,255,72,33,115,255,72,35,116,255,72,36,117,255,72,37,118,255,72,38,119,255,72,40,120,255,72,41,121,255,71,42,122,255,71,44,122,255,71,45,123,255,71,46,124,255,71,47,125,255,70,48,126,255,70,50,126,255,70,51,127,255,70,52,128,255,69,53,129,255,69,55,129,255,69,56,130,255,68,57,131,255,68,58,131,255,68,59,132,255,67,61,132,255,67,62,133,255,66,63,133,255,66,64,134,255,66,65,134,255,65,66,135,255,65,68,135,255,64,69,136,255,64,70,136,255,63,71,136,255,63,72,137,255,62,73,137,255,62,74,137,255,62,76,138,255,61,77,138,255,61,78,138,255,60,79,138,255,60,80,139,255,59,81,139,255,59,82,139,255,58,83,139,255,58,84,140,255,57,85,140,255,57,86,140,255,56,88,140,255,56,89,140,255,55,90,140,255,55,91,141,255,54,92,141,255,54,93,141,255,53,94,141,255,53,95,141,255,52,96,141,255,52,97,141,255,51,98,141,255,51,99,141,255,50,100,142,255,50,101,142,255,49,102,142,255,49,103,142,255,49,104,142,255,48,105,142,255,48,106,142,255,47,107,142,255,47,108,142,255,46,109,142,255,46,110,142,255,46,111,142,255,45,112,142,255,45,113,142,255,44,113,142,255,44,114,142,255,44,115,142,255,43,116,142,255,43,117,142,255,42,118,142,255,42,119,142,255,42,120,142,255,41,121,142,255,41,122,142,255,41,123,142,255,40,124,142,255,40,125,142,255,39,126,142,255,39,127,142,255,39,128,142,255,38,129,142,255,38,130,142,255,38,130,142,255,37,131,142,255,37,132,142,255,37,133,142,255,36,134,142,255,36,135,142,255,35,136,142,255,35,137,142,255,35,138,141,255,34,139,141,255,34,140,141,255,34,141,141,255,33,142,141,255,33,143,141,255,33,144,141,255,33,145,140,255,32,146,140,255,32,146,140,255,32,147,140,255,31,148,140,255,31,149,139,255,31,150,139,255,31,151,139,255,31,152,139,255,31,153,138,255,31,154,138,255,30,155,138,255,30,156,137,255,30,157,137,255,31,158,137,255,31,159,136,255,31,160,136,255,31,161,136,255,31,161,135,255,31,162,135,255,32,163,134,255,32,164,134,255,33,165,133,255,33,166,133,255,34,167,133,255,34,168,132,255,35,169,131,255,36,170,131,255,37,171,130,255,37,172,130,255,38,173,129,255,39,173,129,255,40,174,128,255,41,175,127,255,42,176,127,255,44,177,126,255,45,178,125,255,46,179,124,255,47,180,124,255,49,181,123,255,50,182,122,255,52,182,121,255,53,183,121,255,55,184,120,255,56,185,119,255,58,186,118,255,59,187,117,255,61,188,116,255,63,188,115,255,64,189,114,255,66,190,113,255,68,191,112,255,70,192,111,255,72,193,110,255,74,193,109,255,76,194,108,255,78,195,107,255,80,196,106,255,82,197,105,255,84,197,104,255,86,198,103,255,88,199,101,255,90,200,100,255,92,200,99,255,94,201,98,255,96,202,96,255,99,203,95,255,101,203,94,255,103,204,92,255,105,205,91,255,108,205,90,255,110,206,88,255,112,207,87,255,115,208,86,255,117,208,84,255,119,209,83,255,122,209,81,255,124,210,80,255,127,211,78,255,129,211,77,255,132,212,75,255,134,213,73,255,137,213,72,255,139,214,70,255,142,214,69,255,144,215,67,255,147,215,65,255,149,216,64,255,152,216,62,255,155,217,60,255,157,217,59,255,160,218,57,255,162,218,55,255,165,219,54,255,168,219,52,255,170,220,50,255,173,220,48,255,176,221,47,255,178,221,45,255,181,222,43,255,184,222,41,255,186,222,40,255,189,223,38,255,192,223,37,255,194,223,35,255,197,224,33,255,200,224,32,255,202,225,31,255,205,225,29,255,208,225,28,255,210,226,27,255,213,226,26,255,216,226,25,255,218,227,25,255,221,227,24,255,223,227,24,255,226,228,24,255,229,228,25,255,231,228,25,255,234,229,26,255,236,229,27,255,239,229,28,255,241,229,29,255,244,230,30,255,246,230,32,255,248,230,33,255,251,231,35,255,253,231,37,255]),
<del> "inferno": new Uint8Array([0,0,4,255,1,0,5,255,1,1,6,255,1,1,8,255,2,1,10,255,2,2,12,255,2,2,14,255,3,2,16,255,4,3,18,255,4,3,20,255,5,4,23,255,6,4,25,255,7,5,27,255,8,5,29,255,9,6,31,255,10,7,34,255,11,7,36,255,12,8,38,255,13,8,41,255,14,9,43,255,16,9,45,255,17,10,48,255,18,10,50,255,20,11,52,255,21,11,55,255,22,11,57,255,24,12,60,255,25,12,62,255,27,12,65,255,28,12,67,255,30,12,69,255,31,12,72,255,33,12,74,255,35,12,76,255,36,12,79,255,38,12,81,255,40,11,83,255,41,11,85,255,43,11,87,255,45,11,89,255,47,10,91,255,49,10,92,255,50,10,94,255,52,10,95,255,54,9,97,255,56,9,98,255,57,9,99,255,59,9,100,255,61,9,101,255,62,9,102,255,64,10,103,255,66,10,104,255,68,10,104,255,69,10,105,255,71,11,106,255,73,11,106,255,74,12,107,255,76,12,107,255,77,13,108,255,79,13,108,255,81,14,108,255,82,14,109,255,84,15,109,255,85,15,109,255,87,16,110,255,89,16,110,255,90,17,110,255,92,18,110,255,93,18,110,255,95,19,110,255,97,19,110,255,98,20,110,255,100,21,110,255,101,21,110,255,103,22,110,255,105,22,110,255,106,23,110,255,108,24,110,255,109,24,110,255,111,25,110,255,113,25,110,255,114,26,110,255,116,26,110,255,117,27,110,255,119,28,109,255,120,28,109,255,122,29,109,255,124,29,109,255,125,30,109,255,127,30,108,255,128,31,108,255,130,32,108,255,132,32,107,255,133,33,107,255,135,33,107,255,136,34,106,255,138,34,106,255,140,35,105,255,141,35,105,255,143,36,105,255,144,37,104,255,146,37,104,255,147,38,103,255,149,38,103,255,151,39,102,255,152,39,102,255,154,40,101,255,155,41,100,255,157,41,100,255,159,42,99,255,160,42,99,255,162,43,98,255,163,44,97,255,165,44,96,255,166,45,96,255,168,46,95,255,169,46,94,255,171,47,94,255,173,48,93,255,174,48,92,255,176,49,91,255,177,50,90,255,179,50,90,255,180,51,89,255,182,52,88,255,183,53,87,255,185,53,86,255,186,54,85,255,188,55,84,255,189,56,83,255,191,57,82,255,192,58,81,255,193,58,80,255,195,59,79,255,196,60,78,255,198,61,77,255,199,62,76,255,200,63,75,255,202,64,74,255,203,65,73,255,204,66,72,255,206,67,71,255,207,68,70,255,208,69,69,255,210,70,68,255,211,71,67,255,212,72,66,255,213,74,65,255,215,75,63,255,216,76,62,255,217,77,61,255,218,78,60,255,219,80,59,255,221,81,58,255,222,82,56,255,223,83,55,255,224,85,54,255,225,86,53,255,226,87,52,255,227,89,51,255,228,90,49,255,229,92,48,255,230,93,47,255,231,94,46,255,232,96,45,255,233,97,43,255,234,99,42,255,235,100,41,255,235,102,40,255,236,103,38,255,237,105,37,255,238,106,36,255,239,108,35,255,239,110,33,255,240,111,32,255,241,113,31,255,241,115,29,255,242,116,28,255,243,118,27,255,243,120,25,255,244,121,24,255,245,123,23,255,245,125,21,255,246,126,20,255,246,128,19,255,247,130,18,255,247,132,16,255,248,133,15,255,248,135,14,255,248,137,12,255,249,139,11,255,249,140,10,255,249,142,9,255,250,144,8,255,250,146,7,255,250,148,7,255,251,150,6,255,251,151,6,255,251,153,6,255,251,155,6,255,251,157,7,255,252,159,7,255,252,161,8,255,252,163,9,255,252,165,10,255,252,166,12,255,252,168,13,255,252,170,15,255,252,172,17,255,252,174,18,255,252,176,20,255,252,178,22,255,252,180,24,255,251,182,26,255,251,184,29,255,251,186,31,255,251,188,33,255,251,190,35,255,250,192,38,255,250,194,40,255,250,196,42,255,250,198,45,255,249,199,47,255,249,201,50,255,249,203,53,255,248,205,55,255,248,207,58,255,247,209,61,255,247,211,64,255,246,213,67,255,246,215,70,255,245,217,73,255,245,219,76,255,244,221,79,255,244,223,83,255,244,225,86,255,243,227,90,255,243,229,93,255,242,230,97,255,242,232,101,255,242,234,105,255,241,236,109,255,241,237,113,255,241,239,117,255,241,241,121,255,242,242,125,255,242,244,130,255,243,245,134,255,243,246,138,255,244,248,142,255,245,249,146,255,246,250,150,255,248,251,154,255,249,252,157,255,250,253,161,255,252,255,164,255]),
<del> "rainbow": {
<del> colors: ["#96005A","#0000C8","#0019FF","#0098FF","#2CFF96","#97FF00","#FFEA00","#FF6F00","#FF0000"],
<add> viridis: new Uint8Array([68,1,84,255,68,2,86,255,69,4,87,255,69,5,89,255,70,7,90,255,70,8,92,255,70,10,93,255,70,11,94,255,71,13,96,255,71,14,97,255,71,16,99,255,71,17,100,255,71,19,101,255,72,20,103,255,72,22,104,255,72,23,105,255,72,24,106,255,72,26,108,255,72,27,109,255,72,28,110,255,72,29,111,255,72,31,112,255,72,32,113,255,72,33,115,255,72,35,116,255,72,36,117,255,72,37,118,255,72,38,119,255,72,40,120,255,72,41,121,255,71,42,122,255,71,44,122,255,71,45,123,255,71,46,124,255,71,47,125,255,70,48,126,255,70,50,126,255,70,51,127,255,70,52,128,255,69,53,129,255,69,55,129,255,69,56,130,255,68,57,131,255,68,58,131,255,68,59,132,255,67,61,132,255,67,62,133,255,66,63,133,255,66,64,134,255,66,65,134,255,65,66,135,255,65,68,135,255,64,69,136,255,64,70,136,255,63,71,136,255,63,72,137,255,62,73,137,255,62,74,137,255,62,76,138,255,61,77,138,255,61,78,138,255,60,79,138,255,60,80,139,255,59,81,139,255,59,82,139,255,58,83,139,255,58,84,140,255,57,85,140,255,57,86,140,255,56,88,140,255,56,89,140,255,55,90,140,255,55,91,141,255,54,92,141,255,54,93,141,255,53,94,141,255,53,95,141,255,52,96,141,255,52,97,141,255,51,98,141,255,51,99,141,255,50,100,142,255,50,101,142,255,49,102,142,255,49,103,142,255,49,104,142,255,48,105,142,255,48,106,142,255,47,107,142,255,47,108,142,255,46,109,142,255,46,110,142,255,46,111,142,255,45,112,142,255,45,113,142,255,44,113,142,255,44,114,142,255,44,115,142,255,43,116,142,255,43,117,142,255,42,118,142,255,42,119,142,255,42,120,142,255,41,121,142,255,41,122,142,255,41,123,142,255,40,124,142,255,40,125,142,255,39,126,142,255,39,127,142,255,39,128,142,255,38,129,142,255,38,130,142,255,38,130,142,255,37,131,142,255,37,132,142,255,37,133,142,255,36,134,142,255,36,135,142,255,35,136,142,255,35,137,142,255,35,138,141,255,34,139,141,255,34,140,141,255,34,141,141,255,33,142,141,255,33,143,141,255,33,144,141,255,33,145,140,255,32,146,140,255,32,146,140,255,32,147,140,255,31,148,140,255,31,149,139,255,31,150,139,255,31,151,139,255,31,152,139,255,31,153,138,255,31,154,138,255,30,155,138,255,30,156,137,255,30,157,137,255,31,158,137,255,31,159,136,255,31,160,136,255,31,161,136,255,31,161,135,255,31,162,135,255,32,163,134,255,32,164,134,255,33,165,133,255,33,166,133,255,34,167,133,255,34,168,132,255,35,169,131,255,36,170,131,255,37,171,130,255,37,172,130,255,38,173,129,255,39,173,129,255,40,174,128,255,41,175,127,255,42,176,127,255,44,177,126,255,45,178,125,255,46,179,124,255,47,180,124,255,49,181,123,255,50,182,122,255,52,182,121,255,53,183,121,255,55,184,120,255,56,185,119,255,58,186,118,255,59,187,117,255,61,188,116,255,63,188,115,255,64,189,114,255,66,190,113,255,68,191,112,255,70,192,111,255,72,193,110,255,74,193,109,255,76,194,108,255,78,195,107,255,80,196,106,255,82,197,105,255,84,197,104,255,86,198,103,255,88,199,101,255,90,200,100,255,92,200,99,255,94,201,98,255,96,202,96,255,99,203,95,255,101,203,94,255,103,204,92,255,105,205,91,255,108,205,90,255,110,206,88,255,112,207,87,255,115,208,86,255,117,208,84,255,119,209,83,255,122,209,81,255,124,210,80,255,127,211,78,255,129,211,77,255,132,212,75,255,134,213,73,255,137,213,72,255,139,214,70,255,142,214,69,255,144,215,67,255,147,215,65,255,149,216,64,255,152,216,62,255,155,217,60,255,157,217,59,255,160,218,57,255,162,218,55,255,165,219,54,255,168,219,52,255,170,220,50,255,173,220,48,255,176,221,47,255,178,221,45,255,181,222,43,255,184,222,41,255,186,222,40,255,189,223,38,255,192,223,37,255,194,223,35,255,197,224,33,255,200,224,32,255,202,225,31,255,205,225,29,255,208,225,28,255,210,226,27,255,213,226,26,255,216,226,25,255,218,227,25,255,221,227,24,255,223,227,24,255,226,228,24,255,229,228,25,255,231,228,25,255,234,229,26,255,236,229,27,255,239,229,28,255,241,229,29,255,244,230,30,255,246,230,32,255,248,230,33,255,251,231,35,255,253,231,37,255]),
<add> inferno: new Uint8Array([0,0,4,255,1,0,5,255,1,1,6,255,1,1,8,255,2,1,10,255,2,2,12,255,2,2,14,255,3,2,16,255,4,3,18,255,4,3,20,255,5,4,23,255,6,4,25,255,7,5,27,255,8,5,29,255,9,6,31,255,10,7,34,255,11,7,36,255,12,8,38,255,13,8,41,255,14,9,43,255,16,9,45,255,17,10,48,255,18,10,50,255,20,11,52,255,21,11,55,255,22,11,57,255,24,12,60,255,25,12,62,255,27,12,65,255,28,12,67,255,30,12,69,255,31,12,72,255,33,12,74,255,35,12,76,255,36,12,79,255,38,12,81,255,40,11,83,255,41,11,85,255,43,11,87,255,45,11,89,255,47,10,91,255,49,10,92,255,50,10,94,255,52,10,95,255,54,9,97,255,56,9,98,255,57,9,99,255,59,9,100,255,61,9,101,255,62,9,102,255,64,10,103,255,66,10,104,255,68,10,104,255,69,10,105,255,71,11,106,255,73,11,106,255,74,12,107,255,76,12,107,255,77,13,108,255,79,13,108,255,81,14,108,255,82,14,109,255,84,15,109,255,85,15,109,255,87,16,110,255,89,16,110,255,90,17,110,255,92,18,110,255,93,18,110,255,95,19,110,255,97,19,110,255,98,20,110,255,100,21,110,255,101,21,110,255,103,22,110,255,105,22,110,255,106,23,110,255,108,24,110,255,109,24,110,255,111,25,110,255,113,25,110,255,114,26,110,255,116,26,110,255,117,27,110,255,119,28,109,255,120,28,109,255,122,29,109,255,124,29,109,255,125,30,109,255,127,30,108,255,128,31,108,255,130,32,108,255,132,32,107,255,133,33,107,255,135,33,107,255,136,34,106,255,138,34,106,255,140,35,105,255,141,35,105,255,143,36,105,255,144,37,104,255,146,37,104,255,147,38,103,255,149,38,103,255,151,39,102,255,152,39,102,255,154,40,101,255,155,41,100,255,157,41,100,255,159,42,99,255,160,42,99,255,162,43,98,255,163,44,97,255,165,44,96,255,166,45,96,255,168,46,95,255,169,46,94,255,171,47,94,255,173,48,93,255,174,48,92,255,176,49,91,255,177,50,90,255,179,50,90,255,180,51,89,255,182,52,88,255,183,53,87,255,185,53,86,255,186,54,85,255,188,55,84,255,189,56,83,255,191,57,82,255,192,58,81,255,193,58,80,255,195,59,79,255,196,60,78,255,198,61,77,255,199,62,76,255,200,63,75,255,202,64,74,255,203,65,73,255,204,66,72,255,206,67,71,255,207,68,70,255,208,69,69,255,210,70,68,255,211,71,67,255,212,72,66,255,213,74,65,255,215,75,63,255,216,76,62,255,217,77,61,255,218,78,60,255,219,80,59,255,221,81,58,255,222,82,56,255,223,83,55,255,224,85,54,255,225,86,53,255,226,87,52,255,227,89,51,255,228,90,49,255,229,92,48,255,230,93,47,255,231,94,46,255,232,96,45,255,233,97,43,255,234,99,42,255,235,100,41,255,235,102,40,255,236,103,38,255,237,105,37,255,238,106,36,255,239,108,35,255,239,110,33,255,240,111,32,255,241,113,31,255,241,115,29,255,242,116,28,255,243,118,27,255,243,120,25,255,244,121,24,255,245,123,23,255,245,125,21,255,246,126,20,255,246,128,19,255,247,130,18,255,247,132,16,255,248,133,15,255,248,135,14,255,248,137,12,255,249,139,11,255,249,140,10,255,249,142,9,255,250,144,8,255,250,146,7,255,250,148,7,255,251,150,6,255,251,151,6,255,251,153,6,255,251,155,6,255,251,157,7,255,252,159,7,255,252,161,8,255,252,163,9,255,252,165,10,255,252,166,12,255,252,168,13,255,252,170,15,255,252,172,17,255,252,174,18,255,252,176,20,255,252,178,22,255,252,180,24,255,251,182,26,255,251,184,29,255,251,186,31,255,251,188,33,255,251,190,35,255,250,192,38,255,250,194,40,255,250,196,42,255,250,198,45,255,249,199,47,255,249,201,50,255,249,203,53,255,248,205,55,255,248,207,58,255,247,209,61,255,247,211,64,255,246,213,67,255,246,215,70,255,245,217,73,255,245,219,76,255,244,221,79,255,244,223,83,255,244,225,86,255,243,227,90,255,243,229,93,255,242,230,97,255,242,232,101,255,242,234,105,255,241,236,109,255,241,237,113,255,241,239,117,255,241,241,121,255,242,242,125,255,242,244,130,255,243,245,134,255,243,246,138,255,244,248,142,255,245,249,146,255,246,250,150,255,248,251,154,255,249,252,157,255,250,253,161,255,252,255,164,255]),
<add> rainbow: {
<add> colors: ['#96005A','#0000C8','#0019FF','#0098FF','#2CFF96','#97FF00','#FFEA00','#FF6F00','#FF0000'],
<ide> positions: [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1]
<ide> },
<del> "jet": {
<del> colors: ["#000083","#003CAA","#05FFFF","#FFFF00","#FA0000","#800000"],
<add> jet: {
<add> colors: ['#000083','#003CAA','#05FFFF','#FFFF00','#FA0000','#800000'],
<ide> positions: [0, 0.125, 0.375, 0.625, 0.875, 1]
<ide> },
<del> "hsv": {
<del> colors: ["#ff0000","#fdff02","#f7ff02","#00fc04","#00fc0a","#01f9ff","#0200fd","#0800fd","#ff00fb","#ff00f5","#ff0006"],
<add> hsv: {
<add> colors: ['#ff0000','#fdff02','#f7ff02','#00fc04','#00fc0a','#01f9ff','#0200fd','#0800fd','#ff00fb','#ff00f5','#ff0006'],
<ide> positions: [0,0.169,0.173,0.337,0.341,0.506,0.671,0.675,0.839,0.843,1]
<ide> },
<del> "hot": {
<del> colors: ["#000000","#e60000","#ffd200","#ffffff"],
<add> hot: {
<add> colors: ['#000000','#e60000','#ffd200','#ffffff'],
<ide> positions: [0,0.3,0.6,1]
<ide> },
<del> "cool": {
<del> colors: ["#00ffff","#ff00ff"],
<add> cool: {
<add> colors: ['#00ffff','#ff00ff'],
<ide> positions: [0,1]
<ide> },
<del> "spring": {
<del> colors: ["#ff00ff","#ffff00"],
<add> spring: {
<add> colors: ['#ff00ff','#ffff00'],
<ide> positions: [0,1]
<ide> },
<del> "summer": {
<del> colors: ["#008066","#ffff66"],
<add> summer: {
<add> colors: ['#008066','#ffff66'],
<ide> positions: [0,1]
<ide> },
<del> "autumn": {
<del> colors: ["#ff0000","#ffff00"],
<add> autumn: {
<add> colors: ['#ff0000','#ffff00'],
<ide> positions: [0,1]
<ide> },
<del> "winter": {
<del> colors: ["#0000ff","#00ff80"],
<add> winter: {
<add> colors: ['#0000ff','#00ff80'],
<ide> positions: [0,1]
<ide> },
<del> "bone": {
<del> colors: ["#000000","#545474","#a9c8c8","#ffffff"],
<add> bone: {
<add> colors: ['#000000','#545474','#a9c8c8','#ffffff'],
<ide> positions: [0,0.376,0.753,1]
<ide> },
<del> "copper": {
<del> colors: ["#000000","#ffa066","#ffc77f"],
<add> copper: {
<add> colors: ['#000000','#ffa066','#ffc77f'],
<ide> positions: [0,0.804,1]
<ide> },
<del> "greys": {
<del> colors: ["#000000","#ffffff"],
<add> greys: {
<add> colors: ['#000000','#ffffff'],
<ide> positions: [0,1]
<ide> },
<del> "yignbu": {
<del> colors: ["#081d58","#253494","#225ea8","#1d91c0","#41b6c4","#7fcdbb","#c7e9b4","#edf8d9","#ffffd9"],
<add> yignbu: {
<add> colors: ['#081d58','#253494','#225ea8','#1d91c0','#41b6c4','#7fcdbb','#c7e9b4','#edf8d9','#ffffd9'],
<ide> positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
<ide> },
<del> "greens": {
<del> colors: ["#00441b","#006d2c","#238b45","#41ab5d","#74c476","#a1d99b","#c7e9c0","#e5f5e0","#f7fcf5"],
<add> greens: {
<add> colors: ['#00441b','#006d2c','#238b45','#41ab5d','#74c476','#a1d99b','#c7e9c0','#e5f5e0','#f7fcf5'],
<ide> positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
<ide> },
<del> "yiorrd": {
<del> colors: ["#800026","#bd0026","#e31a1c","#fc4e2a","#fd8d3c","#feb24c","#fed976","#ffeda0","#ffffcc"],
<add> yiorrd: {
<add> colors: ['#800026','#bd0026','#e31a1c','#fc4e2a','#fd8d3c','#feb24c','#fed976','#ffeda0','#ffffcc'],
<ide> positions: [0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1]
<ide> },
<del> "bluered": {
<del> colors: ["#0000ff","#ff0000"],
<add> bluered: {
<add> colors: ['#0000ff','#ff0000'],
<ide> positions: [0,1]
<ide> },
<del> "rdbu": {
<del> colors: ["#050aac","#6a89f7","#bebebe","#dcaa84","#e6915a","#b20a1c"],
<add> rdbu: {
<add> colors: ['#050aac','#6a89f7','#bebebe','#dcaa84','#e6915a','#b20a1c'],
<ide> positions: [0,0.35,0.5,0.6,0.7,1]
<ide> },
<del> "picnic": {
<del> colors: ["#0000ff","#3399ff","#66ccff","#99ccff","#ccccff","#ffffff","#ffccff","#ff99ff","#ff66cc","#ff6666","#ff0000"],
<add> picnic: {
<add> colors: ['#0000ff','#3399ff','#66ccff','#99ccff','#ccccff','#ffffff','#ffccff','#ff99ff','#ff66cc','#ff6666','#ff0000'],
<ide> positions: [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]
<ide> },
<del> "portland": {
<del> colors: ["#0c3383","#0a88ba","#f2d338","#f28f38","#d91e1e"],
<add> portland: {
<add> colors: ['#0c3383','#0a88ba','#f2d338','#f28f38','#d91e1e'],
<ide> positions: [0,0.25,0.5,0.75,1]
<ide> },
<del> "blackbody": {
<del> colors: ["#000000","#e60000","#e6d200","#ffffff","#a0c8ff"],
<add> blackbody: {
<add> colors: ['#000000','#e60000','#e6d200','#ffffff','#a0c8ff'],
<ide> positions: [0,0.2,0.4,0.7,1]
<ide> },
<del> "earth": {
<del> colors: ["#000082","#00b4b4","#28d228","#e6e632","#784614","#ffffff"],
<add> earth: {
<add> colors: ['#000082','#00b4b4','#28d228','#e6e632','#784614','#ffffff'],
<ide> positions: [0,0.1,0.2,0.4,0.6,1]
<ide> },
<del> "electric": {
<del> colors: ["#000000","#1e0064","#780064","#a05a00","#e6c800","#fffadc"],
<add> electric: {
<add> colors: ['#000000','#1e0064','#780064','#a05a00','#e6c800','#fffadc'],
<ide> positions: [0,0.15,0.4,0.6,0.8,1]
<ide> },
<del> "magma": new Uint8Array([0,0,4,255,1,0,5,255,1,1,6,255,1,1,8,255,2,1,9,255,2,2,11,255,2,2,13,255,3,3,15,255,3,3,18,255,4,4,20,255,5,4,22,255,6,5,24,255,6,5,26,255,7,6,28,255,8,7,30,255,9,7,32,255,10,8,34,255,11,9,36,255,12,9,38,255,13,10,41,255,14,11,43,255,16,11,45,255,17,12,47,255,18,13,49,255,19,13,52,255,20,14,54,255,21,14,56,255,22,15,59,255,24,15,61,255,25,16,63,255,26,16,66,255,28,16,68,255,29,17,71,255,30,17,73,255,32,17,75,255,33,17,78,255,34,17,80,255,36,18,83,255,37,18,85,255,39,18,88,255,41,17,90,255,42,17,92,255,44,17,95,255,45,17,97,255,47,17,99,255,49,17,101,255,51,16,103,255,52,16,105,255,54,16,107,255,56,16,108,255,57,15,110,255,59,15,112,255,61,15,113,255,63,15,114,255,64,15,116,255,66,15,117,255,68,15,118,255,69,16,119,255,71,16,120,255,73,16,120,255,74,16,121,255,76,17,122,255,78,17,123,255,79,18,123,255,81,18,124,255,82,19,124,255,84,19,125,255,86,20,125,255,87,21,126,255,89,21,126,255,90,22,126,255,92,22,127,255,93,23,127,255,95,24,127,255,96,24,128,255,98,25,128,255,100,26,128,255,101,26,128,255,103,27,128,255,104,28,129,255,106,28,129,255,107,29,129,255,109,29,129,255,110,30,129,255,112,31,129,255,114,31,129,255,115,32,129,255,117,33,129,255,118,33,129,255,120,34,129,255,121,34,130,255,123,35,130,255,124,35,130,255,126,36,130,255,128,37,130,255,129,37,129,255,131,38,129,255,132,38,129,255,134,39,129,255,136,39,129,255,137,40,129,255,139,41,129,255,140,41,129,255,142,42,129,255,144,42,129,255,145,43,129,255,147,43,128,255,148,44,128,255,150,44,128,255,152,45,128,255,153,45,128,255,155,46,127,255,156,46,127,255,158,47,127,255,160,47,127,255,161,48,126,255,163,48,126,255,165,49,126,255,166,49,125,255,168,50,125,255,170,51,125,255,171,51,124,255,173,52,124,255,174,52,123,255,176,53,123,255,178,53,123,255,179,54,122,255,181,54,122,255,183,55,121,255,184,55,121,255,186,56,120,255,188,57,120,255,189,57,119,255,191,58,119,255,192,58,118,255,194,59,117,255,196,60,117,255,197,60,116,255,199,61,115,255,200,62,115,255,202,62,114,255,204,63,113,255,205,64,113,255,207,64,112,255,208,65,111,255,210,66,111,255,211,67,110,255,213,68,109,255,214,69,108,255,216,69,108,255,217,70,107,255,219,71,106,255,220,72,105,255,222,73,104,255,223,74,104,255,224,76,103,255,226,77,102,255,227,78,101,255,228,79,100,255,229,80,100,255,231,82,99,255,232,83,98,255,233,84,98,255,234,86,97,255,235,87,96,255,236,88,96,255,237,90,95,255,238,91,94,255,239,93,94,255,240,95,94,255,241,96,93,255,242,98,93,255,242,100,92,255,243,101,92,255,244,103,92,255,244,105,92,255,245,107,92,255,246,108,92,255,246,110,92,255,247,112,92,255,247,114,92,255,248,116,92,255,248,118,92,255,249,120,93,255,249,121,93,255,249,123,93,255,250,125,94,255,250,127,94,255,250,129,95,255,251,131,95,255,251,133,96,255,251,135,97,255,252,137,97,255,252,138,98,255,252,140,99,255,252,142,100,255,252,144,101,255,253,146,102,255,253,148,103,255,253,150,104,255,253,152,105,255,253,154,106,255,253,155,107,255,254,157,108,255,254,159,109,255,254,161,110,255,254,163,111,255,254,165,113,255,254,167,114,255,254,169,115,255,254,170,116,255,254,172,118,255,254,174,119,255,254,176,120,255,254,178,122,255,254,180,123,255,254,182,124,255,254,183,126,255,254,185,127,255,254,187,129,255,254,189,130,255,254,191,132,255,254,193,133,255,254,194,135,255,254,196,136,255,254,198,138,255,254,200,140,255,254,202,141,255,254,204,143,255,254,205,144,255,254,207,146,255,254,209,148,255,254,211,149,255,254,213,151,255,254,215,153,255,254,216,154,255,253,218,156,255,253,220,158,255,253,222,160,255,253,224,161,255,253,226,163,255,253,227,165,255,253,229,167,255,253,231,169,255,253,233,170,255,253,235,172,255,252,236,174,255,252,238,176,255,252,240,178,255,252,242,180,255,252,244,182,255,252,246,184,255,252,247,185,255,252,249,187,255,252,251,189,255,252,253,191,255]),
<del> "plasma": new Uint8Array([13,8,135,255,16,7,136,255,19,7,137,255,22,7,138,255,25,6,140,255,27,6,141,255,29,6,142,255,32,6,143,255,34,6,144,255,36,6,145,255,38,5,145,255,40,5,146,255,42,5,147,255,44,5,148,255,46,5,149,255,47,5,150,255,49,5,151,255,51,5,151,255,53,4,152,255,55,4,153,255,56,4,154,255,58,4,154,255,60,4,155,255,62,4,156,255,63,4,156,255,65,4,157,255,67,3,158,255,68,3,158,255,70,3,159,255,72,3,159,255,73,3,160,255,75,3,161,255,76,2,161,255,78,2,162,255,80,2,162,255,81,2,163,255,83,2,163,255,85,2,164,255,86,1,164,255,88,1,164,255,89,1,165,255,91,1,165,255,92,1,166,255,94,1,166,255,96,1,166,255,97,0,167,255,99,0,167,255,100,0,167,255,102,0,167,255,103,0,168,255,105,0,168,255,106,0,168,255,108,0,168,255,110,0,168,255,111,0,168,255,113,0,168,255,114,1,168,255,116,1,168,255,117,1,168,255,119,1,168,255,120,1,168,255,122,2,168,255,123,2,168,255,125,3,168,255,126,3,168,255,128,4,168,255,129,4,167,255,131,5,167,255,132,5,167,255,134,6,166,255,135,7,166,255,136,8,166,255,138,9,165,255,139,10,165,255,141,11,165,255,142,12,164,255,143,13,164,255,145,14,163,255,146,15,163,255,148,16,162,255,149,17,161,255,150,19,161,255,152,20,160,255,153,21,159,255,154,22,159,255,156,23,158,255,157,24,157,255,158,25,157,255,160,26,156,255,161,27,155,255,162,29,154,255,163,30,154,255,165,31,153,255,166,32,152,255,167,33,151,255,168,34,150,255,170,35,149,255,171,36,148,255,172,38,148,255,173,39,147,255,174,40,146,255,176,41,145,255,177,42,144,255,178,43,143,255,179,44,142,255,180,46,141,255,181,47,140,255,182,48,139,255,183,49,138,255,184,50,137,255,186,51,136,255,187,52,136,255,188,53,135,255,189,55,134,255,190,56,133,255,191,57,132,255,192,58,131,255,193,59,130,255,194,60,129,255,195,61,128,255,196,62,127,255,197,64,126,255,198,65,125,255,199,66,124,255,200,67,123,255,201,68,122,255,202,69,122,255,203,70,121,255,204,71,120,255,204,73,119,255,205,74,118,255,206,75,117,255,207,76,116,255,208,77,115,255,209,78,114,255,210,79,113,255,211,81,113,255,212,82,112,255,213,83,111,255,213,84,110,255,214,85,109,255,215,86,108,255,216,87,107,255,217,88,106,255,218,90,106,255,218,91,105,255,219,92,104,255,220,93,103,255,221,94,102,255,222,95,101,255,222,97,100,255,223,98,99,255,224,99,99,255,225,100,98,255,226,101,97,255,226,102,96,255,227,104,95,255,228,105,94,255,229,106,93,255,229,107,93,255,230,108,92,255,231,110,91,255,231,111,90,255,232,112,89,255,233,113,88,255,233,114,87,255,234,116,87,255,235,117,86,255,235,118,85,255,236,119,84,255,237,121,83,255,237,122,82,255,238,123,81,255,239,124,81,255,239,126,80,255,240,127,79,255,240,128,78,255,241,129,77,255,241,131,76,255,242,132,75,255,243,133,75,255,243,135,74,255,244,136,73,255,244,137,72,255,245,139,71,255,245,140,70,255,246,141,69,255,246,143,68,255,247,144,68,255,247,145,67,255,247,147,66,255,248,148,65,255,248,149,64,255,249,151,63,255,249,152,62,255,249,154,62,255,250,155,61,255,250,156,60,255,250,158,59,255,251,159,58,255,251,161,57,255,251,162,56,255,252,163,56,255,252,165,55,255,252,166,54,255,252,168,53,255,252,169,52,255,253,171,51,255,253,172,51,255,253,174,50,255,253,175,49,255,253,177,48,255,253,178,47,255,253,180,47,255,253,181,46,255,254,183,45,255,254,184,44,255,254,186,44,255,254,187,43,255,254,189,42,255,254,190,42,255,254,192,41,255,253,194,41,255,253,195,40,255,253,197,39,255,253,198,39,255,253,200,39,255,253,202,38,255,253,203,38,255,252,205,37,255,252,206,37,255,252,208,37,255,252,210,37,255,251,211,36,255,251,213,36,255,251,215,36,255,250,216,36,255,250,218,36,255,249,220,36,255,249,221,37,255,248,223,37,255,248,225,37,255,247,226,37,255,247,228,37,255,246,230,38,255,246,232,38,255,245,233,38,255,245,235,39,255,244,237,39,255,243,238,39,255,243,240,39,255,242,242,39,255,241,244,38,255,241,245,37,255,240,247,36,255,240,249,33,255]),
<del> "redblue": {
<del> colors: ["#ff0000", "#0000ff"],
<add> magma: new Uint8Array([0,0,4,255,1,0,5,255,1,1,6,255,1,1,8,255,2,1,9,255,2,2,11,255,2,2,13,255,3,3,15,255,3,3,18,255,4,4,20,255,5,4,22,255,6,5,24,255,6,5,26,255,7,6,28,255,8,7,30,255,9,7,32,255,10,8,34,255,11,9,36,255,12,9,38,255,13,10,41,255,14,11,43,255,16,11,45,255,17,12,47,255,18,13,49,255,19,13,52,255,20,14,54,255,21,14,56,255,22,15,59,255,24,15,61,255,25,16,63,255,26,16,66,255,28,16,68,255,29,17,71,255,30,17,73,255,32,17,75,255,33,17,78,255,34,17,80,255,36,18,83,255,37,18,85,255,39,18,88,255,41,17,90,255,42,17,92,255,44,17,95,255,45,17,97,255,47,17,99,255,49,17,101,255,51,16,103,255,52,16,105,255,54,16,107,255,56,16,108,255,57,15,110,255,59,15,112,255,61,15,113,255,63,15,114,255,64,15,116,255,66,15,117,255,68,15,118,255,69,16,119,255,71,16,120,255,73,16,120,255,74,16,121,255,76,17,122,255,78,17,123,255,79,18,123,255,81,18,124,255,82,19,124,255,84,19,125,255,86,20,125,255,87,21,126,255,89,21,126,255,90,22,126,255,92,22,127,255,93,23,127,255,95,24,127,255,96,24,128,255,98,25,128,255,100,26,128,255,101,26,128,255,103,27,128,255,104,28,129,255,106,28,129,255,107,29,129,255,109,29,129,255,110,30,129,255,112,31,129,255,114,31,129,255,115,32,129,255,117,33,129,255,118,33,129,255,120,34,129,255,121,34,130,255,123,35,130,255,124,35,130,255,126,36,130,255,128,37,130,255,129,37,129,255,131,38,129,255,132,38,129,255,134,39,129,255,136,39,129,255,137,40,129,255,139,41,129,255,140,41,129,255,142,42,129,255,144,42,129,255,145,43,129,255,147,43,128,255,148,44,128,255,150,44,128,255,152,45,128,255,153,45,128,255,155,46,127,255,156,46,127,255,158,47,127,255,160,47,127,255,161,48,126,255,163,48,126,255,165,49,126,255,166,49,125,255,168,50,125,255,170,51,125,255,171,51,124,255,173,52,124,255,174,52,123,255,176,53,123,255,178,53,123,255,179,54,122,255,181,54,122,255,183,55,121,255,184,55,121,255,186,56,120,255,188,57,120,255,189,57,119,255,191,58,119,255,192,58,118,255,194,59,117,255,196,60,117,255,197,60,116,255,199,61,115,255,200,62,115,255,202,62,114,255,204,63,113,255,205,64,113,255,207,64,112,255,208,65,111,255,210,66,111,255,211,67,110,255,213,68,109,255,214,69,108,255,216,69,108,255,217,70,107,255,219,71,106,255,220,72,105,255,222,73,104,255,223,74,104,255,224,76,103,255,226,77,102,255,227,78,101,255,228,79,100,255,229,80,100,255,231,82,99,255,232,83,98,255,233,84,98,255,234,86,97,255,235,87,96,255,236,88,96,255,237,90,95,255,238,91,94,255,239,93,94,255,240,95,94,255,241,96,93,255,242,98,93,255,242,100,92,255,243,101,92,255,244,103,92,255,244,105,92,255,245,107,92,255,246,108,92,255,246,110,92,255,247,112,92,255,247,114,92,255,248,116,92,255,248,118,92,255,249,120,93,255,249,121,93,255,249,123,93,255,250,125,94,255,250,127,94,255,250,129,95,255,251,131,95,255,251,133,96,255,251,135,97,255,252,137,97,255,252,138,98,255,252,140,99,255,252,142,100,255,252,144,101,255,253,146,102,255,253,148,103,255,253,150,104,255,253,152,105,255,253,154,106,255,253,155,107,255,254,157,108,255,254,159,109,255,254,161,110,255,254,163,111,255,254,165,113,255,254,167,114,255,254,169,115,255,254,170,116,255,254,172,118,255,254,174,119,255,254,176,120,255,254,178,122,255,254,180,123,255,254,182,124,255,254,183,126,255,254,185,127,255,254,187,129,255,254,189,130,255,254,191,132,255,254,193,133,255,254,194,135,255,254,196,136,255,254,198,138,255,254,200,140,255,254,202,141,255,254,204,143,255,254,205,144,255,254,207,146,255,254,209,148,255,254,211,149,255,254,213,151,255,254,215,153,255,254,216,154,255,253,218,156,255,253,220,158,255,253,222,160,255,253,224,161,255,253,226,163,255,253,227,165,255,253,229,167,255,253,231,169,255,253,233,170,255,253,235,172,255,252,236,174,255,252,238,176,255,252,240,178,255,252,242,180,255,252,244,182,255,252,246,184,255,252,247,185,255,252,249,187,255,252,251,189,255,252,253,191,255]),
<add> plasma: new Uint8Array([13,8,135,255,16,7,136,255,19,7,137,255,22,7,138,255,25,6,140,255,27,6,141,255,29,6,142,255,32,6,143,255,34,6,144,255,36,6,145,255,38,5,145,255,40,5,146,255,42,5,147,255,44,5,148,255,46,5,149,255,47,5,150,255,49,5,151,255,51,5,151,255,53,4,152,255,55,4,153,255,56,4,154,255,58,4,154,255,60,4,155,255,62,4,156,255,63,4,156,255,65,4,157,255,67,3,158,255,68,3,158,255,70,3,159,255,72,3,159,255,73,3,160,255,75,3,161,255,76,2,161,255,78,2,162,255,80,2,162,255,81,2,163,255,83,2,163,255,85,2,164,255,86,1,164,255,88,1,164,255,89,1,165,255,91,1,165,255,92,1,166,255,94,1,166,255,96,1,166,255,97,0,167,255,99,0,167,255,100,0,167,255,102,0,167,255,103,0,168,255,105,0,168,255,106,0,168,255,108,0,168,255,110,0,168,255,111,0,168,255,113,0,168,255,114,1,168,255,116,1,168,255,117,1,168,255,119,1,168,255,120,1,168,255,122,2,168,255,123,2,168,255,125,3,168,255,126,3,168,255,128,4,168,255,129,4,167,255,131,5,167,255,132,5,167,255,134,6,166,255,135,7,166,255,136,8,166,255,138,9,165,255,139,10,165,255,141,11,165,255,142,12,164,255,143,13,164,255,145,14,163,255,146,15,163,255,148,16,162,255,149,17,161,255,150,19,161,255,152,20,160,255,153,21,159,255,154,22,159,255,156,23,158,255,157,24,157,255,158,25,157,255,160,26,156,255,161,27,155,255,162,29,154,255,163,30,154,255,165,31,153,255,166,32,152,255,167,33,151,255,168,34,150,255,170,35,149,255,171,36,148,255,172,38,148,255,173,39,147,255,174,40,146,255,176,41,145,255,177,42,144,255,178,43,143,255,179,44,142,255,180,46,141,255,181,47,140,255,182,48,139,255,183,49,138,255,184,50,137,255,186,51,136,255,187,52,136,255,188,53,135,255,189,55,134,255,190,56,133,255,191,57,132,255,192,58,131,255,193,59,130,255,194,60,129,255,195,61,128,255,196,62,127,255,197,64,126,255,198,65,125,255,199,66,124,255,200,67,123,255,201,68,122,255,202,69,122,255,203,70,121,255,204,71,120,255,204,73,119,255,205,74,118,255,206,75,117,255,207,76,116,255,208,77,115,255,209,78,114,255,210,79,113,255,211,81,113,255,212,82,112,255,213,83,111,255,213,84,110,255,214,85,109,255,215,86,108,255,216,87,107,255,217,88,106,255,218,90,106,255,218,91,105,255,219,92,104,255,220,93,103,255,221,94,102,255,222,95,101,255,222,97,100,255,223,98,99,255,224,99,99,255,225,100,98,255,226,101,97,255,226,102,96,255,227,104,95,255,228,105,94,255,229,106,93,255,229,107,93,255,230,108,92,255,231,110,91,255,231,111,90,255,232,112,89,255,233,113,88,255,233,114,87,255,234,116,87,255,235,117,86,255,235,118,85,255,236,119,84,255,237,121,83,255,237,122,82,255,238,123,81,255,239,124,81,255,239,126,80,255,240,127,79,255,240,128,78,255,241,129,77,255,241,131,76,255,242,132,75,255,243,133,75,255,243,135,74,255,244,136,73,255,244,137,72,255,245,139,71,255,245,140,70,255,246,141,69,255,246,143,68,255,247,144,68,255,247,145,67,255,247,147,66,255,248,148,65,255,248,149,64,255,249,151,63,255,249,152,62,255,249,154,62,255,250,155,61,255,250,156,60,255,250,158,59,255,251,159,58,255,251,161,57,255,251,162,56,255,252,163,56,255,252,165,55,255,252,166,54,255,252,168,53,255,252,169,52,255,253,171,51,255,253,172,51,255,253,174,50,255,253,175,49,255,253,177,48,255,253,178,47,255,253,180,47,255,253,181,46,255,254,183,45,255,254,184,44,255,254,186,44,255,254,187,43,255,254,189,42,255,254,190,42,255,254,192,41,255,253,194,41,255,253,195,40,255,253,197,39,255,253,198,39,255,253,200,39,255,253,202,38,255,253,203,38,255,252,205,37,255,252,206,37,255,252,208,37,255,252,210,37,255,251,211,36,255,251,213,36,255,251,215,36,255,250,216,36,255,250,218,36,255,249,220,36,255,249,221,37,255,248,223,37,255,248,225,37,255,247,226,37,255,247,228,37,255,246,230,38,255,246,232,38,255,245,233,38,255,245,235,39,255,244,237,39,255,243,238,39,255,243,240,39,255,242,242,39,255,241,244,38,255,241,245,37,255,240,247,36,255,240,249,33,255]),
<add> redblue: {
<add> colors: ['#ff0000', '#0000ff'],
<ide> positions: [0,1]
<ide> },
<del> "coolwarm": {
<del> colors: ["#0000ff", "#ffffff", "#ff0000"],
<add> coolwarm: {
<add> colors: ['#0000ff', '#ffffff', '#ff0000'],
<ide> positions: [0,0.5,1]
<ide> },
<del> "diverging_1": {
<del> colors: ["#400040","#3b004d","#36005b","#320068","#2d0076","#290084","#240091","#20009f","#1b00ad","#1600ba","#1200c8","#0d00d6","#0900e3","#0400f1","#0000ff","#0217ff","#042eff","#0645ff","#095cff","#0b73ff","#0d8bff","#10a2ff","#12b9ff","#14d0ff","#17e7ff","#19ffff","#3fffff","#66ffff","#8cffff","#b2ffff","#d8ffff","#ffffff","#ffffd4","#ffffaa","#ffff7f","#ffff54","#ffff2a","#ffff00","#ffed00","#ffdd00","#ffcc00","#ffba00","#ffaa00","#ff9900","#ff8700","#ff7700","#ff6600","#ff5400","#ff4400","#ff3300","#ff2100","#ff1100","#ff0000","#ff0017","#ff002e","#ff0045","#ff005c","#ff0073","#ff008b","#ff00a2","#ff00b9","#ff00d0","#ff00e7","#ff00ff"],
<add> diverging_1: {
<add> colors: ['#400040','#3b004d','#36005b','#320068','#2d0076','#290084','#240091','#20009f','#1b00ad','#1600ba','#1200c8','#0d00d6','#0900e3','#0400f1','#0000ff','#0217ff','#042eff','#0645ff','#095cff','#0b73ff','#0d8bff','#10a2ff','#12b9ff','#14d0ff','#17e7ff','#19ffff','#3fffff','#66ffff','#8cffff','#b2ffff','#d8ffff','#ffffff','#ffffd4','#ffffaa','#ffff7f','#ffff54','#ffff2a','#ffff00','#ffed00','#ffdd00','#ffcc00','#ffba00','#ffaa00','#ff9900','#ff8700','#ff7700','#ff6600','#ff5400','#ff4400','#ff3300','#ff2100','#ff1100','#ff0000','#ff0017','#ff002e','#ff0045','#ff005c','#ff0073','#ff008b','#ff00a2','#ff00b9','#ff00d0','#ff00e7','#ff00ff'],
<ide> positions: [0.0,0.01587301587,0.03174603174,0.04761904761,0.06349206348,0.07936507935,0.09523809522,0.11111111109,0.12698412696,0.14285714283,0.15873015870,0.17460317457,0.19047619044,0.20634920631,0.22222222218,0.23809523805,0.25396825392,0.26984126979,0.28571428566,0.30158730153,0.31746031740,0.33333333327,0.34920634914,0.36507936501,0.38095238088,0.39682539675,0.41269841262,0.42857142849,0.44444444436,0.46031746023,0.47619047610,0.49206349197,0.50793650784,0.52380952371,0.53968253958,0.55555555545,0.57142857132,0.58730158719,0.60317460306,0.61904761893,0.63492063480,0.65079365067,0.66666666654,0.68253968241,0.69841269828,0.71428571415,0.73015873002,0.74603174589,0.76190476176,0.77777777763,0.79365079350,0.80952380937,0.82539682524,0.84126984111,0.85714285698,0.87301587285,0.88888888872,0.90476190459,0.92063492046,0.93650793633,0.95238095220,0.96825396807,0.98412698394,1]
<ide> },
<del> "diverging_2": {
<del> colors: ["#000000","#030aff","#204aff","#3c8aff","#77c4ff","#f0ffff","#f0ffff","#f2ff7f","#ffff00","#ff831e","#ff083d","#ff00ff"],
<add> diverging_2: {
<add> colors: ['#000000','#030aff','#204aff','#3c8aff','#77c4ff','#f0ffff','#f0ffff','#f2ff7f','#ffff00','#ff831e','#ff083d','#ff00ff'],
<ide> positions: [0,0.0000000001,0.1,0.2,0.3333,0.4666,0.5333,0.6666,0.8,0.9,0.999999999999,1]
<ide> },
<del> "blackwhite": {
<del> colors: ["#000000","#ffffff"],
<add> blackwhite: {
<add> colors: ['#000000','#ffffff'],
<ide> positions: [0,1]
<ide> },
<del> "ylgnbu": {
<del> colors: ["#081d58","#253494","#225ea8","#1d91c0","#41b6c4","#7fcdbb","#c7e9b4","#edf8d9","#ffffd9"],
<add> ylgnbu: {
<add> colors: ['#081d58','#253494','#225ea8','#1d91c0','#41b6c4','#7fcdbb','#c7e9b4','#edf8d9','#ffffd9'],
<ide> positions: [1,0.875,0.75,0.625,0.5,0.375,0.25,0.125,0]
<ide> },
<del> "ylorrd": {
<del> colors: ["#800026","#bd0026","#e31a1c","#fc4e2a","#fd8d3c","#feb24c","#fed976","#ffeda0","#ffffcc"],
<add> ylorrd: {
<add> colors: ['#800026','#bd0026','#e31a1c','#fc4e2a','#fd8d3c','#feb24c','#fed976','#ffeda0','#ffffcc'],
<ide> positions: [1,0.875,0.75,0.625,0.5,0.375,0.25,0.125,0]
<ide> },
<del> "twilight": {
<del> colors: ["#E2D9E2", "#E0D9E2", "#DDD9E0", "#DAD8DF", "#D6D7DD", "#D2D5DB", "#CDD3D8", "#C8D0D6", "#C2CED4", "#BCCBD1", "#B6C8CF", "#B0C5CD", "#AAC2CC", "#A4BECA", "#9EBBC9", "#99B8C8", "#93B4C6", "#8EB1C5", "#89ADC5", "#85A9C4", "#80A5C3", "#7CA2C2", "#789EC2", "#759AC1", "#7196C1", "#6E92C0", "#6C8EBF", "#698ABF", "#6786BE", "#6682BD", "#647DBC", "#6379BB", "#6275BA", "#6170B9", "#606CB8", "#6067B6", "#5F62B4", "#5F5EB3", "#5F59B1", "#5E54AE", "#5E4FAC", "#5E4BA9", "#5E46A6", "#5D41A3", "#5D3CA0", "#5C379C", "#5B3298", "#5A2E93", "#59298E", "#572588", "#562182", "#531E7C", "#511A75", "#4E186F", "#4B1668", "#471461", "#44135A", "#411254", "#3D114E", "#3A1149", "#371144", "#351140", "#33113C", "#311339", "#301437", "#331237", "#351138", "#381139", "#3B113B", "#3F123D", "#43123E", "#481341", "#4D1443", "#521545", "#571647", "#5C1749", "#61184B", "#67194C", "#6C1B4E", "#711D4F", "#761F4F", "#7B2150", "#802350", "#852650", "#8A2950", "#8E2C50", "#922F50", "#963350", "#9A3750", "#9E3B50", "#A13F50", "#A54350", "#A84750", "#AB4B50", "#AE5051", "#B15452", "#B35953", "#B65D54", "#B86255", "#BA6657", "#BC6B59", "#BE705B", "#C0755E", "#C27A61", "#C37F64", "#C58468", "#C6896C", "#C78E71", "#C89275", "#C9977B", "#CA9C80", "#CCA186", "#CDA68C", "#CEAB92", "#CFAF99", "#D1B4A0", "#D2B8A7", "#D4BDAD", "#D6C1B4", "#D8C5BB", "#D9C9C2", "#DBCCC8", "#DDD0CE", "#DED3D3", "#DFD5D8", "#E0D7DB", "#E1D8DF", "#E2D9E1"],
<add> twilight: {
<add> colors: ['#E2D9E2', '#E0D9E2', '#DDD9E0', '#DAD8DF', '#D6D7DD', '#D2D5DB', '#CDD3D8', '#C8D0D6', '#C2CED4', '#BCCBD1', '#B6C8CF', '#B0C5CD', '#AAC2CC', '#A4BECA', '#9EBBC9', '#99B8C8', '#93B4C6', '#8EB1C5', '#89ADC5', '#85A9C4', '#80A5C3', '#7CA2C2', '#789EC2', '#759AC1', '#7196C1', '#6E92C0', '#6C8EBF', '#698ABF', '#6786BE', '#6682BD', '#647DBC', '#6379BB', '#6275BA', '#6170B9', '#606CB8', '#6067B6', '#5F62B4', '#5F5EB3', '#5F59B1', '#5E54AE', '#5E4FAC', '#5E4BA9', '#5E46A6', '#5D41A3', '#5D3CA0', '#5C379C', '#5B3298', '#5A2E93', '#59298E', '#572588', '#562182', '#531E7C', '#511A75', '#4E186F', '#4B1668', '#471461', '#44135A', '#411254', '#3D114E', '#3A1149', '#371144', '#351140', '#33113C', '#311339', '#301437', '#331237', '#351138', '#381139', '#3B113B', '#3F123D', '#43123E', '#481341', '#4D1443', '#521545', '#571647', '#5C1749', '#61184B', '#67194C', '#6C1B4E', '#711D4F', '#761F4F', '#7B2150', '#802350', '#852650', '#8A2950', '#8E2C50', '#922F50', '#963350', '#9A3750', '#9E3B50', '#A13F50', '#A54350', '#A84750', '#AB4B50', '#AE5051', '#B15452', '#B35953', '#B65D54', '#B86255', '#BA6657', '#BC6B59', '#BE705B', '#C0755E', '#C27A61', '#C37F64', '#C58468', '#C6896C', '#C78E71', '#C89275', '#C9977B', '#CA9C80', '#CCA186', '#CDA68C', '#CEAB92', '#CFAF99', '#D1B4A0', '#D2B8A7', '#D4BDAD', '#D6C1B4', '#D8C5BB', '#D9C9C2', '#DBCCC8', '#DDD0CE', '#DED3D3', '#DFD5D8', '#E0D7DB', '#E1D8DF', '#E2D9E1'],
<ide> positions: [0.0000000000, 0.0078740157, 0.0157480315, 0.0236220472, 0.0314960630, 0.0393700787, 0.0472440945, 0.0551181102, 0.0629921260, 0.0708661417, 0.0787401575, 0.0866141732, 0.0944881890, 0.1023622047, 0.1102362205, 0.1181102362, 0.1259842520, 0.1338582677, 0.1417322835, 0.1496062992, 0.1574803150, 0.1653543307, 0.1732283465, 0.1811023622, 0.1889763780, 0.1968503937, 0.2047244094, 0.2125984252, 0.2204724409, 0.2283464567, 0.2362204724, 0.2440944882, 0.2519685039, 0.2598425197, 0.2677165354, 0.2755905512, 0.2834645669, 0.2913385827, 0.2992125984, 0.3070866142, 0.3149606299, 0.3228346457, 0.3307086614, 0.3385826772, 0.3464566929, 0.3543307087, 0.3622047244, 0.3700787402, 0.3779527559, 0.3858267717, 0.3937007874, 0.4015748031, 0.4094488189, 0.4173228346, 0.4251968504, 0.4330708661, 0.4409448819, 0.4488188976, 0.4566929134, 0.4645669291, 0.4724409449, 0.4803149606, 0.4881889764, 0.4960629921, 0.5039370079, 0.5118110236, 0.5196850394, 0.5275590551, 0.5354330709, 0.5433070866, 0.5511811024, 0.5590551181, 0.5669291339, 0.5748031496, 0.5826771654, 0.5905511811, 0.5984251969, 0.6062992126, 0.6141732283, 0.6220472441, 0.6299212598, 0.6377952756, 0.6456692913, 0.6535433071, 0.6614173228, 0.6692913386, 0.6771653543, 0.6850393701, 0.6929133858, 0.7007874016, 0.7086614173, 0.7165354331, 0.7244094488, 0.7322834646, 0.7401574803, 0.7480314961, 0.7559055118, 0.7637795276, 0.7716535433, 0.7795275591, 0.7874015748, 0.7952755906, 0.8031496063, 0.8110236220, 0.8188976378, 0.8267716535, 0.8346456693, 0.8425196850, 0.8503937008, 0.8582677165, 0.8661417323, 0.8740157480, 0.8818897638, 0.8897637795, 0.8976377953, 0.9055118110, 0.9133858268, 0.9212598425, 0.9291338583, 0.9370078740, 0.9448818898, 0.9527559055, 0.9606299213, 0.9685039370, 0.9763779528, 0.9842519685, 0.9921259843, 1.0000000000]
<ide> },
<del> "twilight_shifted": {
<del> colors: ["#301437", "#32123A", "#34113E", "#361142", "#391146", "#3C114B", "#3F1251", "#421257", "#46145E", "#491564", "#4C176B", "#4F1972", "#521C79", "#551F7F", "#572385", "#58278B", "#5A2B90", "#5B3095", "#5C359A", "#5D3A9E", "#5D3EA1", "#5E43A5", "#5E48A8", "#5E4DAB", "#5E52AD", "#5F57B0", "#5F5BB2", "#5F60B4", "#5F65B5", "#6069B7", "#606EB8", "#6172BA", "#6277BB", "#637BBC", "#657FBD", "#6684BD", "#6888BE", "#6B8CBF", "#6D90C0", "#7094C0", "#7398C1", "#769CC1", "#7AA0C2", "#7EA4C3", "#82A7C3", "#87ABC4", "#8CAFC5", "#91B2C6", "#96B6C7", "#9CB9C8", "#A1BDC9", "#A7C0CB", "#ADC3CD", "#B3C6CE", "#B9C9D0", "#BFCCD3", "#C5CFD5", "#CBD2D7", "#D0D4D9", "#D4D6DC", "#D8D8DE", "#DCD9DF", "#DED9E1", "#E1D9E2", "#E2D9E1", "#E1D8DF", "#E0D7DB", "#DFD5D8", "#DED3D3", "#DDD0CE", "#DBCCC8", "#D9C9C2", "#D8C5BB", "#D6C1B4", "#D4BDAD", "#D2B8A7", "#D1B4A0", "#CFAF99", "#CEAB92", "#CDA68C", "#CCA186", "#CA9C80", "#C9977B", "#C89275", "#C78E71", "#C6896C", "#C58468", "#C37F64", "#C27A61", "#C0755E", "#BE705B", "#BC6B59", "#BA6657", "#B86255", "#B65D54", "#B35953", "#B15452", "#AE5051", "#AB4B50", "#A84750", "#A54350", "#A13F50", "#9E3B50", "#9A3750", "#963350", "#922F50", "#8E2C50", "#8A2950", "#852650", "#802350", "#7B2150", "#761F4F", "#711D4F", "#6C1B4E", "#67194C", "#61184B", "#5C1749", "#571647", "#521545", "#4D1443", "#481341", "#43123E", "#3F123D", "#3B113B", "#381139", "#351138", "#331237", "#301437"],
<add> twilight_shifted: {
<add> colors: ['#301437', '#32123A', '#34113E', '#361142', '#391146', '#3C114B', '#3F1251', '#421257', '#46145E', '#491564', '#4C176B', '#4F1972', '#521C79', '#551F7F', '#572385', '#58278B', '#5A2B90', '#5B3095', '#5C359A', '#5D3A9E', '#5D3EA1', '#5E43A5', '#5E48A8', '#5E4DAB', '#5E52AD', '#5F57B0', '#5F5BB2', '#5F60B4', '#5F65B5', '#6069B7', '#606EB8', '#6172BA', '#6277BB', '#637BBC', '#657FBD', '#6684BD', '#6888BE', '#6B8CBF', '#6D90C0', '#7094C0', '#7398C1', '#769CC1', '#7AA0C2', '#7EA4C3', '#82A7C3', '#87ABC4', '#8CAFC5', '#91B2C6', '#96B6C7', '#9CB9C8', '#A1BDC9', '#A7C0CB', '#ADC3CD', '#B3C6CE', '#B9C9D0', '#BFCCD3', '#C5CFD5', '#CBD2D7', '#D0D4D9', '#D4D6DC', '#D8D8DE', '#DCD9DF', '#DED9E1', '#E1D9E2', '#E2D9E1', '#E1D8DF', '#E0D7DB', '#DFD5D8', '#DED3D3', '#DDD0CE', '#DBCCC8', '#D9C9C2', '#D8C5BB', '#D6C1B4', '#D4BDAD', '#D2B8A7', '#D1B4A0', '#CFAF99', '#CEAB92', '#CDA68C', '#CCA186', '#CA9C80', '#C9977B', '#C89275', '#C78E71', '#C6896C', '#C58468', '#C37F64', '#C27A61', '#C0755E', '#BE705B', '#BC6B59', '#BA6657', '#B86255', '#B65D54', '#B35953', '#B15452', '#AE5051', '#AB4B50', '#A84750', '#A54350', '#A13F50', '#9E3B50', '#9A3750', '#963350', '#922F50', '#8E2C50', '#8A2950', '#852650', '#802350', '#7B2150', '#761F4F', '#711D4F', '#6C1B4E', '#67194C', '#61184B', '#5C1749', '#571647', '#521545', '#4D1443', '#481341', '#43123E', '#3F123D', '#3B113B', '#381139', '#351138', '#331237', '#301437'],
<ide> positions: [0.0000000000, 0.0078740157, 0.0157480315, 0.0236220472, 0.0314960630, 0.0393700787, 0.0472440945, 0.0551181102, 0.0629921260, 0.0708661417, 0.0787401575, 0.0866141732, 0.0944881890, 0.1023622047, 0.1102362205, 0.1181102362, 0.1259842520, 0.1338582677, 0.1417322835, 0.1496062992, 0.1574803150, 0.1653543307, 0.1732283465, 0.1811023622, 0.1889763780, 0.1968503937, 0.2047244094, 0.2125984252, 0.2204724409, 0.2283464567, 0.2362204724, 0.2440944882, 0.2519685039, 0.2598425197, 0.2677165354, 0.2755905512, 0.2834645669, 0.2913385827, 0.2992125984, 0.3070866142, 0.3149606299, 0.3228346457, 0.3307086614, 0.3385826772, 0.3464566929, 0.3543307087, 0.3622047244, 0.3700787402, 0.3779527559, 0.3858267717, 0.3937007874, 0.4015748031, 0.4094488189, 0.4173228346, 0.4251968504, 0.4330708661, 0.4409448819, 0.4488188976, 0.4566929134, 0.4645669291, 0.4724409449, 0.4803149606, 0.4881889764, 0.4960629921, 0.5039370079, 0.5118110236, 0.5196850394, 0.5275590551, 0.5354330709, 0.5433070866, 0.5511811024, 0.5590551181, 0.5669291339, 0.5748031496, 0.5826771654, 0.5905511811, 0.5984251969, 0.6062992126, 0.6141732283, 0.6220472441, 0.6299212598, 0.6377952756, 0.6456692913, 0.6535433071, 0.6614173228, 0.6692913386, 0.6771653543, 0.6850393701, 0.6929133858, 0.7007874016, 0.7086614173, 0.7165354331, 0.7244094488, 0.7322834646, 0.7401574803, 0.7480314961, 0.7559055118, 0.7637795276, 0.7716535433, 0.7795275591, 0.7874015748, 0.7952755906, 0.8031496063, 0.8110236220, 0.8188976378, 0.8267716535, 0.8346456693, 0.8425196850, 0.8503937008, 0.8582677165, 0.8661417323, 0.8740157480, 0.8818897638, 0.8897637795, 0.8976377953, 0.9055118110, 0.9133858268, 0.9212598425, 0.9291338583, 0.9370078740, 0.9448818898, 0.9527559055, 0.9606299213, 0.9685039370, 0.9763779528, 0.9842519685, 0.9921259843, 1.0000000000]
<ide> },
<ide> };
|
|
Java
|
apache-2.0
|
c4305e1a14acbb5c862ca47041ba7e598066b2ed
| 0 |
chrisblutz/TrinityLang
|
package com.github.chrisblutz.trinity.natives;
import com.github.chrisblutz.trinity.lang.ClassRegistry;
import com.github.chrisblutz.trinity.lang.TYClass;
import com.github.chrisblutz.trinity.lang.TYMethod;
import com.github.chrisblutz.trinity.lang.TYObject;
import com.github.chrisblutz.trinity.lang.errors.TYError;
import com.github.chrisblutz.trinity.lang.errors.TYSyntaxError;
import com.github.chrisblutz.trinity.lang.errors.stacktrace.TYStackTrace;
import com.github.chrisblutz.trinity.lang.procedures.ProcedureAction;
import com.github.chrisblutz.trinity.lang.procedures.TYProcedure;
import com.github.chrisblutz.trinity.lang.scope.TYRuntime;
import com.github.chrisblutz.trinity.lang.types.arrays.TYArray;
import com.github.chrisblutz.trinity.lang.types.bool.TYBoolean;
import com.github.chrisblutz.trinity.lang.types.numeric.TYFloat;
import com.github.chrisblutz.trinity.lang.types.numeric.TYInt;
import com.github.chrisblutz.trinity.lang.types.numeric.TYLong;
import com.github.chrisblutz.trinity.lang.types.strings.TYString;
import java.util.*;
/**
* This class houses the central API for native
* methods in Trinity.
*
* @author Christopher Lutz
*/
public class TrinityNatives {
private static Map<String, List<NativeAction>> pendingActions = new HashMap<>();
private static Map<String, TYMethod> methods = new HashMap<>();
private static Map<String, TYClass> pendingLoads = new HashMap<>();
private static Map<String, Boolean> pendingSecure = new HashMap<>();
private static Map<String, String> pendingLoadFiles = new HashMap<>();
private static Map<String, Integer> pendingLoadLines = new HashMap<>();
private static Map<String, ProcedureAction> globals = new HashMap<>();
public static void registerMethod(String className, String methodName, boolean staticMethod, String[] mandatoryParams, Map<String, ProcedureAction> optionalParams, String blockParam, ProcedureAction action) {
ProcedureAction actionWithStackTrace = (runtime, thisObj, params) -> {
TYStackTrace.add(className, methodName, null, 0);
TYObject result = action.onAction(runtime, thisObj, params);
TYStackTrace.pop();
return result;
};
List<String> mandatoryParamsList;
if (mandatoryParams != null) {
mandatoryParamsList = Arrays.asList(mandatoryParams);
} else {
mandatoryParamsList = new ArrayList<>();
}
if (optionalParams == null) {
optionalParams = new TreeMap<>();
}
TYProcedure procedure = new TYProcedure(actionWithStackTrace, mandatoryParamsList, optionalParams, blockParam);
TYMethod method = new TYMethod(methodName, staticMethod, true, ClassRegistry.getClass(className), procedure);
String fullName = className + "." + methodName;
methods.put(fullName, method);
}
public static void registerMethodPendingLoad(String pendingClassName, String className, String methodName, boolean staticMethod, String[] mandatoryParams, Map<String, ProcedureAction> optionalParams, String blockParam, ProcedureAction action) {
performPendingLoad(pendingClassName, () -> registerMethod(className, methodName, staticMethod, mandatoryParams, optionalParams, blockParam, action));
}
public static void registerGlobal(String name, ProcedureAction action) {
globals.put(name, action);
}
public static void registerGlobalPendingLoad(String pendingClassName, String name, ProcedureAction action) {
performPendingLoad(pendingClassName, () -> registerGlobal(name, action));
}
public static void performPendingLoad(String className, NativeAction action) {
if (ClassRegistry.classExists(className)) {
action.onAction();
} else {
if (!pendingActions.containsKey(className)) {
pendingActions.put(className, new ArrayList<>());
}
pendingActions.get(className).add(action);
}
}
public static void doLoad(String name, boolean secureMethod, TYClass current, String fileName, int lineNumber) {
if (methods.containsKey(name)) {
addToClass(name, secureMethod, current, fileName, lineNumber);
} else {
pendingLoads.put(name, current);
pendingSecure.put(name, secureMethod);
pendingLoadFiles.put(name, fileName);
pendingLoadLines.put(name, lineNumber);
}
}
private static void addToClass(String name, boolean secureMethod, TYClass current, String fileName, int lineNumber) {
if (methods.containsKey(name)) {
TYMethod method = methods.get(name);
method.setSecureMethod(secureMethod);
current.registerMethod(method);
} else {
TYSyntaxError error = new TYSyntaxError("Trinity.Errors.ParseError", "Native method " + name + " not found.", fileName, lineNumber);
error.throwError();
}
}
public static void triggerActionsPendingLoad(String className) {
if (pendingActions.containsKey(className)) {
for (NativeAction action : pendingActions.get(className)) {
action.onAction();
}
}
for (String str : pendingLoads.keySet()) {
if (methods.containsKey(str)) {
addToClass(str, pendingSecure.get(str), pendingLoads.get(str), pendingLoadFiles.get(str), pendingLoadLines.get(str));
pendingLoads.remove(str);
pendingSecure.remove(str);
pendingLoadFiles.remove(str);
pendingLoadLines.remove(str);
}
}
}
public static ProcedureAction getGlobalProcedureAction(String name) {
return globals.get(name);
}
/**
* This method wraps native types inside Trinity's
* object format ({@code TYObject}).
* <br>
* <br>
* Possible Types:<br>
* - Integer<br>
* - Float/Double<br>
* - Long<br>
* - String<br>
* - Boolean<br>
*
* @param obj The object to be converted into a native Trinity object
* @return The converted {@code TYObject} form of the original object
*/
public static TYObject getObjectFor(Object obj) {
if (obj == null) {
return TYObject.NIL;
} else if (obj instanceof Integer) {
return new TYInt((Integer) obj);
} else if (obj instanceof Float) {
return new TYFloat((Float) obj);
} else if (obj instanceof Double) {
return new TYFloat((Double) obj);
} else if (obj instanceof Long) {
return new TYLong((Long) obj);
} else if (obj instanceof String) {
return new TYString((String) obj);
} else if (obj instanceof Boolean) {
if ((Boolean) obj) {
return TYBoolean.TRUE;
} else {
return TYBoolean.FALSE;
}
}
TYSyntaxError error = new TYSyntaxError("Trinity.Errors.NativeTypeError", "Trinity does not have native type-conversion utilities for " + obj.getClass() + ".", null, 0);
error.throwError();
return TYObject.NIL;
}
/**
* This method wraps an array of native types inside Trinity's
* array format ({@code TYObject}). All objects inside are converted
* into Trinity's native type of them.
* <br>
* <br>
* Possible Types:<br>
* - Integer<br>
* - Float/Double<br>
* - Long<br>
* - String<br>
* - Boolean<br>
*
* @param arr The array of Objects to be converted into a native array of Trinity object
* @return The converted {@code TYArray} form of the original form, containing {@code TYObject} forms of
* the original objects
*/
public static TYArray getArrayFor(Object[] arr) {
List<TYObject> objects = new ArrayList<>();
for (Object o : arr) {
objects.add(getObjectFor(o));
}
return new TYArray(objects);
}
public static TYObject newInstance(String className, TYObject... args) {
return newInstance(className, new TYRuntime(), args);
}
public static TYObject newInstance(String className, TYRuntime runtime, TYObject... args) {
return ClassRegistry.getClass(className).tyInvoke("new", runtime, null, null, TYObject.NONE, args);
}
public static TYObject call(String className, String methodName, TYRuntime runtime, TYObject thisObj, TYObject... args) {
if (ClassRegistry.classExists(className)) {
return ClassRegistry.getClass(className).tyInvoke(methodName, runtime, null, null, thisObj, args);
} else {
TYError error = new TYError("Trinity.Errors.ClassNotFoundError", "Class " + className + " does not exist.");
error.throwError();
}
return TYObject.NIL;
}
public static <T extends TYObject> T cast(Class<T> desiredClass, TYObject object) {
if (desiredClass.isInstance(object)) {
return desiredClass.cast(object);
} else {
TYError error = new TYError("Trinity.Errors.InvalidTypeError", "Unexpected value of type " + object.getObjectClass().getName() + " found.");
error.throwError();
// This will throw an error, but the program will exit at the line above, never reaching this point
return desiredClass.cast(object);
}
}
public static int toInt(TYObject tyObject) {
if (tyObject instanceof TYLong) {
return Math.toIntExact(((TYLong) tyObject).getInternalLong());
} else if (tyObject instanceof TYFloat) {
return (int) ((TYFloat) tyObject).getInternalDouble();
} else if (tyObject instanceof TYString) {
return Integer.parseInt(((TYString) tyObject).getInternalString());
} else {
return TrinityNatives.cast(TYInt.class, tyObject).getInternalInteger();
}
}
public static long toLong(TYObject tyObject) {
if (tyObject instanceof TYInt) {
return ((TYInt) tyObject).getInternalInteger();
} else if (tyObject instanceof TYFloat) {
return (long) ((TYFloat) tyObject).getInternalDouble();
} else if (tyObject instanceof TYString) {
return Long.parseLong(((TYString) tyObject).getInternalString());
} else {
return TrinityNatives.cast(TYLong.class, tyObject).getInternalLong();
}
}
public static double toFloat(TYObject tyObject) {
if (tyObject instanceof TYInt) {
return ((TYInt) tyObject).getInternalInteger();
} else if (tyObject instanceof TYLong) {
return ((TYLong) tyObject).getInternalLong();
} else if (tyObject instanceof TYString) {
return Double.parseDouble(((TYString) tyObject).getInternalString());
} else {
return TrinityNatives.cast(TYFloat.class, tyObject).getInternalDouble();
}
}
public static String toString(TYObject tyObject, TYRuntime runtime) {
if (tyObject instanceof TYString) {
return ((TYString) tyObject).getInternalString();
} else {
TYString tyString = cast(TYString.class, tyObject.tyInvoke("toString", runtime, null, null));
return tyString.getInternalString();
}
}
public static boolean toBoolean(TYObject tyObject) {
if (tyObject == TYObject.NIL || tyObject == TYObject.NONE) {
return false;
} else if (tyObject instanceof TYBoolean) {
return ((TYBoolean) tyObject).getInternalBoolean();
} else if (tyObject instanceof TYInt) {
return ((TYInt) tyObject).getInternalInteger() != 0;
} else if (tyObject instanceof TYLong) {
return ((TYLong) tyObject).getInternalLong() != 0;
} else if (tyObject instanceof TYFloat) {
return ((TYFloat) tyObject).getInternalDouble() != 0;
} else {
return true;
}
}
}
|
src/main/java/com/github/chrisblutz/trinity/natives/TrinityNatives.java
|
package com.github.chrisblutz.trinity.natives;
import com.github.chrisblutz.trinity.lang.ClassRegistry;
import com.github.chrisblutz.trinity.lang.TYClass;
import com.github.chrisblutz.trinity.lang.TYMethod;
import com.github.chrisblutz.trinity.lang.TYObject;
import com.github.chrisblutz.trinity.lang.errors.TYError;
import com.github.chrisblutz.trinity.lang.errors.TYSyntaxError;
import com.github.chrisblutz.trinity.lang.errors.stacktrace.TYStackTrace;
import com.github.chrisblutz.trinity.lang.procedures.ProcedureAction;
import com.github.chrisblutz.trinity.lang.procedures.TYProcedure;
import com.github.chrisblutz.trinity.lang.scope.TYRuntime;
import com.github.chrisblutz.trinity.lang.types.arrays.TYArray;
import com.github.chrisblutz.trinity.lang.types.bool.TYBoolean;
import com.github.chrisblutz.trinity.lang.types.numeric.TYFloat;
import com.github.chrisblutz.trinity.lang.types.numeric.TYInt;
import com.github.chrisblutz.trinity.lang.types.numeric.TYLong;
import com.github.chrisblutz.trinity.lang.types.strings.TYString;
import java.util.*;
/**
* This class houses the central API for native
* methods in Trinity.
*
* @author Christopher Lutz
*/
public class TrinityNatives {
private static Map<String, List<NativeAction>> pendingActions = new HashMap<>();
private static Map<String, TYMethod> methods = new HashMap<>();
private static Map<String, TYClass> pendingLoads = new HashMap<>();
private static Map<String, Boolean> pendingSecure = new HashMap<>();
private static Map<String, String> pendingLoadFiles = new HashMap<>();
private static Map<String, Integer> pendingLoadLines = new HashMap<>();
private static Map<String, ProcedureAction> globals = new HashMap<>();
public static void registerMethod(String className, String methodName, boolean staticMethod, String[] mandatoryParams, Map<String, ProcedureAction> optionalParams, String blockParam, ProcedureAction action) {
ProcedureAction actionWithStackTrace = (runtime, thisObj, params) -> {
TYStackTrace.add(className, methodName, null, 0);
TYObject result = action.onAction(runtime, thisObj, params);
TYStackTrace.pop();
return result;
};
List<String> mandatoryParamsList;
if (mandatoryParams != null) {
mandatoryParamsList = Arrays.asList(mandatoryParams);
} else {
mandatoryParamsList = new ArrayList<>();
}
if (optionalParams == null) {
optionalParams = new TreeMap<>();
}
TYProcedure procedure = new TYProcedure(actionWithStackTrace, mandatoryParamsList, optionalParams, blockParam);
TYMethod method = new TYMethod(methodName, staticMethod, true, ClassRegistry.getClass(className), procedure);
String fullName = className + "." + methodName;
methods.put(fullName, method);
}
public static void registerMethodPendingLoad(String pendingClassName, String className, String methodName, boolean staticMethod, String[] mandatoryParams, Map<String, ProcedureAction> optionalParams, String blockParam, ProcedureAction action) {
performPendingLoad(pendingClassName, () -> registerMethod(className, methodName, staticMethod, mandatoryParams, optionalParams, blockParam, action));
}
public static void registerGlobal(String name, ProcedureAction action) {
globals.put(name, action);
}
public static void registerGlobalPendingLoad(String pendingClassName, String name, ProcedureAction action) {
performPendingLoad(pendingClassName, () -> registerGlobal(name, action));
}
public static void performPendingLoad(String className, NativeAction action) {
if (ClassRegistry.classExists(className)) {
action.onAction();
} else {
if (!pendingActions.containsKey(className)) {
pendingActions.put(className, new ArrayList<>());
}
pendingActions.get(className).add(action);
}
}
public static void doLoad(String name, boolean secureMethod, TYClass current, String fileName, int lineNumber) {
if (methods.containsKey(name)) {
addToClass(name, secureMethod, current, fileName, lineNumber);
} else {
pendingLoads.put(name, current);
pendingSecure.put(name, secureMethod);
pendingLoadFiles.put(name, fileName);
pendingLoadLines.put(name, lineNumber);
}
}
private static void addToClass(String name, boolean secureMethod, TYClass current, String fileName, int lineNumber) {
if (methods.containsKey(name)) {
TYMethod method = methods.get(name);
method.setSecureMethod(secureMethod);
current.registerMethod(method);
} else {
TYSyntaxError error = new TYSyntaxError("Trinity.Errors.ParseError", "Native method " + name + " not found.", fileName, lineNumber);
error.throwError();
}
}
public static void triggerActionsPendingLoad(String className) {
if (pendingActions.containsKey(className)) {
for (NativeAction action : pendingActions.get(className)) {
action.onAction();
}
}
for (String str : pendingLoads.keySet()) {
if (methods.containsKey(str)) {
addToClass(str, pendingSecure.get(str), pendingLoads.get(str), pendingLoadFiles.get(str), pendingLoadLines.get(str));
pendingLoads.remove(str);
pendingSecure.remove(str);
pendingLoadFiles.remove(str);
pendingLoadLines.remove(str);
}
}
}
public static ProcedureAction getGlobalProcedureAction(String name) {
return globals.get(name);
}
/**
* This method wraps native types inside Trinity's
* object format ({@code TYObject}).
* <br>
* <br>
* Possible Types:<br>
* - Integer<br>
* - Float/Double<br>
* - Long<br>
* - String<br>
* - Boolean<br>
*
* @param obj The object to be converted into a native Trinity object
* @return The converted {@code TYObject} form of the original object
*/
public static TYObject getObjectFor(Object obj) {
if (obj == null) {
return TYObject.NIL;
} else if (obj instanceof Integer) {
return new TYInt((Integer) obj);
} else if (obj instanceof Float) {
return new TYFloat((Float) obj);
} else if (obj instanceof Double) {
return new TYFloat((Double) obj);
} else if (obj instanceof Long) {
return new TYLong((Long) obj);
} else if (obj instanceof String) {
return new TYString((String) obj);
} else if (obj instanceof Boolean) {
if ((Boolean) obj) {
return TYBoolean.TRUE;
} else {
return TYBoolean.FALSE;
}
}
TYSyntaxError error = new TYSyntaxError("Trinity.Errors.NativeTypeError", "Trinity does not have native type-conversion utilities for " + obj.getClass() + ".", null, 0);
error.throwError();
return TYObject.NIL;
}
/**
* This method wraps an array of native types inside Trinity's
* array format ({@code TYObject}). All objects inside are converted
* into Trinity's native type of them.
* <br>
* <br>
* Possible Types:<br>
* - Integer<br>
* - Float/Double<br>
* - Long<br>
* - String<br>
* - Boolean<br>
*
* @param arr The array of Objects to be converted into a native array of Trinity object
* @return The converted {@code TYArray} form of the original form, containing {@code TYObject} forms of
* the original objects
*/
public static TYArray getArrayFor(Object[] arr) {
List<TYObject> objects = new ArrayList<>();
for (Object o : arr) {
objects.add(getObjectFor(o));
}
return new TYArray(objects);
}
public static TYObject newInstance(String className, TYObject... args) {
return newInstance(className, new TYRuntime(), args);
}
public static TYObject newInstance(String className, TYRuntime runtime, TYObject... args) {
return ClassRegistry.getClass(className).tyInvoke("new", runtime, null, null, TYObject.NONE, args);
}
public static <T extends TYObject> T cast(Class<T> desiredClass, TYObject object) {
if (desiredClass.isInstance(object)) {
return desiredClass.cast(object);
} else {
TYError error = new TYError("Trinity.Errors.InvalidTypeError", "Unexpected value of type " + object.getObjectClass().getName() + " found.");
error.throwError();
// This will throw an error, but the program will exit at the line above, never reaching this point
return desiredClass.cast(object);
}
}
public static int toInt(TYObject tyObject) {
if (tyObject instanceof TYLong) {
return Math.toIntExact(((TYLong) tyObject).getInternalLong());
} else if (tyObject instanceof TYFloat) {
return (int) ((TYFloat) tyObject).getInternalDouble();
} else if (tyObject instanceof TYString) {
return Integer.parseInt(((TYString) tyObject).getInternalString());
} else {
return TrinityNatives.cast(TYInt.class, tyObject).getInternalInteger();
}
}
public static long toLong(TYObject tyObject) {
if (tyObject instanceof TYInt) {
return ((TYInt) tyObject).getInternalInteger();
} else if (tyObject instanceof TYFloat) {
return (long) ((TYFloat) tyObject).getInternalDouble();
} else if (tyObject instanceof TYString) {
return Long.parseLong(((TYString) tyObject).getInternalString());
} else {
return TrinityNatives.cast(TYLong.class, tyObject).getInternalLong();
}
}
public static double toFloat(TYObject tyObject) {
if (tyObject instanceof TYInt) {
return ((TYInt) tyObject).getInternalInteger();
} else if (tyObject instanceof TYLong) {
return ((TYLong) tyObject).getInternalLong();
} else if (tyObject instanceof TYString) {
return Double.parseDouble(((TYString) tyObject).getInternalString());
} else {
return TrinityNatives.cast(TYFloat.class, tyObject).getInternalDouble();
}
}
public static String toString(TYObject tyObject, TYRuntime runtime) {
if (tyObject instanceof TYString) {
return ((TYString) tyObject).getInternalString();
} else {
TYString tyString = cast(TYString.class, tyObject.tyInvoke("toString", runtime, null, null));
return tyString.getInternalString();
}
}
public static boolean toBoolean(TYObject tyObject) {
if (tyObject == TYObject.NIL || tyObject == TYObject.NONE) {
return false;
} else if (tyObject instanceof TYBoolean) {
return ((TYBoolean) tyObject).getInternalBoolean();
} else if (tyObject instanceof TYInt) {
return ((TYInt) tyObject).getInternalInteger() != 0;
} else if (tyObject instanceof TYLong) {
return ((TYLong) tyObject).getInternalLong() != 0;
} else if (tyObject instanceof TYFloat) {
return ((TYFloat) tyObject).getInternalDouble() != 0;
} else {
return true;
}
}
}
|
Add method-calling utility to TrinityNatives
|
src/main/java/com/github/chrisblutz/trinity/natives/TrinityNatives.java
|
Add method-calling utility to TrinityNatives
|
<ide><path>rc/main/java/com/github/chrisblutz/trinity/natives/TrinityNatives.java
<ide> return ClassRegistry.getClass(className).tyInvoke("new", runtime, null, null, TYObject.NONE, args);
<ide> }
<ide>
<add> public static TYObject call(String className, String methodName, TYRuntime runtime, TYObject thisObj, TYObject... args) {
<add>
<add> if (ClassRegistry.classExists(className)) {
<add>
<add> return ClassRegistry.getClass(className).tyInvoke(methodName, runtime, null, null, thisObj, args);
<add>
<add> } else {
<add>
<add> TYError error = new TYError("Trinity.Errors.ClassNotFoundError", "Class " + className + " does not exist.");
<add> error.throwError();
<add> }
<add>
<add> return TYObject.NIL;
<add> }
<add>
<ide> public static <T extends TYObject> T cast(Class<T> desiredClass, TYObject object) {
<ide>
<ide> if (desiredClass.isInstance(object)) {
|
|
Java
|
apache-2.0
|
779c0b470e43d4d6200f59581c244a16920c639d
| 0 |
Reidddddd/mo-alluxio,PasaLab/tachyon,jsimsa/alluxio,PasaLab/tachyon,jswudi/alluxio,ShailShah/alluxio,riversand963/alluxio,yuluo-ding/alluxio,maboelhassan/alluxio,bf8086/alluxio,riversand963/alluxio,bf8086/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,aaudiber/alluxio,maobaolong/alluxio,jsimsa/alluxio,wwjiang007/alluxio,bf8086/alluxio,ChangerYoung/alluxio,calvinjia/tachyon,aaudiber/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio,apc999/alluxio,calvinjia/tachyon,maobaolong/alluxio,wwjiang007/alluxio,Alluxio/alluxio,jsimsa/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,calvinjia/tachyon,aaudiber/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,ChangerYoung/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,maobaolong/alluxio,maobaolong/alluxio,yuluo-ding/alluxio,riversand963/alluxio,bf8086/alluxio,PasaLab/tachyon,wwjiang007/alluxio,madanadit/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,calvinjia/tachyon,yuluo-ding/alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio,uronce-cc/alluxio,maobaolong/alluxio,apc999/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,bf8086/alluxio,calvinjia/tachyon,aaudiber/alluxio,PasaLab/tachyon,uronce-cc/alluxio,jswudi/alluxio,PasaLab/tachyon,yuluo-ding/alluxio,riversand963/alluxio,Alluxio/alluxio,jsimsa/alluxio,maboelhassan/alluxio,madanadit/alluxio,Alluxio/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,jsimsa/alluxio,ShailShah/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,madanadit/alluxio,PasaLab/tachyon,WilliamZapata/alluxio,aaudiber/alluxio,Reidddddd/alluxio,Alluxio/alluxio,Alluxio/alluxio,madanadit/alluxio,ChangerYoung/alluxio,Reidddddd/alluxio,aaudiber/alluxio,Reidddddd/alluxio,madanadit/alluxio,maboelhassan/alluxio,bf8086/alluxio,uronce-cc/alluxio,aaudiber/alluxio,apc999/alluxio,ShailShah/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,uronce-cc/alluxio,maboelhassan/alluxio,apc999/alluxio,riversand963/alluxio,ShailShah/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,calvinjia/tachyon,madanadit/alluxio,jswudi/alluxio,riversand963/alluxio,EvilMcJerkface/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,maobaolong/alluxio,wwjiang007/alluxio,jsimsa/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,jswudi/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,madanadit/alluxio,Alluxio/alluxio,WilliamZapata/alluxio,WilliamZapata/alluxio,calvinjia/tachyon,maobaolong/alluxio,jswudi/alluxio,madanadit/alluxio,wwjiang007/alluxio,bf8086/alluxio,apc999/alluxio,Alluxio/alluxio,ShailShah/alluxio,PasaLab/tachyon,jswudi/alluxio,wwjiang007/alluxio,ShailShah/alluxio,WilliamZapata/alluxio,Reidddddd/mo-alluxio,maboelhassan/alluxio
|
/*
* Licensed to the University of California, Berkeley 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 tachyon.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tachyon.Constants;
import tachyon.conf.TachyonConf;
/**
* Common utilities shared by all components in Tachyon.
*/
public final class CommonUtils {
private static final Logger LOG = LoggerFactory.getLogger("");
public static long getCurrentMs() {
return System.currentTimeMillis();
}
public static <T> String listToString(List<T> list) {
StringBuilder sb = new StringBuilder();
for (T s : list) {
sb.append(s).append(" ");
}
return sb.toString();
}
public static String[] toStringArray(ArrayList<String> src) {
String[] ret = new String[src.size()];
return src.toArray(ret);
}
public static void sleepMs(Logger logger, long timeMs) {
sleepMs(logger, timeMs, false);
}
public static void sleepMs(Logger logger, long timeMs, boolean shouldInterrupt) {
try {
Thread.sleep(timeMs);
} catch (InterruptedException e) {
logger.warn(e.getMessage(), e);
if (shouldInterrupt) {
Thread.currentThread().interrupt();
}
}
}
public static void warmUpLoop() {
for (int k = 0; k < 10000000; k ++) {
}
}
/**
* Creates new instance of a class by calling a constructor that receives ctorClassArgs arguments
*
* @param cls the class to create
* @param ctorClassArgs parameters type list of the constructor to initiate, if null default
* constructor will be called
* @param ctorArgs the arguments to pass the constructor
* @return new class object or null if not successful
*/
public static <T> T createNewClassInstance(Class<T> cls, Class<?>[] ctorClassArgs,
Object[] ctorArgs) throws InstantiationException, IllegalAccessException,
NoSuchMethodException, SecurityException, InvocationTargetException {
if (ctorClassArgs == null) {
return cls.newInstance();
}
Constructor<T> ctor = cls.getConstructor(ctorClassArgs);
return ctor.newInstance(ctorArgs);
}
}
|
common/src/main/java/tachyon/util/CommonUtils.java
|
/*
* Licensed to the University of California, Berkeley 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 tachyon.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tachyon.Constants;
import tachyon.conf.TachyonConf;
/**
* Common utilities shared by all components in Tachyon.
*/
public final class CommonUtils {
private static final Logger LOG = LoggerFactory.getLogger("");
public static long getCurrentMs() {
return System.currentTimeMillis();
}
public static <T> String listToString(List<T> list) {
StringBuilder sb = new StringBuilder();
for (T s : list) {
sb.append(s).append(" ");
}
return sb.toString();
}
public static String[] toStringArray(ArrayList<String> src) {
String[] ret = new String[src.size()];
return src.toArray(ret);
}
public static void sleepMs(Logger logger, long timeMs) {
sleepMs(logger, timeMs, false);
}
public static void sleepMs(Logger logger, long timeMs, boolean shouldInterrupt) {
try {
Thread.sleep(timeMs);
} catch (InterruptedException e) {
logger.warn(e.getMessage(), e);
if (shouldInterrupt) {
Thread.currentThread().interrupt();
}
}
}
public static void warmUpLoop() {
for (int k = 0; k < 10000000; k ++) {
}
}
/**
* Creates new instance of a class by calling a constructor that receives ctorClassArgs arguments
*
* @param cls the class to create
* @param ctorClassArgs parameters type list of the constructor to initiate, if null default
* constructor will be called
* @param ctorArgs the arguments to pass the constructor
* @return new class object or null if not successful
*/
public static <T> T createNewClassInstance(Class<T> cls, Class<?>[] ctorClassArgs,
Object[] ctorArgs) throws InstantiationException, IllegalAccessException,
NoSuchMethodException, SecurityException, InvocationTargetException {
if (ctorClassArgs == null) {
return cls.newInstance();
}
Constructor<T> ctor = cls.getConstructor(ctorClassArgs);
return ctor.newInstance(ctorArgs);
}
}
|
adding one line for separate from the javadoc of next function
|
common/src/main/java/tachyon/util/CommonUtils.java
|
adding one line for separate from the javadoc of next function
|
<ide><path>ommon/src/main/java/tachyon/util/CommonUtils.java
<ide> for (int k = 0; k < 10000000; k ++) {
<ide> }
<ide> }
<add>
<ide> /**
<ide> * Creates new instance of a class by calling a constructor that receives ctorClassArgs arguments
<ide> *
|
|
JavaScript
|
mit
|
d7597e3fdbaf280ef5314ef9a78b81d34c1cffb3
| 0 |
xtermjs/xtermjs.org,xtermjs/xtermjs.org,xtermjs/xtermjs.org,xtermjs/xtermjs.org
|
$(function () {
var term = new Terminal();
term.open(document.getElementById('terminal'));
function runFakeTerminal() {
if (term._initialized) {
return;
}
term._initialized = true;
term.prompt = () => {
term.write('\r\n$ ');
};
term.writeln('Welcome to xterm.js');
term.writeln('This is a local terminal emulation, without a real terminal in the back-end.');
term.writeln('Type some keys and commands to play around.');
term.writeln('');
term.prompt();
term.on('key', function(key, ev) {
const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey;
if (ev.keyCode === 13) {
term.prompt();
} else if (ev.keyCode === 8) {
// Do not delete the prompt
if (term._core.buffer.x > 2) {
term.write('\b \b');
}
} else if (printable) {
term.write(key);
}
});
term.on('paste', function(data) {
term.write(data);
});
}
runFakeTerminal();
});
|
js/demo.js
|
$(function () {
var term = new Terminal();
term.open(document.getElementById('terminal'));
function runFakeTerminal() {
if (term._initialized) {
return;
}
term._initialized = true;
term.prompt = () => {
term.write('\r\n$ ');
};
term.writeln('Welcome to xterm.js');
term.writeln('This is a local terminal emulation, without a real terminal in the back-end.');
term.writeln('Type some keys and commands to play around.');
term.writeln('');
term.prompt();
term.on('key', function(key, ev) {
const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey;
if (ev.keyCode === 13) {
term.prompt();
} else if (ev.keyCode === 8) {
// Do not delete the prompt
if (term.x > 2) {
term.write('\b \b');
}
} else if (printable) {
term.write(key);
}
});
term.on('paste', function(data) {
term.write(data);
});
}
runFakeTerminal();
});
|
Fix backspace in demo
Fixes xtermjs/xterm.js#1989
|
js/demo.js
|
Fix backspace in demo
|
<ide><path>s/demo.js
<ide> term.prompt();
<ide> } else if (ev.keyCode === 8) {
<ide> // Do not delete the prompt
<del> if (term.x > 2) {
<add> if (term._core.buffer.x > 2) {
<ide> term.write('\b \b');
<ide> }
<ide> } else if (printable) {
|
|
Java
|
apache-2.0
|
f740755b4dc3b55913ae777cdfe52288a03140d8
| 0 |
tpb1908/HN
|
package com.tpb.hn.viewer.views;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.tpb.hn.R;
/**
* Created by theo on 10/12/16.
*/
public class FloatingFAB extends FloatingActionButton {
private static final String TAG = FloatingFAB.class.getSimpleName();
private float mInitialX, mInitialY, mLastdypc;
private float mAcceleration = 1f;
private Handler mUiHandler = new Handler(Looper.getMainLooper());
private FloatingFABListener mListener;
private FloatingFABState mState = FloatingFABState.DOWN;
private boolean mLongPress = false;
private boolean mInDragRange = false;
public FloatingFAB(Context context) {
super(context);
}
public FloatingFAB(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FloatingFAB(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setListener(FloatingFABListener listener) {
this.mListener = listener;
}
public void setState(FloatingFABState state) {
mState = state;
setImageResource(mState == FloatingFABState.DOWN ? R.drawable.ic_arrow_downward : R.drawable.ic_arrow_upward);
}
private Runnable drag = new Runnable() {
@Override
public void run() {
mListener.fabDrag(mLastdypc * mAcceleration);
if(getY() >= ((View) getParent()).getHeight() - getHeight() || getY() <= getHeight()/2) {
mAcceleration = Math.max(mAcceleration + 0.1f, 2f);
} else {
mAcceleration = 1f;
}
mUiHandler.postDelayed(this, 167);
}
};
private Runnable longPress = new Runnable() {
@Override
public void run() {
mLongPress = true;
mListener.fabLongPressDown(mState);
}
};
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(mListener == null) return super.onTouchEvent(ev);
final float parentHeight = ((View) getParent()).getHeight();
switch(ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialX = ev.getRawX();
mInitialY = ev.getRawY();
mUiHandler.postDelayed(longPress, 300);
mListener.fabDown(mState);
return true;
case MotionEvent.ACTION_MOVE:
moveToPosition(ev);
final float dypc = (ev.getRawY() - mInitialY)/parentHeight;
if(dypc > 0 && (mLastdypc < 0 || !mInDragRange)) {
setImageResource(R.drawable.ic_arrow_downward);
mState = FloatingFABState.DOWN;
mAcceleration = 1f;
} else if(dypc < 0 && (mLastdypc > 0 || !mInDragRange)) {
setImageResource(R.drawable.ic_arrow_upward);
mState = FloatingFABState.UP;
mAcceleration = 1f;
}
if((getY() < parentHeight/3 || getY() > parentHeight - parentHeight/3)) {
if((Math.abs(dypc- mLastdypc) > 0.05f || mLastdypc == 0)) {
mLastdypc = dypc;
mInDragRange = true;
mListener.fabLongPressUp(mState);
mUiHandler.removeCallbacks(longPress);
mUiHandler.post(drag);
}
} else {
setImageResource(R.drawable.ic_close);
mUiHandler.removeCallbacks(drag);
mInDragRange = false;
}
break;
case MotionEvent.ACTION_UP:
mUiHandler.removeCallbacks(longPress);
mUiHandler.removeCallbacks(drag);
if(mLongPress) {
mListener.fabLongPressUp(mState);
mLongPress = false;
} else if(Math.abs((ev.getRawY() - mInitialY))/parentHeight < 0.05f) {
mListener.fabUp(mState);
}
if(!mInDragRange) {
mUiHandler.postDelayed(() -> setImageResource(mState == FloatingFABState.DOWN ?
R.drawable.ic_arrow_downward : R.drawable.ic_arrow_upward),
400);
}
mAcceleration = 1f;
return true;
}
return super.onTouchEvent(ev);
}
private void moveToPosition(MotionEvent movement) {
final int[] location = new int[2];
getLocationOnScreen(location);
final int offsetX = (location[0] - (int) getX());
final int offsetY = (location[1] - (int) getY());
int newX = (int) movement.getRawX() - offsetX - getWidth() / 2;
int newY = (int) movement.getRawY() - offsetY - getHeight() / 2;
if(newX < 0) newX = 0;
if(newX > ((View) getParent()).getWidth() - getWidth()) newX = ((View) getParent()).getWidth() - getWidth();
if(newY < 0) newY = 0;
if(newY > ((View) getParent()).getHeight() - getHeight()) newY = ((View) getParent()).getHeight() - getHeight();
setX(newX);
setY(newY);
}
public interface FloatingFABListener {
void fabDown(FloatingFABState state);
void fabUp(FloatingFABState state);
void fabDrag(float velocitypc);
void fabLongPressDown(FloatingFABState state);
void fabLongPressUp(FloatingFABState state);
}
public enum FloatingFABState {
UP, DOWN
}
}
|
app/src/main/java/com/tpb/hn/viewer/views/FloatingFAB.java
|
package com.tpb.hn.viewer.views;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.design.widget.FloatingActionButton;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.tpb.hn.R;
/**
* Created by theo on 10/12/16.
*/
public class FloatingFAB extends FloatingActionButton {
private static final String TAG = FloatingFAB.class.getSimpleName();
private float mInitialX, mInitialY, mLastDifY;
private float mAcceleration = 1f;
private Handler mUiHandler = new Handler(Looper.getMainLooper());
private FloatingFABListener mListener;
private FloatingFABState mState = FloatingFABState.DOWN;
private boolean mLongPress = false;
private boolean mInDragRange = false;
public FloatingFAB(Context context) {
super(context);
}
public FloatingFAB(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FloatingFAB(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setListener(FloatingFABListener listener) {
this.mListener = listener;
}
public void setState(FloatingFABState state) {
mState = state;
setImageResource(mState == FloatingFABState.DOWN ? R.drawable.ic_arrow_downward : R.drawable.ic_arrow_upward);
}
private Runnable drag = new Runnable() {
@Override
public void run() {
mListener.fabDrag(mLastDifY * mAcceleration);
if(getY() >= ((View) getParent()).getHeight() - getHeight() || getY() <= getHeight()/2) {
mAcceleration = Math.max(mAcceleration + 0.1f, 2f);
} else {
mAcceleration = 1f;
}
mUiHandler.postDelayed(this, 167);
}
};
private Runnable longPress = new Runnable() {
@Override
public void run() {
mLongPress = true;
mListener.fabLongPressDown(mState);
}
};
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(mListener == null) return super.onTouchEvent(ev);
final float parentHeight = ((View) getParent()).getHeight();
switch(ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialX = ev.getRawX();
mInitialY = ev.getRawY();
mUiHandler.postDelayed(longPress, 300);
mListener.fabDown(mState);
return true;
case MotionEvent.ACTION_MOVE:
moveToPosition(ev);
final float dy = (ev.getRawY() - mInitialY)/parentHeight;
if(dy > 0 && (mLastDifY < 0 || !mInDragRange)) {
setImageResource(R.drawable.ic_arrow_downward);
mState = FloatingFABState.DOWN;
mAcceleration = 1f;
} else if(dy < 0 && (mLastDifY > 0 || !mInDragRange)) {
setImageResource(R.drawable.ic_arrow_upward);
mState = FloatingFABState.UP;
mAcceleration = 1f;
}
if((getY() < parentHeight/3 || getY() > parentHeight - parentHeight/3)) {
if((Math.abs(dy-mLastDifY) > 0.05f || mLastDifY == 0)) {
mLastDifY = dy;
mInDragRange = true;
mListener.fabLongPressUp(mState);
mUiHandler.removeCallbacks(longPress);
mUiHandler.post(drag);
}
} else {
setImageResource(R.drawable.ic_close);
mUiHandler.removeCallbacks(drag);
mInDragRange = false;
}
break;
case MotionEvent.ACTION_UP:
mUiHandler.removeCallbacks(longPress);
mUiHandler.removeCallbacks(drag);
if(mLongPress) {
mListener.fabLongPressUp(mState);
mLongPress = false;
} else if(Math.abs((ev.getRawY() - mInitialY))/parentHeight < 0.05f) {
mListener.fabUp(mState);
}
mAcceleration = 1f;
return true;
}
return super.onTouchEvent(ev);
}
private void moveToPosition(MotionEvent movement) {
final int[] location = new int[2];
getLocationOnScreen(location);
final int offsetX = (location[0] - (int) getX());
final int offsetY = (location[1] - (int) getY());
int newX = (int) movement.getRawX() - offsetX - getWidth() / 2;
int newY = (int) movement.getRawY() - offsetY - getHeight() / 2;
if(newX < 0) newX = 0;
if(newX > ((View) getParent()).getWidth() - getWidth()) newX = ((View) getParent()).getWidth() - getWidth();
if(newY < 0) newY = 0;
if(newY > ((View) getParent()).getHeight() - getHeight()) newY = ((View) getParent()).getHeight() - getHeight();
setX(newX);
setY(newY);
}
public interface FloatingFABListener {
void fabDown(FloatingFABState state);
void fabUp(FloatingFABState state);
void fabDrag(float velocitypc);
void fabLongPressDown(FloatingFABState state);
void fabLongPressUp(FloatingFABState state);
}
public enum FloatingFABState {
UP, DOWN
}
}
|
Added resource change when FAB is not in scrolling range.
|
app/src/main/java/com/tpb/hn/viewer/views/FloatingFAB.java
|
Added resource change when FAB is not in scrolling range.
|
<ide><path>pp/src/main/java/com/tpb/hn/viewer/views/FloatingFAB.java
<ide> public class FloatingFAB extends FloatingActionButton {
<ide> private static final String TAG = FloatingFAB.class.getSimpleName();
<ide>
<del> private float mInitialX, mInitialY, mLastDifY;
<add> private float mInitialX, mInitialY, mLastdypc;
<ide> private float mAcceleration = 1f;
<ide> private Handler mUiHandler = new Handler(Looper.getMainLooper());
<ide> private FloatingFABListener mListener;
<ide> private Runnable drag = new Runnable() {
<ide> @Override
<ide> public void run() {
<del> mListener.fabDrag(mLastDifY * mAcceleration);
<add> mListener.fabDrag(mLastdypc * mAcceleration);
<ide> if(getY() >= ((View) getParent()).getHeight() - getHeight() || getY() <= getHeight()/2) {
<ide> mAcceleration = Math.max(mAcceleration + 0.1f, 2f);
<ide> } else {
<ide> return true;
<ide> case MotionEvent.ACTION_MOVE:
<ide> moveToPosition(ev);
<del> final float dy = (ev.getRawY() - mInitialY)/parentHeight;
<del> if(dy > 0 && (mLastDifY < 0 || !mInDragRange)) {
<add> final float dypc = (ev.getRawY() - mInitialY)/parentHeight;
<add> if(dypc > 0 && (mLastdypc < 0 || !mInDragRange)) {
<ide> setImageResource(R.drawable.ic_arrow_downward);
<ide> mState = FloatingFABState.DOWN;
<ide> mAcceleration = 1f;
<del> } else if(dy < 0 && (mLastDifY > 0 || !mInDragRange)) {
<add> } else if(dypc < 0 && (mLastdypc > 0 || !mInDragRange)) {
<ide> setImageResource(R.drawable.ic_arrow_upward);
<ide> mState = FloatingFABState.UP;
<ide> mAcceleration = 1f;
<ide> }
<ide> if((getY() < parentHeight/3 || getY() > parentHeight - parentHeight/3)) {
<del> if((Math.abs(dy-mLastDifY) > 0.05f || mLastDifY == 0)) {
<del> mLastDifY = dy;
<add> if((Math.abs(dypc- mLastdypc) > 0.05f || mLastdypc == 0)) {
<add> mLastdypc = dypc;
<ide> mInDragRange = true;
<ide> mListener.fabLongPressUp(mState);
<ide> mUiHandler.removeCallbacks(longPress);
<ide> mLongPress = false;
<ide> } else if(Math.abs((ev.getRawY() - mInitialY))/parentHeight < 0.05f) {
<ide> mListener.fabUp(mState);
<add> }
<add> if(!mInDragRange) {
<add> mUiHandler.postDelayed(() -> setImageResource(mState == FloatingFABState.DOWN ?
<add> R.drawable.ic_arrow_downward : R.drawable.ic_arrow_upward),
<add> 400);
<add>
<ide> }
<ide> mAcceleration = 1f;
<ide>
|
|
Java
|
agpl-3.0
|
fc2756f3dd74a59c331429d525b3a396f51868fc
| 0 |
kkronenb/kfs,UniversityOfHawaii/kfs,smith750/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,smith750/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,bhutchinson/kfs,smith750/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,kuali/kfs,kuali/kfs,kuali/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,kuali/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,ua-eas/kfs
|
/*
* Copyright 2014 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.ar.document.validation.impl;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
import org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument;
import org.kuali.kfs.module.ar.document.validation.SuspensionCategoryBase;
/**
* Suspension Category that checks to see if the invoice was created after award expiration date.
*/
public class BillDateExceedsAwardStopDateSuspensionCategory extends SuspensionCategoryBase {
/**
* @see org.kuali.kfs.module.ar.document.validation.SuspensionCategory#shouldSuspend(org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument)
*/
@Override
public boolean shouldSuspend(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) {
Date documentDate = new Date(contractsGrantsInvoiceDocument.getFinancialSystemDocumentHeader().getWorkflowCreateDate().getTime());
Date awardEndingDate = contractsGrantsInvoiceDocument.getAward().getAwardEndingDate();
return DateUtils.truncatedCompareTo(documentDate, awardEndingDate, Calendar.DATE) > 0;
}
}
|
work/src/org/kuali/kfs/module/ar/document/validation/impl/BillDateExceedsAwardStopDateSuspensionCategory.java
|
/*
* Copyright 2014 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.ar.document.validation.impl;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
import org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument;
import org.kuali.kfs.module.ar.document.validation.SuspensionCategoryBase;
/**
* Suspension Category that checks to see if the invoice was created after award expiration date.
*/
public class BillDateExceedsAwardStopDateSuspensionCategory extends SuspensionCategoryBase {
/**
* @see org.kuali.kfs.module.ar.document.validation.SuspensionCategory#shouldSuspend(org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument)
*/
@Override
public boolean shouldSuspend(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) {
Date documentDate = new Date(contractsGrantsInvoiceDocument.getDocumentHeader().getWorkflowDocument().getDateCreated().getMillis());
Date awardEndingDate = contractsGrantsInvoiceDocument.getAward().getAwardEndingDate();
return DateUtils.truncatedCompareTo(documentDate, awardEndingDate, Calendar.DATE) > 0;
}
}
|
KFSTI-296,put code review change back, unit tests will be fixed by separate JIRA
|
work/src/org/kuali/kfs/module/ar/document/validation/impl/BillDateExceedsAwardStopDateSuspensionCategory.java
|
KFSTI-296,put code review change back, unit tests will be fixed by separate JIRA
|
<ide><path>ork/src/org/kuali/kfs/module/ar/document/validation/impl/BillDateExceedsAwardStopDateSuspensionCategory.java
<ide> */
<ide> @Override
<ide> public boolean shouldSuspend(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) {
<del> Date documentDate = new Date(contractsGrantsInvoiceDocument.getDocumentHeader().getWorkflowDocument().getDateCreated().getMillis());
<add> Date documentDate = new Date(contractsGrantsInvoiceDocument.getFinancialSystemDocumentHeader().getWorkflowCreateDate().getTime());
<ide> Date awardEndingDate = contractsGrantsInvoiceDocument.getAward().getAwardEndingDate();
<ide>
<ide> return DateUtils.truncatedCompareTo(documentDate, awardEndingDate, Calendar.DATE) > 0;
|
|
Java
|
apache-2.0
|
bf06b5815232b0496b5d64cc77efd05c4707e157
| 0 |
crow-misia/xmlbeans,crow-misia/xmlbeans,crow-misia/xmlbeans
|
/* Copyright 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.xmlbeans.impl.store;
import javax.xml.namespace.QName;
import org.apache.xmlbeans.SystemProperties;
import org.apache.xmlbeans.XmlDocumentProperties;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlOptionCharEscapeMap;
import org.apache.xmlbeans.impl.common.QNameHelper;
import org.apache.xmlbeans.impl.common.EncodingMap;
import java.io.Writer;
import java.io.Reader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.ConcurrentModificationException;
abstract class Saver
{
static final int ROOT = Cur.ROOT;
static final int ELEM = Cur.ELEM;
static final int ATTR = Cur.ATTR;
static final int COMMENT = Cur.COMMENT;
static final int PROCINST = Cur.PROCINST;
static final int TEXT = Cur.TEXT;
protected abstract boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues );
protected abstract void emitFinish ( SaveCur c );
protected abstract void emitText ( SaveCur c );
protected abstract void emitComment ( SaveCur c );
protected abstract void emitProcinst ( SaveCur c );
protected abstract void emitDocType ( String docTypeName, String publicId, String systemId );
protected void syntheticNamespace ( String prefix, String uri, boolean considerDefault ) { }
Saver ( Cur c, XmlOptions options )
{
assert c._locale.entered();
options = XmlOptions.maskNull( options );
_cur = createSaveCur( c, options );
_locale = c._locale;
_version = _locale.version();
_namespaceStack = new ArrayList();
_uriMap = new HashMap();
_prefixMap = new HashMap();
_attrNames = new ArrayList();
_attrValues = new ArrayList ();
// Define implicit xml prefixed namespace
addMapping( "xml", Locale._xml1998Uri );
if (options.hasOption( XmlOptions.SAVE_IMPLICIT_NAMESPACES ))
{
Map m = (Map) options.get( XmlOptions.SAVE_IMPLICIT_NAMESPACES );
for ( Iterator i = m.keySet().iterator() ; i.hasNext() ; )
{
String prefix = (String) i.next();
addMapping( prefix, (String) m.get( prefix ) );
}
}
// define character map for escaped replacements
if (options.hasOption( XmlOptions.SAVE_SUBSTITUTE_CHARACTERS ))
{
_replaceChar = (XmlOptionCharEscapeMap)
options.get( XmlOptions.SAVE_SUBSTITUTE_CHARACTERS);
}
// If the default prefix has not been mapped, do so now
if (getNamespaceForPrefix( "" ) == null)
{
_initialDefaultUri = new String( "" );
addMapping( "", _initialDefaultUri );
}
if (options.hasOption( XmlOptions.SAVE_AGGRESSIVE_NAMESPACES ) &&
!(this instanceof SynthNamespaceSaver))
{
SynthNamespaceSaver saver = new SynthNamespaceSaver( c, options );
while ( saver.process() )
;
if (!saver._synthNamespaces.isEmpty())
_preComputedNamespaces = saver._synthNamespaces;
}
_useDefaultNamespace =
options.hasOption( XmlOptions.SAVE_USE_DEFAULT_NAMESPACE );
_saveNamespacesFirst = options.hasOption( XmlOptions.SAVE_NAMESPACES_FIRST );
if (options.hasOption( XmlOptions.SAVE_SUGGESTED_PREFIXES ))
_suggestedPrefixes = (Map) options.get( XmlOptions.SAVE_SUGGESTED_PREFIXES);
_ancestorNamespaces = _cur.getAncestorNamespaces();
}
private static SaveCur createSaveCur ( Cur c, XmlOptions options )
{
QName synthName = (QName) options.get( XmlOptions.SAVE_SYNTHETIC_DOCUMENT_ELEMENT );
QName fragName = synthName;
if (fragName == null)
{
fragName =
options.hasOption( XmlOptions.SAVE_USE_OPEN_FRAGMENT )
? Locale._openuriFragment
: Locale._xmlFragment;
}
boolean saveInner =
options.hasOption( XmlOptions.SAVE_INNER ) &&
!options.hasOption( XmlOptions.SAVE_OUTER );
Cur start = c.tempCur();
Cur end = c.tempCur();
SaveCur cur = null;
int k = c.kind();
switch ( k )
{
case ROOT :
{
positionToInner( c, start, end );
if (Locale.isFragment( start, end ))
cur = new FragSaveCur( start, end, fragName );
else if (synthName != null)
cur = new FragSaveCur( start, end, synthName );
else
cur = new DocSaveCur( c );
break;
}
case ELEM :
{
if (saveInner)
{
positionToInner( c, start, end );
cur =
new FragSaveCur(
start, end, Locale.isFragment( start, end ) ? fragName : synthName );
}
else if (synthName != null)
{
positionToInner( c, start, end );
cur = new FragSaveCur( start, end, synthName );
}
else
{
start.moveToCur( c );
end.moveToCur( c );
end.skip();
cur = new FragSaveCur( start, end, null );
}
break;
}
}
if (cur == null)
{
assert k < 0 || k == ATTR || k == COMMENT || k == PROCINST || k == TEXT;
if (k < 0)
{
// Save out ""
start.moveToCur( c );
end.moveToCur( c );
}
else if (k == TEXT)
{
start.moveToCur( c );
end.moveToCur( c );
end.next();
}
else if (saveInner)
{
start.moveToCur( c );
start.next();
end.moveToCur( c );
end.toEnd();
}
else if (k == ATTR)
{
start.moveToCur( c );
end.moveToCur( c );
}
else
{
assert k == COMMENT || k == PROCINST;
start.moveToCur( c );
end.moveToCur( c );
end.skip();
}
cur = new FragSaveCur( start, end, fragName );
}
String filterPI = (String) options.get( XmlOptions.SAVE_FILTER_PROCINST );
if (filterPI != null)
cur = new FilterPiSaveCur( cur, filterPI );
if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT ))
cur = new PrettySaveCur( cur, options );
start.release();
end.release();
return cur;
}
private static void positionToInner ( Cur c, Cur start, Cur end )
{
assert c.isContainer();
start.moveToCur( c );
if (!start.toFirstAttr())
start.next();
end.moveToCur( c );
end.toEnd();
}
protected boolean saveNamespacesFirst ( )
{
return _saveNamespacesFirst;
}
protected final boolean process ( )
{
assert _locale.entered();
if (_cur == null)
return false;
if (_version != _locale.version())
throw new ConcurrentModificationException( "Document changed during save" );
switch ( _cur.kind() )
{
case ROOT : { processRoot(); break; }
case ELEM : { processElement(); break; }
case - ELEM : { processFinish (); break; }
case TEXT : { emitText ( _cur ); break; }
case COMMENT : { emitComment ( _cur ); _cur.toEnd(); break; }
case PROCINST : { emitProcinst ( _cur ); _cur.toEnd(); break; }
case - ROOT :
{
_cur.release();
_cur = null;
return false;
}
default : throw new RuntimeException( "Unexpected kind" );
}
_cur.next();
return true;
}
private final void processFinish ( )
{
emitFinish( _cur );
popMappings();
}
private final void processRoot ( )
{
assert _cur.isRoot();
XmlDocumentProperties props = _cur.getDocProps();
String systemId = null;
String docTypeName = null;
if (props != null)
{
systemId = props.getDoctypeSystemId();
docTypeName = props.getDoctypeName();
}
if (systemId != null || docTypeName != null)
{
if (docTypeName == null)
{
_cur.push();
while (!_cur.isElem() && _cur.next())
;
if (_cur.isElem())
docTypeName = _cur.getName().getLocalPart();
_cur.pop();
}
String publicId = props.getDoctypePublicId();
if (docTypeName != null)
emitDocType( docTypeName, publicId, systemId );
}
}
private final void processElement ( )
{
assert _cur.isElem() && _cur.getName() != null;
QName name = _cur.getName();
// Add a new entry to the frontier. If this element has a name
// which has no namespace, then we must make sure that pushing
// the mappings causes the default namespace to be empty
boolean ensureDefaultEmpty = name.getNamespaceURI().length() == 0;
pushMappings( _cur, ensureDefaultEmpty );
//
// There are four things which use mappings:
//
// 1) The element name
// 2) The element value (qname based)
// 3) Attribute names
// 4) The attribute values (qname based)
//
// 1) The element name (not for starts)
ensureMapping( name.getNamespaceURI(), name.getPrefix(), !ensureDefaultEmpty, false );
//
//
//
_attrNames.clear();
_attrValues.clear();
_cur.push();
attrs:
for ( boolean A = _cur.toFirstAttr() ; A ; A = _cur.toNextAttr() )
{
if (_cur.isNormalAttr())
{
QName attrName = _cur.getName();
_attrNames.add( attrName );
for ( int i = _attrNames.size() - 2 ; i >= 0 ; i-- )
{
if (_attrNames.get( i ).equals( attrName ))
{
_attrNames.remove( _attrNames.size() - 1 );
continue attrs;
}
}
_attrValues.add( _cur.getAttrValue() );
ensureMapping( attrName.getNamespaceURI(), attrName.getPrefix(), false, true );
}
}
_cur.pop();
// If I am doing aggressive namespaces and we're emitting a
// container which can contain content, add the namespaces
// we've computed. Basically, I'm making sure the pre-computed
// namespaces are mapped on the first container which has a name.
if (_preComputedNamespaces != null)
{
for ( Iterator i = _preComputedNamespaces.keySet().iterator() ; i.hasNext() ; )
{
String uri = (String) i.next();
String prefix = (String) _preComputedNamespaces.get( uri );
boolean considerDefault = prefix.length() == 0 && !ensureDefaultEmpty;
ensureMapping( uri, prefix, considerDefault, false );
}
// Set to null so we do this once at the top
_preComputedNamespaces = null;
}
if (emitElement( _cur, _attrNames, _attrValues ))
{
popMappings();
_cur.toEnd();
}
}
//
// Layout of namespace stack:
//
// URI Undo
// URI Rename
// Prefix Undo
// Mapping
//
boolean hasMappings ( )
{
int i = _namespaceStack.size();
return i > 0 && _namespaceStack.get( i - 1 ) != null;
}
void iterateMappings ( )
{
_currentMapping = _namespaceStack.size();
while ( _currentMapping > 0 && _namespaceStack.get( _currentMapping - 1 ) != null )
_currentMapping -= 8;
}
boolean hasMapping ( )
{
return _currentMapping < _namespaceStack.size();
}
void nextMapping ( )
{
_currentMapping += 8;
}
String mappingPrefix ( )
{
assert hasMapping();
return (String) _namespaceStack.get( _currentMapping + 6 );
}
String mappingUri ( )
{
assert hasMapping();
return (String) _namespaceStack.get( _currentMapping + 7 );
}
private final void pushMappings ( SaveCur c, boolean ensureDefaultEmpty )
{
assert c.isContainer();
_namespaceStack.add( null );
c.push();
namespaces:
for ( boolean A = c.toFirstAttr() ; A ; A = c.toNextAttr() )
if (c.isXmlns())
addNewFrameMapping( c.getXmlnsPrefix(), c.getXmlnsUri(), ensureDefaultEmpty );
c.pop();
if (_ancestorNamespaces != null)
{
for ( int i = 0 ; i < _ancestorNamespaces.size() ; i += 2 )
{
String prefix = (String) _ancestorNamespaces.get( i );
String uri = (String) _ancestorNamespaces.get( i + 1 );
addNewFrameMapping( prefix, uri, ensureDefaultEmpty );
}
_ancestorNamespaces = null;
}
if (ensureDefaultEmpty)
{
String defaultUri = (String) _prefixMap.get( "" );
// I map the default to "" at the very beginning
assert defaultUri != null;
if (defaultUri.length() > 0)
addMapping( "", "" );
}
}
private final void addNewFrameMapping ( String prefix, String uri, boolean ensureDefaultEmpty )
{
// If the prefix maps to "", this don't include this mapping 'cause it's not well formed.
// Also, if we want to make sure that the default namespace is always "", then check that
// here as well.
if ((prefix.length() == 0 || uri.length() > 0) &&
(!ensureDefaultEmpty || prefix.length() > 0 || uri.length() == 0))
{
// Make sure the prefix is not already mapped in this frame
for ( iterateMappings() ; hasMapping() ; nextMapping() )
if (mappingPrefix().equals( prefix ))
return;
// Also make sure that the prefix declaration is not redundant
// This has the side-effect of making it impossible to set a
// redundant prefix declaration, but seems that it's better
// to just never issue a duplicate prefix declaration.
if (uri.equals(getNamespaceForPrefix(prefix)))
return;
addMapping( prefix, uri );
}
}
private final void addMapping ( String prefix, String uri )
{
assert uri != null;
assert prefix != null;
// If the prefix being mapped here is already mapped to a uri,
// that uri will either go out of scope or be mapped to another
// prefix.
String renameUri = (String) _prefixMap.get( prefix );
String renamePrefix = null;
if (renameUri != null)
{
// See if this prefix is already mapped to this uri. If
// so, then add to the stack, but there is nothing to rename
if (renameUri.equals( uri ))
renameUri = null;
else
{
int i = _namespaceStack.size();
while ( i > 0 )
{
if (_namespaceStack.get( i - 1 ) == null)
{
i--;
continue;
}
if (_namespaceStack.get( i - 7 ).equals( renameUri ))
{
renamePrefix = (String) _namespaceStack.get( i - 8 );
if (renamePrefix == null || !renamePrefix.equals( prefix ))
break;
}
i -= 8;
}
assert i > 0;
}
}
_namespaceStack.add( _uriMap.get( uri ) );
_namespaceStack.add( uri );
if (renameUri != null)
{
_namespaceStack.add( _uriMap.get( renameUri ) );
_namespaceStack.add( renameUri );
}
else
{
_namespaceStack.add( null );
_namespaceStack.add( null );
}
_namespaceStack.add( prefix );
_namespaceStack.add( _prefixMap.get( prefix ) );
_namespaceStack.add( prefix );
_namespaceStack.add( uri );
_uriMap.put( uri, prefix );
_prefixMap.put( prefix, uri );
if (renameUri != null)
_uriMap.put( renameUri, renamePrefix );
}
private final void popMappings ( )
{
for ( ; ; )
{
int i = _namespaceStack.size();
if (i == 0)
break;
if (_namespaceStack.get( i - 1 ) == null)
{
_namespaceStack.remove( i - 1 );
break;
}
Object oldUri = _namespaceStack.get( i - 7 );
Object oldPrefix = _namespaceStack.get( i - 8 );
if (oldPrefix == null)
_uriMap.remove( oldUri );
else
_uriMap.put( oldUri, oldPrefix );
oldPrefix = _namespaceStack.get( i - 4 );
oldUri = _namespaceStack.get( i - 3 );
if (oldUri == null)
_prefixMap.remove( oldPrefix );
else
_prefixMap.put( oldPrefix, oldUri );
String uri = (String) _namespaceStack.get( i - 5 );
if (uri != null)
_uriMap.put( uri, _namespaceStack.get( i - 6 ) );
// Hahahahahaha -- :-(
_namespaceStack.remove( i - 1 );
_namespaceStack.remove( i - 2 );
_namespaceStack.remove( i - 3 );
_namespaceStack.remove( i - 4 );
_namespaceStack.remove( i - 5 );
_namespaceStack.remove( i - 6 );
_namespaceStack.remove( i - 7 );
_namespaceStack.remove( i - 8 );
}
}
private final void dumpMappings ( )
{
for ( int i = _namespaceStack.size() ; i > 0 ; )
{
if (_namespaceStack.get( i - 1 ) == null)
{
System.out.println( "----------------" );
i--;
continue;
}
System.out.print( "Mapping: " );
System.out.print( _namespaceStack.get( i - 2 ) );
System.out.print( " -> " );
System.out.print( _namespaceStack.get( i - 1 ) );
System.out.println();
System.out.print( "Prefix Undo: " );
System.out.print( _namespaceStack.get( i - 4 ) );
System.out.print( " -> " );
System.out.print( _namespaceStack.get( i - 3 ) );
System.out.println();
System.out.print( "Uri Rename: " );
System.out.print( _namespaceStack.get( i - 5 ) );
System.out.print( " -> " );
System.out.print( _namespaceStack.get( i - 6 ) );
System.out.println();
System.out.print( "UriUndo: " );
System.out.print( _namespaceStack.get( i - 7 ) );
System.out.print( " -> " );
System.out.print( _namespaceStack.get( i - 8 ) );
System.out.println();
System.out.println();
i -= 8;
}
}
private final String ensureMapping (
String uri, String candidatePrefix,
boolean considerCreatingDefault, boolean mustHavePrefix )
{
assert uri != null;
// Can be called for no-namespaced things
if (uri.length() == 0)
return null;
String prefix = (String) _uriMap.get( uri );
if (prefix != null && (prefix.length() > 0 || !mustHavePrefix))
return prefix;
//
// I try prefixes from a number of places, in order:
//
// 1) What was passed in
// 2) The optional suggestions (for uri's)
// 3) The default mapping is allowed
// 4) ns#++
//
if (candidatePrefix != null && candidatePrefix.length() == 0)
candidatePrefix = null;
if (candidatePrefix == null || !tryPrefix( candidatePrefix ))
{
if (_suggestedPrefixes != null &&
_suggestedPrefixes.containsKey( uri ) &&
tryPrefix( (String) _suggestedPrefixes.get( uri ) ))
{
candidatePrefix = (String) _suggestedPrefixes.get( uri );
}
else if (considerCreatingDefault && _useDefaultNamespace && tryPrefix( "" ))
candidatePrefix = "";
else
{
String basePrefix = QNameHelper.suggestPrefix( uri );
candidatePrefix = basePrefix;
for ( int i = 1 ; ; i++ )
{
if (tryPrefix( candidatePrefix ))
break;
candidatePrefix = basePrefix + i;
}
}
}
assert candidatePrefix != null;
syntheticNamespace( candidatePrefix, uri, considerCreatingDefault );
addMapping( candidatePrefix, uri );
return candidatePrefix;
}
protected final String getUriMapping ( String uri )
{
assert _uriMap.get( uri ) != null;
return (String) _uriMap.get( uri );
}
String getNonDefaultUriMapping ( String uri )
{
String prefix = (String) _uriMap.get( uri );
if (prefix != null && prefix.length() > 0)
return prefix;
for ( Iterator keys = _prefixMap.keySet().iterator() ; keys.hasNext() ; )
{
prefix = (String) keys.next();
if (prefix.length() > 0 && _prefixMap.get( prefix ).equals( uri ))
return prefix;
}
assert false : "Could not find non-default mapping";
return null;
}
private final boolean tryPrefix ( String prefix )
{
if (prefix == null || Locale.beginsWithXml( prefix ))
return false;
String existingUri = (String) _prefixMap.get( prefix );
// If the prefix is currently mapped, then try another prefix. A
// special case is that of trying to map the default prefix ("").
// Here, there always exists a default mapping. If this is the
// mapping we found, then remap it anyways. I use != to compare
// strings because I want to test for the specific initial default
// uri I added when I initialized the saver.
if (existingUri != null && (prefix.length() > 0 || existingUri != _initialDefaultUri))
return false;
return true;
}
public final String getNamespaceForPrefix ( String prefix )
{
assert !prefix.equals( "xml" ) || _prefixMap.get( prefix ).equals( Locale._xml1998Uri );
return (String) _prefixMap.get( prefix );
}
//
//
//
static final class SynthNamespaceSaver extends Saver
{
LinkedHashMap _synthNamespaces = new LinkedHashMap();
SynthNamespaceSaver ( Cur c, XmlOptions options )
{
super( c, options );
}
protected void syntheticNamespace (
String prefix, String uri, boolean considerCreatingDefault )
{
_synthNamespaces.put( uri, considerCreatingDefault ? "" : prefix );
}
protected boolean emitElement (
SaveCur c, ArrayList attrNames, ArrayList attrValues ) { return false; }
protected void emitFinish ( SaveCur c ) { }
protected void emitText ( SaveCur c ) { }
protected void emitComment ( SaveCur c ) { }
protected void emitProcinst ( SaveCur c ) { }
protected void emitDocType ( String docTypeName, String publicId, String systemId ) { }
}
//
//
//
static final class TextSaver extends Saver
{
TextSaver ( Cur c, XmlOptions options, String encoding )
{
super( c, options );
boolean noSaveDecl =
options != null && options.hasOption( XmlOptions.SAVE_NO_XML_DECL );
if (encoding != null && !noSaveDecl)
{
XmlDocumentProperties props = Locale.getDocProps( c, false );
String version = props == null ? null : props.getVersion();
if (version == null)
version = "1.0";
emit( "<?xml version=\"" );
emit( version );
emit( "\" encoding=\"" + encoding + "\"?>" + _newLine );
}
}
protected boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues )
{
assert c.isElem();
emit( '<' );
emitName( c.getName(), false );
if (saveNamespacesFirst())
emitNamespacesHelper();
for ( int i = 0 ; i < attrNames.size() ; i++ )
emitAttrHelper( (QName) attrNames.get( i ), (String) attrValues.get( i ) );
if (!saveNamespacesFirst())
emitNamespacesHelper();
if (!c.hasChildren() && !c.hasText())
{
emit( "/>" );
return true;
}
else
{
emit( '>' );
return false;
}
}
protected void emitFinish ( SaveCur c )
{
emit( "</" );
emitName( c.getName(), false );
emit( '>' );
}
protected void emitXmlns ( String prefix, String uri )
{
assert prefix != null;
assert uri != null;
emit( "xmlns" );
if (prefix.length() > 0)
{
emit( ":" );
emit( prefix );
}
emit( "=\"" );
// TODO - must encode uri properly
emit( uri );
entitizeAttrValue();
emit( '"' );
}
private void emitNamespacesHelper ( )
{
for ( iterateMappings() ; hasMapping() ; nextMapping() )
{
emit( ' ' );
emitXmlns( mappingPrefix(), mappingUri() );
}
}
private void emitAttrHelper ( QName attrName, String attrValue )
{
emit( ' ' );
emitName( attrName, true );
emit( "=\"" );
emit( attrValue );
entitizeAttrValue();
emit( '"' );
}
protected void emitText ( SaveCur c )
{
assert c.isText();
emit( c );
entitizeContent();
}
protected void emitComment ( SaveCur c )
{
assert c.isComment();
emit( "<!--" );
c.push();
c.next();
emit( c );
c.pop();
entitizeComment();
emit( "-->" );
}
protected void emitProcinst ( SaveCur c )
{
assert c.isProcinst();
emit( "<?" );
// TODO - encoding issues here?
emit( c.getName().getLocalPart() );
c.push();
c.next();
if (c.isText())
{
emit( " " );
emit( c );
entitizeProcinst();
}
c.pop();
emit( "?>" );
}
private void emitLiteral ( String literal )
{
// TODO: systemId production http://www.w3.org/TR/REC-xml/#NT-SystemLiteral
// TODO: publicId production http://www.w3.org/TR/REC-xml/#NT-PubidLiteral
if (literal.indexOf( "\"" ) < 0)
{
emit( "\"" );
emit( literal );
emit( "\"" );
}
else
{
emit( "'" );
emit( literal );
emit( "'" );
}
}
protected void emitDocType ( String docTypeName, String publicId, String systemId )
{
assert docTypeName != null;
emit( "<!DOCTYPE " );
emit( docTypeName );
if (publicId == null && systemId != null)
{
emit( " SYSTEM " );
emitLiteral( systemId );
}
else if (publicId != null)
{
emit( " PUBLIC " );
emitLiteral( publicId );
emit( " " );
emitLiteral( systemId );
}
emit( ">" );
emit( _newLine );
}
//
//
//
private void emitName ( QName name, boolean needsPrefix )
{
assert name != null;
String uri = name.getNamespaceURI();
assert uri != null;
if (uri.length() != 0)
{
String prefix = name.getPrefix();
String mappedUri = getNamespaceForPrefix( prefix );
if (mappedUri == null || !mappedUri.equals( uri ))
prefix = getUriMapping( uri );
// Attrs need a prefix. If I have not found one, then there must be a default
// prefix obscuring the prefix needed for this attr. Find it manually.
// NOTE - Consider keeping the currently mapped default URI separate fromn the
// _urpMap and _prefixMap. This way, I would not have to look it up manually
// here
if (needsPrefix && prefix.length() == 0)
prefix = getNonDefaultUriMapping( uri );
if (prefix.length() > 0)
{
emit( prefix );
emit( ":" );
}
}
assert name.getLocalPart().length() > 0;
emit( name.getLocalPart() );
}
private void emit ( char ch )
{
preEmit( 1 );
_buf[ _in ] = ch;
_in = (_in + 1) % _buf.length;
}
private void emit ( String s )
{
int cch = s == null ? 0 : s.length();
if (preEmit( cch ))
return;
int chunk;
if (_in <= _out || cch < (chunk = _buf.length - _in))
{
s.getChars( 0, cch, _buf, _in );
_in += cch;
}
else
{
s.getChars( 0, chunk, _buf, _in );
s.getChars( chunk, cch, _buf, 0 );
_in = (_in + cch) % _buf.length;
}
}
private void emit ( SaveCur c )
{
if (c.isText())
{
Object src = c.getChars();
int cch = c._cchSrc;
if (preEmit( cch ))
return;
int chunk;
if (_in <= _out || cch < (chunk = _buf.length - _in))
{
CharUtil.getChars( _buf, _in, src, c._offSrc, cch );
_in += cch;
}
else
{
CharUtil.getChars( _buf, _in, src, c._offSrc, chunk );
CharUtil.getChars( _buf, 0, src, c._offSrc + chunk, cch - chunk );
_in = (_in + cch) % _buf.length;
}
}
else
preEmit( 0 );
}
private boolean preEmit ( int cch )
{
assert cch >= 0;
_lastEmitCch = cch;
if (cch == 0)
return true;
if (_free < cch)
resize( cch, -1 );
assert cch <= _free;
int used = getAvailable();
// if we are about to emit and there is noting in the buffer, reset
// the buffer to be at the beginning so as to not grow it anymore
// than needed.
if (used == 0)
{
assert _in == _out;
assert _free == _buf.length;
_in = _out = 0;
}
_lastEmitIn = _in;
_free -= cch;
assert _free >= 0;
return false;
}
private void entitizeContent ( )
{
if (_lastEmitCch == 0)
return;
int i = _lastEmitIn;
final int n = _buf.length;
boolean hasCharToBeReplaced = false;
int count = 0;
char prevChar = 0;
char prevPrevChar = 0;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (ch == '<' || ch == '&')
count++;
else if (prevPrevChar == ']' && prevChar == ']' && ch == '>' )
hasCharToBeReplaced = true;
else if (isBadChar( ch ) || isEscapedChar( ch ))
hasCharToBeReplaced = true;
if (++i == n)
i = 0;
prevPrevChar = prevChar;
prevChar = ch;
}
if (count == 0 && !hasCharToBeReplaced)
return;
i = _lastEmitIn;
//
// Heuristic for knowing when to save out stuff as a CDATA.
//
if (_lastEmitCch > 32 && count > 5 &&
count * 100 / _lastEmitCch > 1)
{
boolean lastWasBracket = _buf[ i ] == ']';
i = replace( i, "<![CDATA[" + _buf[ i ] );
boolean secondToLastWasBracket = lastWasBracket;
lastWasBracket = _buf[ i ] == ']';
if (++i == _buf.length)
i = 0;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (ch == '>' && secondToLastWasBracket && lastWasBracket)
i = replace( i, "]]>><![CDATA[" );
else if (isBadChar( ch ))
i = replace( i, "?" );
else
i++;
secondToLastWasBracket = lastWasBracket;
lastWasBracket = ch == ']';
if (i == _buf.length)
i = 0;
}
emit( "]]>" );
}
else
{
char ch = 0, ch_1 = 0, ch_2;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
ch_2 = ch_1;
ch_1 = ch;
ch = _buf[ i ];
if (ch == '<')
i = replace( i, "<" );
else if (ch == '&')
i = replace( i, "&" );
else if (ch == '>' && ch_1 == ']' && ch_2 == ']')
i = replace( i, ">" );
else if (isBadChar( ch ))
i = replace( i, "?" );
else if (isEscapedChar( ch ))
i = replace( i, _replaceChar.getEscapedString( ch ) );
else
i++;
if (i == _buf.length)
i = 0;
}
}
}
private void entitizeAttrValue ( )
{
if (_lastEmitCch == 0)
return;
int i = _lastEmitIn;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (ch == '<')
i = replace( i, "<" );
else if (ch == '&')
i = replace( i, "&" );
else if (ch == '"')
i = replace( i, """ );
else
i++;
if (i == _buf.length)
i = 0;
}
}
private void entitizeComment ( )
{
if (_lastEmitCch == 0)
return;
int i = _lastEmitIn;
boolean lastWasDash = false;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (isBadChar( ch ))
i = replace( i, "?" );
else if (ch == '-')
{
if (lastWasDash)
{
// Replace "--" with "- " to make well formed
i = replace( i, " " );
lastWasDash = false;
}
else
{
lastWasDash = true;
i++;
}
}
else
{
lastWasDash = false;
i++;
}
if (i == _buf.length)
i = 0;
}
// Because I have only replaced chars with single chars,
// _lastEmitIn will still be ok
int offset = (_lastEmitIn + _lastEmitCch - 1) % _buf.length;
if (_buf[ offset ] == '-')
i = replace( offset, " " );
}
private void entitizeProcinst ( )
{
if (_lastEmitCch == 0)
return;
int i = _lastEmitIn;
boolean lastWasQuestion = false;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (isBadChar( ch ))
i = replace( i, "?" );
if (ch == '>')
{
// TODO - Had to convert to a space here ... imples not well formed XML
if (lastWasQuestion)
i = replace( i, " " );
else
i++;
lastWasQuestion = false;
}
else
{
lastWasQuestion = ch == '?';
i++;
}
if (i == _buf.length)
i = 0;
}
}
/**
* Test if a character is valid in xml character content. See
* http://www.w3.org/TR/REC-xml#NT-Char
*/
private boolean isBadChar ( char ch )
{
return ! (
(ch >= 0x20 && ch <= 0xD7FF ) ||
(ch >= 0xE000 && ch <= 0xFFFD) ||
(ch >= 0x10000 && ch <= 0x10FFFF) ||
(ch == 0x9) || (ch == 0xA) || (ch == 0xD)
);
}
/**
* Test if a character is to be replaced with an escaped value
*/
private boolean isEscapedChar ( char ch )
{
return ( null != _replaceChar && _replaceChar.containsChar( ch ) );
}
private int replace ( int i, String replacement )
{
assert replacement.length() > 0;
int dCch = replacement.length() - 1;
if (dCch == 0)
{
_buf[ i ] = replacement.charAt( 0 );
return i + 1;
}
assert _free >= 0;
if (dCch > _free)
i = resize( dCch, i );
assert _free >= 0;
assert _free >= dCch;
assert getAvailable() > 0;
if (_out > _in && i >= _out)
{
System.arraycopy( _buf, _out, _buf, _out - dCch, i - _out );
_out -= dCch;
i -= dCch;
}
else
{
assert i < _in;
System.arraycopy( _buf, i, _buf, i + dCch, _in - i );
_in += dCch;
}
replacement.getChars( 0, dCch + 1, _buf, i );
_free -= dCch;
assert _free >= 0;
return i + dCch + 1;
}
//
//
//
private int ensure ( int cch )
{
// Even if we're asked to ensure nothing, still try to ensure
// atleast one character so we can determine if we're at the
// end of the stream.
if (cch <= 0)
cch = 1;
int available = getAvailable();
for ( ; available < cch ; available = getAvailable() )
if (!process())
break;
assert available == getAvailable();
// if (available == 0)
// return 0;
return available;
}
int getAvailable ( )
{
return _buf == null ? 0 : _buf.length - _free;
}
private int resize ( int cch, int i )
{
assert _free >= 0;
assert cch > 0;
assert cch > _free;
int newLen = _buf == null ? _initialBufSize : _buf.length * 2;
int used = getAvailable();
while ( newLen - used < cch )
newLen *= 2;
char[] newBuf = new char [ newLen ];
if (used > 0)
{
if (_in > _out)
{
assert i == -1 || (i >= _out && i < _in);
System.arraycopy( _buf, _out, newBuf, 0, used );
i -= _out;
}
else
{
assert i == -1 || (i >= _out || i < _in);
System.arraycopy( _buf, _out, newBuf, 0, used - _in );
System.arraycopy( _buf, 0, newBuf, used - _in, _in );
i = i >= _out ? i - _out : i + _out;
}
_out = 0;
_in = used;
_free += newBuf.length - _buf.length;
}
else
{
_free += newBuf.length;
assert _in == 0 && _out == 0;
assert i == -1;
}
_buf = newBuf;
assert _free >= 0;
return i;
}
public int read ( )
{
if (ensure( 1 ) == 0)
return -1;
assert getAvailable() > 0;
int ch = _buf[ _out ];
_out = (_out + 1) % _buf.length;
_free++;
return ch;
}
public int read ( char[] cbuf, int off, int len )
{
// Check for end of stream even if there is no way to return
// characters because the Reader doc says to return -1 at end of
// stream.
int n;
if ((n = ensure( len )) == 0)
return -1;
if (cbuf == null || len <= 0)
return 0;
if (n < len)
len = n;
if (_out < _in)
{
System.arraycopy( _buf, _out, cbuf, off, len );
}
else
{
int chunk = _buf.length - _out;
if (chunk >= len)
System.arraycopy( _buf, _out, cbuf, off, len );
else
{
System.arraycopy( _buf, _out, cbuf, off, chunk );
System.arraycopy( _buf, 0, cbuf, off + chunk, len - chunk );
}
}
_out = (_out + len) % _buf.length;
_free += len;
assert _free >= 0;
return len;
}
public int write ( Writer writer, int cchMin )
{
while ( getAvailable() < cchMin)
{
if (!process())
break;
}
int charsAvailable = getAvailable();
if (charsAvailable > 0)
{
// I don't want to deal with the circular cases
assert _out == 0;
try
{
writer.write( _buf, 0, charsAvailable );
writer.flush();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
_free += charsAvailable;
assert _free >= 0;
_in = 0;
}
return charsAvailable;
}
public String saveToString ( )
{
// We're gonna build a string. Instead of using StringBuffer, may
// as well use my buffer here. Fill the whole sucker up and
// create a String!
while ( process() )
;
assert _out == 0;
int available = getAvailable();
return available == 0 ? "" : new String( _buf, _out, available );
}
//
//
//
private static final int _initialBufSize = 4096;
private int _lastEmitIn;
private int _lastEmitCch;
private int _free;
private int _in;
private int _out;
private char[] _buf;
}
static final class TextReader extends Reader
{
TextReader ( Cur c, XmlOptions options )
{
_textSaver = new TextSaver( c, options, null );
_locale = c._locale;
_closed = false;
}
public void close ( ) throws IOException { _closed = true; }
public boolean ready ( ) throws IOException { return !_closed; }
public int read ( ) throws IOException
{
checkClosed();
if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read(); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read(); } finally { _locale.exit(); } }
}
public int read ( char[] cbuf ) throws IOException
{
checkClosed();
if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read( cbuf, 0, cbuf == null ? 0 : cbuf.length ); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read( cbuf, 0, cbuf == null ? 0 : cbuf.length ); } finally { _locale.exit(); } }
}
public int read ( char[] cbuf, int off, int len ) throws IOException
{
checkClosed();
if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read( cbuf, off, len ); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read( cbuf, off, len ); } finally { _locale.exit(); } }
}
private void checkClosed ( ) throws IOException
{
if (_closed)
throw new IOException( "Reader has been closed" );
}
private Locale _locale;
private TextSaver _textSaver;
private boolean _closed;
}
static final class InputStreamSaver extends InputStream
{
InputStreamSaver ( Cur c, XmlOptions options )
{
_locale = c._locale;
_closed = false;
assert _locale.entered();
options = XmlOptions.maskNull( options );
_outStreamImpl = new OutputStreamImpl();
String encoding = null;
XmlDocumentProperties props = Locale.getDocProps( c, false );
if (props != null && props.getEncoding() != null)
encoding = EncodingMap.getIANA2JavaMapping( props.getEncoding() );
if (options.hasOption( XmlOptions.CHARACTER_ENCODING ))
encoding = (String) options.get( XmlOptions.CHARACTER_ENCODING );
if (encoding != null)
{
String ianaEncoding = EncodingMap.getJava2IANAMapping( encoding );
if (ianaEncoding != null)
encoding = ianaEncoding;
}
if (encoding == null)
encoding = EncodingMap.getJava2IANAMapping( "UTF8" );
String javaEncoding = EncodingMap.getIANA2JavaMapping( encoding );
if (javaEncoding == null)
throw new IllegalStateException( "Unknown encoding: " + encoding );
try
{
_converter = new OutputStreamWriter( _outStreamImpl, javaEncoding );
}
catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( e );
}
_textSaver = new TextSaver( c, options, encoding );
}
public void close ( ) throws IOException
{
_closed = true;
}
private void checkClosed ( ) throws IOException
{
if (_closed)
throw new IOException( "Stream closed" );
}
// Having the gateway here is kinda slow for the single character case. It may be possible
// to only enter the gate when there are no chars in the buffer.
public int read ( ) throws IOException
{
checkClosed();
if (_locale.noSync()) { _locale.enter(); try { return _outStreamImpl.read(); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _outStreamImpl.read(); } finally { _locale.exit(); } }
}
public int read ( byte[] bbuf, int off, int len ) throws IOException
{
checkClosed();
if (bbuf == null)
throw new NullPointerException( "buf to read into is null" );
if (off < 0 || off > bbuf.length)
throw new IndexOutOfBoundsException( "Offset is not within buf" );
if (_locale.noSync()) { _locale.enter(); try { return _outStreamImpl.read( bbuf, off, len ); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _outStreamImpl.read( bbuf, off, len ); } finally { _locale.exit(); } }
}
private int ensure ( int cbyte )
{
// Even if we're asked to ensure nothing, still try to ensure
// atleast one byte so we can determine if we're at the
// end of the stream.
if (cbyte <= 0)
cbyte = 1;
int bytesAvailable = _outStreamImpl.getAvailable();
for ( ; bytesAvailable < cbyte ;
bytesAvailable = _outStreamImpl.getAvailable() )
{
if (_textSaver.write( _converter, 2048 ) < 2048)
break;
}
bytesAvailable = _outStreamImpl.getAvailable();
if (bytesAvailable == 0)
return 0;
return bytesAvailable;
}
private final class OutputStreamImpl extends OutputStream
{
int read ( )
{
if (InputStreamSaver.this.ensure( 1 ) == 0)
return -1;
assert getAvailable() > 0;
int bite = _buf[ _out ];
_out = (_out + 1) % _buf.length;
_free++;
return bite;
}
int read ( byte[] bbuf, int off, int len )
{
// Check for end of stream even if there is no way to return
// characters because the Reader doc says to return -1 at end of
// stream.
int n;
if ((n = ensure( len )) == 0)
return -1;
if (bbuf == null || len <= 0)
return 0;
if (n < len)
len = n;
if (_out < _in)
{
System.arraycopy( _buf, _out, bbuf, off, len );
}
else
{
int chunk = _buf.length - _out;
if (chunk >= len)
System.arraycopy( _buf, _out, bbuf, off, len );
else
{
System.arraycopy( _buf, _out, bbuf, off, chunk );
System.arraycopy(
_buf, 0, bbuf, off + chunk, len - chunk );
}
}
_out = (_out + len) % _buf.length;
_free += len;
return len;
}
int getAvailable ( )
{
return _buf == null ? 0 : _buf.length - _free;
}
public void write ( int bite )
{
if (_free == 0)
resize( 1 );
assert _free > 0;
_buf[ _in ] = (byte) bite;
_in = (_in + 1) % _buf.length;
_free--;
}
public void write ( byte[] buf, int off, int cbyte )
{
assert cbyte >= 0;
if (cbyte == 0)
return;
if (_free < cbyte)
resize( cbyte );
if (_in == _out)
{
assert getAvailable() == 0;
assert _free == _buf.length - getAvailable();
_in = _out = 0;
}
int chunk;
if (_in <= _out || cbyte < (chunk = _buf.length - _in))
{
System.arraycopy( buf, off, _buf, _in, cbyte );
_in += cbyte;
}
else
{
System.arraycopy( buf, off, _buf, _in, chunk );
System.arraycopy(
buf, off + chunk, _buf, 0, cbyte - chunk );
_in = (_in + cbyte) % _buf.length;
}
_free -= cbyte;
}
void resize ( int cbyte )
{
assert cbyte > _free;
int newLen = _buf == null ? _initialBufSize : _buf.length * 2;
int used = getAvailable();
while ( newLen - used < cbyte )
newLen *= 2;
byte[] newBuf = new byte [ newLen ];
if (used > 0)
{
if (_out == _in)
System.arraycopy( _buf, 0, newBuf, 0, used );
else if (_in > _out)
System.arraycopy( _buf, _out, newBuf, 0, used );
else
{
System.arraycopy(
_buf, _out, newBuf, 0, used - _in );
System.arraycopy(
_buf, 0, newBuf, used - _in, _in );
}
_out = 0;
_in = used;
_free += newBuf.length - _buf.length;
}
else
{
_free += newBuf.length;
assert _in == 0 && _out == 0;
}
_buf = newBuf;
}
private static final int _initialBufSize = 4096;
int _free;
int _in;
int _out;
byte[] _buf;
}
private Locale _locale;
private boolean _closed;
private OutputStreamImpl _outStreamImpl;
private TextSaver _textSaver;
private OutputStreamWriter _converter;
}
static final class SaxSaver extends Saver
{
SaxSaver ( Cur c, XmlOptions options, ContentHandler ch, LexicalHandler lh )
throws SAXException
{
super( c, options );
_contentHandler = ch;
_lexicalHandler = lh;
_attributes = new AttributesImpl();
_contentHandler.startDocument();
try
{
while ( process() )
;
}
catch ( SaverSAXException e )
{
throw e._saxException;
}
_contentHandler.endDocument();
}
private class SaverSAXException extends RuntimeException
{
SaverSAXException ( SAXException e )
{
_saxException = e;
}
SAXException _saxException;
}
private String getPrefixedName ( QName name )
{
String uri = name.getNamespaceURI();
String local = name.getLocalPart();
if (uri.length() == 0)
return local;
String prefix = getUriMapping( uri );
if (prefix.length() == 0)
return local;
return prefix + ":" + local;
}
private void emitNamespacesHelper ( )
{
for ( iterateMappings() ; hasMapping() ; nextMapping() )
{
String prefix = mappingPrefix();
String uri = mappingUri();
try
{
_contentHandler.startPrefixMapping( prefix, uri );
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
if (prefix == null || prefix.length() == 0)
_attributes.addAttribute( "http://www.w3.org/2000/xmlns/", "", "xmlns", "CDATA", uri );
else
_attributes.addAttribute( "http://www.w3.org/2000/xmlns/", "", "xmlns:" + prefix, "CDATA", uri );
}
}
protected boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues )
{
_attributes.clear();
if (saveNamespacesFirst())
emitNamespacesHelper();
for ( int i = 0 ; i < attrNames.size() ; i++ )
{
QName name = (QName) attrNames.get( i );
_attributes.addAttribute(
name.getNamespaceURI(), name.getLocalPart(), getPrefixedName( name ),
"CDATA", (String) attrValues.get( i ) );
}
if (!saveNamespacesFirst())
emitNamespacesHelper();
QName elemName = c.getName();
try
{
_contentHandler.startElement(
elemName.getNamespaceURI(), elemName.getLocalPart(),
getPrefixedName( elemName ), _attributes );
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
return false;
}
protected void emitFinish ( SaveCur c )
{
QName name = c.getName();
try
{
_contentHandler.endElement(
name.getNamespaceURI(), name.getLocalPart(), getPrefixedName( name ) );
for ( iterateMappings() ; hasMapping() ; nextMapping() )
_contentHandler.endPrefixMapping( mappingPrefix() );
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
}
protected void emitText ( SaveCur c )
{
assert c.isText();
Object src = c.getChars();
try
{
if (src instanceof char[])
{
// Pray the user does not modify the buffer ....
_contentHandler.characters( (char[]) src, c._offSrc, c._cchSrc );
}
else
{
if (_buf == null)
_buf = new char [ 1024 ];
while ( c._cchSrc > 0 )
{
int cch = java.lang.Math.min( _buf.length, c._cchSrc );
CharUtil.getChars( _buf, 0, src, c._offSrc, cch );
_contentHandler.characters( _buf, 0, cch );
c._offSrc += cch;
c._cchSrc -= cch;
}
}
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
}
protected void emitComment ( SaveCur c )
{
if (_lexicalHandler != null)
{
c.push();
c.next();
try
{
if (!c.isText())
_lexicalHandler.comment( null, 0, 0 );
else
{
Object src = c.getChars();
if (src instanceof char[])
{
// Pray the user does not modify the buffer ....
_lexicalHandler.comment( (char[]) src, c._offSrc, c._cchSrc );
}
else
{
if (_buf == null || _buf.length < c._cchSrc)
_buf = new char [ java.lang.Math.min( 1024, c._cchSrc ) ];
CharUtil.getChars( _buf, 0, src, c._offSrc, c._cchSrc );
_lexicalHandler.comment( _buf, 0, c._cchSrc );
}
}
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
c.pop();
}
}
protected void emitProcinst ( SaveCur c )
{
String target = c.getName().getLocalPart();
c.push();
c.next();
String value = CharUtil.getString( c.getChars(), c._offSrc, c._cchSrc );
c.pop();
try
{
_contentHandler.processingInstruction( c.getName().getLocalPart(), value );
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
}
protected void emitDocType ( String docTypeName, String publicId, String systemId )
{
if (_lexicalHandler != null)
{
try
{
_lexicalHandler.startDTD( docTypeName, publicId, systemId );
_lexicalHandler.endDTD();
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
}
}
private ContentHandler _contentHandler;
private LexicalHandler _lexicalHandler;
private AttributesImpl _attributes;
private char[] _buf;
}
//
//
//
static abstract class SaveCur
{
final boolean isRoot ( ) { return kind() == ROOT; }
final boolean isElem ( ) { return kind() == ELEM; }
final boolean isAttr ( ) { return kind() == ATTR; }
final boolean isText ( ) { return kind() == TEXT; }
final boolean isComment ( ) { return kind() == COMMENT; }
final boolean isProcinst ( ) { return kind() == PROCINST; }
final boolean isFinish ( ) { return Cur.kindIsFinish( kind() ); }
final boolean isContainer ( ) { return Cur.kindIsContainer( kind() ); }
final boolean isNormalAttr ( ) { return kind() == ATTR && !isXmlns(); }
final boolean skip ( ) { toEnd(); return next(); }
abstract void release ( );
abstract int kind ( );
abstract QName getName ( );
abstract String getXmlnsPrefix ( );
abstract String getXmlnsUri ( );
abstract boolean isXmlns ( );
abstract boolean hasChildren ( );
abstract boolean hasText ( );
abstract boolean toFirstAttr ( );
abstract boolean toNextAttr ( );
abstract String getAttrValue ( );
abstract boolean next ( );
abstract void toEnd ( );
abstract void push ( );
abstract void pop ( );
abstract Object getChars ( );
abstract List getAncestorNamespaces ( );
abstract XmlDocumentProperties getDocProps ( );
int _offSrc;
int _cchSrc;
}
// TODO - saving a fragment need to take namesapces from root and
// reflect them on the document element
private static final class DocSaveCur extends SaveCur
{
DocSaveCur ( Cur c )
{
assert c.isRoot();
_cur = c.weakCur( this );
}
void release ( )
{
_cur.release();
_cur = null;
}
int kind ( ) { return _cur.kind(); }
QName getName ( ) { return _cur.getName(); }
String getXmlnsPrefix ( ) { return _cur.getXmlnsPrefix(); }
String getXmlnsUri ( ) { return _cur.getXmlnsUri(); }
boolean isXmlns ( ) { return _cur.isXmlns(); }
boolean hasChildren ( ) { return _cur.hasChildren(); }
boolean hasText ( ) { return _cur.hasText(); }
boolean toFirstAttr ( ) { return _cur.toFirstAttr(); }
boolean toNextAttr ( ) { return _cur.toNextAttr(); }
String getAttrValue ( ) { assert _cur.isAttr(); return _cur.getValueAsString(); }
void toEnd ( ) { _cur.toEnd(); }
boolean next ( ) { return _cur.next(); }
void push ( ) { _cur.push(); }
void pop ( ) { _cur.pop(); }
List getAncestorNamespaces ( ) { return null; }
Object getChars ( )
{
Object o = _cur.getChars( -1 );
_offSrc = _cur._offSrc;
_cchSrc = _cur._cchSrc;
return o;
}
XmlDocumentProperties getDocProps ( ) { return Locale.getDocProps(_cur, false); }
private Cur _cur;
}
private static abstract class FilterSaveCur extends SaveCur
{
FilterSaveCur ( SaveCur c )
{
assert c.isRoot();
_cur = c;
}
// Can filter anything by root and attributes and text
protected abstract boolean filter ( );
void release ( )
{
_cur.release();
_cur = null;
}
int kind ( ) { return _cur.kind(); }
QName getName ( ) { return _cur.getName(); }
String getXmlnsPrefix ( ) { return _cur.getXmlnsPrefix(); }
String getXmlnsUri ( ) { return _cur.getXmlnsUri(); }
boolean isXmlns ( ) { return _cur.isXmlns(); }
boolean hasChildren ( ) { return _cur.hasChildren(); }
boolean hasText ( ) { return _cur.hasText(); }
boolean toFirstAttr ( ) { return _cur.toFirstAttr(); }
boolean toNextAttr ( ) { return _cur.toNextAttr(); }
String getAttrValue ( ) { return _cur.getAttrValue(); }
void toEnd ( ) { _cur.toEnd(); }
boolean next ( )
{
if (!_cur.next())
return false;
if (!filter())
return true;
assert !isRoot() && !isText() && !isAttr();
toEnd();
return next();
}
void push ( ) { _cur.push(); }
void pop ( ) { _cur.pop(); }
List getAncestorNamespaces ( ) { return _cur.getAncestorNamespaces(); }
Object getChars ( )
{
Object o = _cur.getChars();
_offSrc = _cur._offSrc;
_cchSrc = _cur._cchSrc;
return o;
}
XmlDocumentProperties getDocProps ( ) { return _cur.getDocProps(); }
private SaveCur _cur;
}
private static final class FilterPiSaveCur extends FilterSaveCur
{
FilterPiSaveCur ( SaveCur c, String target )
{
super( c );
_piTarget = target;
}
protected boolean filter ( )
{
return kind() == PROCINST && getName().getLocalPart().equals( _piTarget );
}
private String _piTarget;
}
private static final class FragSaveCur extends SaveCur
{
FragSaveCur ( Cur start, Cur end, QName synthElem )
{
_saveAttr = start.isAttr() && start.isSamePos( end );
_cur = start.weakCur( this );
_end = end.weakCur( this );
_elem = synthElem;
_state = ROOT_START;
_stateStack = new int [ 8 ];
start.push();
computeAncestorNamespaces( start );
start.pop();
}
List getAncestorNamespaces ( )
{
return _ancestorNamespaces;
}
private void computeAncestorNamespaces ( Cur c )
{
_ancestorNamespaces = new ArrayList();
while ( c.toParentRaw() )
{
if (c.toFirstAttr())
{
do
{
if (c.isXmlns())
{
String prefix = c.getXmlnsPrefix();
String uri = c.getXmlnsUri();
// Don't let xmlns:foo="" get used
if (uri.length() > 0 || prefix.length() == 0)
{
_ancestorNamespaces.add( c.getXmlnsPrefix() );
_ancestorNamespaces.add( c.getXmlnsUri() );
}
}
}
while ( c.toNextAttr() );
c.toParent();
}
}
}
//
//
//
void release ( )
{
_cur.release();
_cur = null;
_end.release();
_end = null;
}
int kind ( )
{
switch ( _state )
{
case ROOT_START : return ROOT;
case ELEM_START : return ELEM;
case ELEM_END : return -ELEM;
case ROOT_END : return -ROOT;
}
assert _state == CUR;
return _cur.kind();
}
QName getName ( )
{
switch ( _state )
{
case ROOT_START :
case ROOT_END : return null;
case ELEM_START :
case ELEM_END : return _elem;
}
assert _state == CUR;
return _cur.getName();
}
String getXmlnsPrefix ( )
{
assert _state == CUR && _cur.isAttr();
return _cur.getXmlnsPrefix();
}
String getXmlnsUri ( )
{
assert _state == CUR && _cur.isAttr();
return _cur.getXmlnsUri();
}
boolean isXmlns ( )
{
assert _state == CUR && _cur.isAttr();
return _cur.isXmlns();
}
boolean hasChildren ( )
{
boolean hasChildren = false;
if (isContainer())
{ // is there a faster way to do this?
push();
next();
if (!isText() && !isFinish())
hasChildren = true;
pop();
}
return hasChildren;
}
boolean hasText ( )
{
boolean hasText = false;
if (isContainer())
{
push();
next();
if (isText())
hasText = true;
pop();
}
return hasText;
}
Object getChars ( )
{
assert _state == CUR && _cur.isText();
Object src = _cur.getChars( -1 );
_offSrc = _cur._offSrc;
_cchSrc = _cur._cchSrc;
return src;
}
boolean next ( )
{
switch ( _state )
{
case ROOT_START :
{
_state = _elem == null ? CUR : ELEM_START;
break;
}
case ELEM_START :
{
if (_saveAttr)
_state = ELEM_END;
else
{
if (_cur.isAttr())
{
_cur.toParent();
_cur.next();
}
if (_cur.isSamePos( _end ))
_state = ELEM_END;
else
_state = CUR;
}
break;
}
case CUR :
{
assert !_cur.isAttr();
_cur.next();
if (_cur.isSamePos( _end ))
_state = _elem == null ? ROOT_END : ELEM_END;
break;
}
case ELEM_END :
{
_state = ROOT_END;
break;
}
case ROOT_END :
return false;
}
return true;
}
void toEnd ( )
{
switch ( _state )
{
case ROOT_START : _state = ROOT_END; return;
case ELEM_START : _state = ELEM_END; return;
case ROOT_END :
case ELEM_END : return;
}
assert _state == CUR && !_cur.isAttr() && !_cur.isText();
_cur.toEnd();
}
boolean toFirstAttr ( )
{
switch ( _state )
{
case ROOT_END :
case ELEM_END :
case ROOT_START : return false;
case CUR : return _cur.toFirstAttr();
}
assert _state == ELEM_START;
if (!_cur.isAttr())
return false;
_state = CUR;
return true;
}
boolean toNextAttr ( )
{
assert _state == CUR;
return !_saveAttr && _cur.toNextAttr();
}
String getAttrValue ( )
{
assert _state == CUR && _cur.isAttr();
return _cur.getValueAsString();
}
void push ( )
{
if (_stateStackSize == _stateStack.length)
{
int[] newStateStack = new int [ _stateStackSize * 2 ];
System.arraycopy( _stateStack, 0, newStateStack, 0, _stateStackSize );
_stateStack = newStateStack;
}
_stateStack [ _stateStackSize++ ] = _state;
_cur.push();
}
void pop ()
{
_cur.pop();
_state = _stateStack [ --_stateStackSize ];
}
XmlDocumentProperties getDocProps ( ) { return Locale.getDocProps(_cur, false); }
//
//
//
private Cur _cur;
private Cur _end;
private ArrayList _ancestorNamespaces;
private QName _elem;
private boolean _saveAttr;
private static final int ROOT_START = 1;
private static final int ELEM_START = 2;
private static final int ROOT_END = 3;
private static final int ELEM_END = 4;
private static final int CUR = 5;
private int _state;
private int[] _stateStack;
private int _stateStackSize;
}
private static final class PrettySaveCur extends SaveCur
{
PrettySaveCur ( SaveCur c, XmlOptions options )
{
_sb = new StringBuffer();
_stack = new ArrayList();
_cur = c;
assert options != null;
_prettyIndent = 2;
if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT_INDENT ))
{
_prettyIndent =
((Integer) options.get( XmlOptions.SAVE_PRETTY_PRINT_INDENT )).intValue();
}
if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT_OFFSET ))
{
_prettyOffset =
((Integer) options.get( XmlOptions.SAVE_PRETTY_PRINT_OFFSET )).intValue();
}
}
List getAncestorNamespaces ( ) { return _cur.getAncestorNamespaces(); }
void release ( ) { _cur.release(); }
int kind ( ) { return _txt == null ? _cur.kind() : TEXT; }
QName getName ( ) { assert _txt == null; return _cur.getName(); }
String getXmlnsPrefix ( ) { assert _txt == null; return _cur.getXmlnsPrefix(); }
String getXmlnsUri ( ) { assert _txt == null; return _cur.getXmlnsUri(); }
boolean isXmlns ( ) { return _txt == null ? _cur.isXmlns() : false; }
boolean hasChildren ( ) { return _txt == null ? _cur.hasChildren() : false; }
boolean hasText ( ) { return _txt == null ? _cur.hasText() : false; }
boolean toFirstAttr ( ) { assert _txt == null; return _cur.toFirstAttr(); }
boolean toNextAttr ( ) { assert _txt == null; return _cur.toNextAttr(); }
String getAttrValue ( ) { assert _txt == null; return _cur.getAttrValue(); }
void toEnd ( )
{
assert _txt == null;
_cur.toEnd();
if (_cur.kind() == -ELEM)
_depth--;
}
boolean next ( )
{
int k;
if (_txt != null)
{
assert _txt.length() > 0;
assert !_cur.isText();
_txt = null;
k = _cur.kind();
}
else
{
int prevKind = k = _cur.kind();
if (!_cur.next())
return false;
_sb.delete( 0, _sb.length() );
assert _txt == null;
// place any text encountered in the buffer
if (_cur.isText())
{
CharUtil.getString( _sb, _cur.getChars(), _cur._offSrc, _cur._cchSrc );
_cur.next();
trim( _sb );
}
k = _cur.kind();
// Check for non leaf, _prettyIndent < 0 means that the save is all on one line
if (_prettyIndent >= 0 &&
prevKind != COMMENT && prevKind != PROCINST && (prevKind != ELEM || k != -ELEM))
// if (prevKind != COMMENT && prevKind != PROCINST && (prevKind != ELEM || k != -ELEM))
{
if (_sb.length() > 0)
{
_sb.insert( 0, _newLine );
spaces( _sb, _newLine.length(), _prettyOffset + _prettyIndent * _depth );
}
if (k != -ROOT)
{
if (prevKind != ROOT)
_sb.append( _newLine );
int d = k < 0 ? _depth - 1 : _depth;
spaces( _sb, _sb.length(), _prettyOffset + _prettyIndent * d );
}
}
if (_sb.length() > 0)
{
_txt = _sb.toString();
k = TEXT;
}
}
if (k == ELEM)
_depth++;
else if (k == -ELEM)
_depth--;
return true;
}
void push ( )
{
_cur.push();
_stack.add( _txt );
_stack.add( new Integer( _depth ) );
}
void pop ( )
{
_cur.pop();
_depth = ((Integer) _stack.remove( _stack.size() - 1 )).intValue();
_txt = (String) _stack.remove( _stack.size() - 1 );
}
Object getChars ( )
{
if (_txt != null)
{
_offSrc = 0;
_cchSrc = _txt.length();
return _txt;
}
Object o = _cur.getChars();
_offSrc = _cur._offSrc;
_cchSrc = _cur._cchSrc;
return o;
}
XmlDocumentProperties getDocProps ( ) { return _cur.getDocProps(); }
final static void spaces ( StringBuffer sb, int offset, int count )
{
while ( count-- > 0 )
sb.insert( offset, ' ' );
}
final static void trim ( StringBuffer sb )
{
int i;
for ( i = 0 ; i < sb.length() ; i++ )
if (!CharUtil.isWhiteSpace( sb.charAt( i ) ))
break;
sb.delete( 0, i );
for ( i = sb.length() ; i > 0 ; i-- )
if (!CharUtil.isWhiteSpace( sb.charAt( i - 1 ) ))
break;
sb.delete( i, sb.length() );
}
private SaveCur _cur;
private int _prettyIndent;
private int _prettyOffset;
private String _txt;
private StringBuffer _sb;
private int _depth;
private ArrayList _stack;
}
//
//
//
private final Locale _locale;
private final long _version;
private SaveCur _cur;
private List _ancestorNamespaces;
private Map _suggestedPrefixes;
protected XmlOptionCharEscapeMap _replaceChar;
private boolean _useDefaultNamespace;
private Map _preComputedNamespaces;
private boolean _saveNamespacesFirst;
private ArrayList _attrNames;
private ArrayList _attrValues;
private ArrayList _namespaceStack;
private int _currentMapping;
private HashMap _uriMap;
private HashMap _prefixMap;
private String _initialDefaultUri;
static final String _newLine =
SystemProperties.getProperty( "line.separator" ) == null
? "\n"
: SystemProperties.getProperty( "line.separator" );
}
|
src/store/org/apache/xmlbeans/impl/store/Saver.java
|
/* Copyright 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.xmlbeans.impl.store;
import javax.xml.namespace.QName;
import org.apache.xmlbeans.SystemProperties;
import org.apache.xmlbeans.XmlDocumentProperties;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlOptionCharEscapeMap;
import org.apache.xmlbeans.impl.common.QNameHelper;
import org.apache.xmlbeans.impl.common.EncodingMap;
import java.io.Writer;
import java.io.Reader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import org.xml.sax.ContentHandler;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.ConcurrentModificationException;
abstract class Saver
{
static final int ROOT = Cur.ROOT;
static final int ELEM = Cur.ELEM;
static final int ATTR = Cur.ATTR;
static final int COMMENT = Cur.COMMENT;
static final int PROCINST = Cur.PROCINST;
static final int TEXT = Cur.TEXT;
protected abstract boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues );
protected abstract void emitFinish ( SaveCur c );
protected abstract void emitText ( SaveCur c );
protected abstract void emitComment ( SaveCur c );
protected abstract void emitProcinst ( SaveCur c );
protected abstract void emitDocType ( String docTypeName, String publicId, String systemId );
protected void syntheticNamespace ( String prefix, String uri, boolean considerDefault ) { }
Saver ( Cur c, XmlOptions options )
{
assert c._locale.entered();
options = XmlOptions.maskNull( options );
_cur = createSaveCur( c, options );
_locale = c._locale;
_version = _locale.version();
_namespaceStack = new ArrayList();
_uriMap = new HashMap();
_prefixMap = new HashMap();
_attrNames = new ArrayList();
_attrValues = new ArrayList ();
// Define implicit xml prefixed namespace
addMapping( "xml", Locale._xml1998Uri );
if (options.hasOption( XmlOptions.SAVE_IMPLICIT_NAMESPACES ))
{
Map m = (Map) options.get( XmlOptions.SAVE_IMPLICIT_NAMESPACES );
for ( Iterator i = m.keySet().iterator() ; i.hasNext() ; )
{
String prefix = (String) i.next();
addMapping( prefix, (String) m.get( prefix ) );
}
}
// define character map for escaped replacements
if (options.hasOption( XmlOptions.SAVE_SUBSTITUTE_CHARACTERS ))
{
_replaceChar = (XmlOptionCharEscapeMap)
options.get( XmlOptions.SAVE_SUBSTITUTE_CHARACTERS);
}
// If the default prefix has not been mapped, do so now
if (getNamespaceForPrefix( "" ) == null)
{
_initialDefaultUri = new String( "" );
addMapping( "", _initialDefaultUri );
}
if (options.hasOption( XmlOptions.SAVE_AGGRESSIVE_NAMESPACES ) &&
!(this instanceof SynthNamespaceSaver))
{
SynthNamespaceSaver saver = new SynthNamespaceSaver( c, options );
while ( saver.process() )
;
if (!saver._synthNamespaces.isEmpty())
_preComputedNamespaces = saver._synthNamespaces;
}
_useDefaultNamespace =
options.hasOption( XmlOptions.SAVE_USE_DEFAULT_NAMESPACE );
_saveNamespacesFirst = options.hasOption( XmlOptions.SAVE_NAMESPACES_FIRST );
if (options.hasOption( XmlOptions.SAVE_SUGGESTED_PREFIXES ))
_suggestedPrefixes = (Map) options.get( XmlOptions.SAVE_SUGGESTED_PREFIXES);
_ancestorNamespaces = _cur.getAncestorNamespaces();
}
private static SaveCur createSaveCur ( Cur c, XmlOptions options )
{
QName synthName = (QName) options.get( XmlOptions.SAVE_SYNTHETIC_DOCUMENT_ELEMENT );
QName fragName = synthName;
if (fragName == null)
{
fragName =
options.hasOption( XmlOptions.SAVE_USE_OPEN_FRAGMENT )
? Locale._openuriFragment
: Locale._xmlFragment;
}
boolean saveInner =
options.hasOption( XmlOptions.SAVE_INNER ) &&
!options.hasOption( XmlOptions.SAVE_OUTER );
Cur start = c.tempCur();
Cur end = c.tempCur();
SaveCur cur = null;
int k = c.kind();
switch ( k )
{
case ROOT :
{
positionToInner( c, start, end );
if (Locale.isFragment( start, end ))
cur = new FragSaveCur( start, end, fragName );
else if (synthName != null)
cur = new FragSaveCur( start, end, synthName );
else
cur = new DocSaveCur( c );
break;
}
case ELEM :
{
if (saveInner)
{
positionToInner( c, start, end );
cur =
new FragSaveCur(
start, end, Locale.isFragment( start, end ) ? fragName : synthName );
}
else if (synthName != null)
{
positionToInner( c, start, end );
cur = new FragSaveCur( start, end, synthName );
}
else
{
start.moveToCur( c );
end.moveToCur( c );
end.skip();
cur = new FragSaveCur( start, end, null );
}
break;
}
}
if (cur == null)
{
assert k < 0 || k == ATTR || k == COMMENT || k == PROCINST || k == TEXT;
if (k < 0)
{
// Save out ""
start.moveToCur( c );
end.moveToCur( c );
}
else if (k == TEXT)
{
start.moveToCur( c );
end.moveToCur( c );
end.next();
}
else if (saveInner)
{
start.moveToCur( c );
start.next();
end.moveToCur( c );
end.toEnd();
}
else if (k == ATTR)
{
start.moveToCur( c );
end.moveToCur( c );
}
else
{
assert k == COMMENT || k == PROCINST;
start.moveToCur( c );
end.moveToCur( c );
end.skip();
}
cur = new FragSaveCur( start, end, fragName );
}
String filterPI = (String) options.get( XmlOptions.SAVE_FILTER_PROCINST );
if (filterPI != null)
cur = new FilterPiSaveCur( cur, filterPI );
if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT ))
cur = new PrettySaveCur( cur, options );
start.release();
end.release();
return cur;
}
private static void positionToInner ( Cur c, Cur start, Cur end )
{
assert c.isContainer();
start.moveToCur( c );
if (!start.toFirstAttr())
start.next();
end.moveToCur( c );
end.toEnd();
}
protected boolean saveNamespacesFirst ( )
{
return _saveNamespacesFirst;
}
protected final boolean process ( )
{
assert _locale.entered();
if (_cur == null)
return false;
if (_version != _locale.version())
throw new ConcurrentModificationException( "Document changed during save" );
switch ( _cur.kind() )
{
case ROOT : { processRoot(); break; }
case ELEM : { processElement(); break; }
case - ELEM : { processFinish (); break; }
case TEXT : { emitText ( _cur ); break; }
case COMMENT : { emitComment ( _cur ); _cur.toEnd(); break; }
case PROCINST : { emitProcinst ( _cur ); _cur.toEnd(); break; }
case - ROOT :
{
_cur.release();
_cur = null;
return false;
}
default : throw new RuntimeException( "Unexpected kind" );
}
_cur.next();
return true;
}
private final void processFinish ( )
{
emitFinish( _cur );
popMappings();
}
private final void processRoot ( )
{
assert _cur.isRoot();
XmlDocumentProperties props = _cur.getDocProps();
String systemId = null;
String docTypeName = null;
if (props != null)
{
systemId = props.getDoctypeSystemId();
docTypeName = props.getDoctypeName();
}
if (systemId != null || docTypeName != null)
{
if (docTypeName == null)
{
_cur.push();
while (!_cur.isElem() && _cur.next())
;
if (_cur.isElem())
docTypeName = _cur.getName().getLocalPart();
_cur.pop();
}
String publicId = props.getDoctypePublicId();
if (docTypeName != null)
emitDocType( docTypeName, publicId, systemId );
}
}
private final void processElement ( )
{
assert _cur.isElem() && _cur.getName() != null;
QName name = _cur.getName();
// Add a new entry to the frontier. If this element has a name
// which has no namespace, then we must make sure that pushing
// the mappings causes the default namespace to be empty
boolean ensureDefaultEmpty = name.getNamespaceURI().length() == 0;
pushMappings( _cur, ensureDefaultEmpty );
//
// There are four things which use mappings:
//
// 1) The element name
// 2) The element value (qname based)
// 3) Attribute names
// 4) The attribute values (qname based)
//
// 1) The element name (not for starts)
ensureMapping( name.getNamespaceURI(), name.getPrefix(), !ensureDefaultEmpty, false );
//
//
//
_attrNames.clear();
_attrValues.clear();
_cur.push();
attrs:
for ( boolean A = _cur.toFirstAttr() ; A ; A = _cur.toNextAttr() )
{
if (_cur.isNormalAttr())
{
QName attrName = _cur.getName();
_attrNames.add( attrName );
for ( int i = _attrNames.size() - 2 ; i >= 0 ; i-- )
{
if (_attrNames.get( i ).equals( attrName ))
{
_attrNames.remove( _attrNames.size() - 1 );
continue attrs;
}
}
_attrValues.add( _cur.getAttrValue() );
ensureMapping( attrName.getNamespaceURI(), attrName.getPrefix(), false, true );
}
}
_cur.pop();
// If I am doing aggressive namespaces and we're emitting a
// container which can contain content, add the namespaces
// we've computed. Basically, I'm making sure the pre-computed
// namespaces are mapped on the first container which has a name.
if (_preComputedNamespaces != null)
{
for ( Iterator i = _preComputedNamespaces.keySet().iterator() ; i.hasNext() ; )
{
String uri = (String) i.next();
String prefix = (String) _preComputedNamespaces.get( uri );
boolean considerDefault = prefix.length() == 0 && !ensureDefaultEmpty;
ensureMapping( uri, prefix, considerDefault, false );
}
// Set to null so we do this once at the top
_preComputedNamespaces = null;
}
if (emitElement( _cur, _attrNames, _attrValues ))
{
popMappings();
_cur.toEnd();
}
}
//
// Layout of namespace stack:
//
// URI Undo
// URI Rename
// Prefix Undo
// Mapping
//
boolean hasMappings ( )
{
int i = _namespaceStack.size();
return i > 0 && _namespaceStack.get( i - 1 ) != null;
}
void iterateMappings ( )
{
_currentMapping = _namespaceStack.size();
while ( _currentMapping > 0 && _namespaceStack.get( _currentMapping - 1 ) != null )
_currentMapping -= 8;
}
boolean hasMapping ( )
{
return _currentMapping < _namespaceStack.size();
}
void nextMapping ( )
{
_currentMapping += 8;
}
String mappingPrefix ( )
{
assert hasMapping();
return (String) _namespaceStack.get( _currentMapping + 6 );
}
String mappingUri ( )
{
assert hasMapping();
return (String) _namespaceStack.get( _currentMapping + 7 );
}
private final void pushMappings ( SaveCur c, boolean ensureDefaultEmpty )
{
assert c.isContainer();
_namespaceStack.add( null );
c.push();
namespaces:
for ( boolean A = c.toFirstAttr() ; A ; A = c.toNextAttr() )
if (c.isXmlns())
addNewFrameMapping( c.getXmlnsPrefix(), c.getXmlnsUri(), ensureDefaultEmpty );
c.pop();
if (_ancestorNamespaces != null)
{
for ( int i = 0 ; i < _ancestorNamespaces.size() ; i += 2 )
{
String prefix = (String) _ancestorNamespaces.get( i );
String uri = (String) _ancestorNamespaces.get( i + 1 );
addNewFrameMapping( prefix, uri, ensureDefaultEmpty );
}
_ancestorNamespaces = null;
}
if (ensureDefaultEmpty)
{
String defaultUri = (String) _prefixMap.get( "" );
// I map the default to "" at the very beginning
assert defaultUri != null;
if (defaultUri.length() > 0)
addMapping( "", "" );
}
}
private final void addNewFrameMapping ( String prefix, String uri, boolean ensureDefaultEmpty )
{
// If the prefix maps to "", this don't include this mapping 'cause it's not well formed.
// Also, if we want to make sure that the default namespace is always "", then check that
// here as well.
if ((prefix.length() == 0 || uri.length() > 0) &&
(!ensureDefaultEmpty || prefix.length() > 0 || uri.length() == 0))
{
// Make sure the prefix is not already mapped in this frame
for ( iterateMappings() ; hasMapping() ; nextMapping() )
if (mappingPrefix().equals( prefix ))
return;
// Also make sure that the prefix declaration is not redundant
// This has the side-effect of making it impossible to set a
// redundant prefix declaration, but seems that it's better
// to just never issue a duplicate prefix declaration.
if (uri.equals(getNamespaceForPrefix(prefix)))
return;
addMapping( prefix, uri );
}
}
private final void addMapping ( String prefix, String uri )
{
assert uri != null;
assert prefix != null;
// If the prefix being mapped here is already mapped to a uri,
// that uri will either go out of scope or be mapped to another
// prefix.
String renameUri = (String) _prefixMap.get( prefix );
String renamePrefix = null;
if (renameUri != null)
{
// See if this prefix is already mapped to this uri. If
// so, then add to the stack, but there is nothing to rename
if (renameUri.equals( uri ))
renameUri = null;
else
{
int i = _namespaceStack.size();
while ( i > 0 )
{
if (_namespaceStack.get( i - 1 ) == null)
{
i--;
continue;
}
if (_namespaceStack.get( i - 7 ).equals( renameUri ))
{
renamePrefix = (String) _namespaceStack.get( i - 8 );
if (renamePrefix == null || !renamePrefix.equals( prefix ))
break;
}
i -= 8;
}
assert i > 0;
}
}
_namespaceStack.add( _uriMap.get( uri ) );
_namespaceStack.add( uri );
if (renameUri != null)
{
_namespaceStack.add( _uriMap.get( renameUri ) );
_namespaceStack.add( renameUri );
}
else
{
_namespaceStack.add( null );
_namespaceStack.add( null );
}
_namespaceStack.add( prefix );
_namespaceStack.add( _prefixMap.get( prefix ) );
_namespaceStack.add( prefix );
_namespaceStack.add( uri );
_uriMap.put( uri, prefix );
_prefixMap.put( prefix, uri );
if (renameUri != null)
_uriMap.put( renameUri, renamePrefix );
}
private final void popMappings ( )
{
for ( ; ; )
{
int i = _namespaceStack.size();
if (i == 0)
break;
if (_namespaceStack.get( i - 1 ) == null)
{
_namespaceStack.remove( i - 1 );
break;
}
Object oldUri = _namespaceStack.get( i - 7 );
Object oldPrefix = _namespaceStack.get( i - 8 );
if (oldPrefix == null)
_uriMap.remove( oldUri );
else
_uriMap.put( oldUri, oldPrefix );
oldPrefix = _namespaceStack.get( i - 4 );
oldUri = _namespaceStack.get( i - 3 );
if (oldUri == null)
_prefixMap.remove( oldPrefix );
else
_prefixMap.put( oldPrefix, oldUri );
String uri = (String) _namespaceStack.get( i - 5 );
if (uri != null)
_uriMap.put( uri, _namespaceStack.get( i - 6 ) );
// Hahahahahaha -- :-(
_namespaceStack.remove( i - 1 );
_namespaceStack.remove( i - 2 );
_namespaceStack.remove( i - 3 );
_namespaceStack.remove( i - 4 );
_namespaceStack.remove( i - 5 );
_namespaceStack.remove( i - 6 );
_namespaceStack.remove( i - 7 );
_namespaceStack.remove( i - 8 );
}
}
private final void dumpMappings ( )
{
for ( int i = _namespaceStack.size() ; i > 0 ; )
{
if (_namespaceStack.get( i - 1 ) == null)
{
System.out.println( "----------------" );
i--;
continue;
}
System.out.print( "Mapping: " );
System.out.print( _namespaceStack.get( i - 2 ) );
System.out.print( " -> " );
System.out.print( _namespaceStack.get( i - 1 ) );
System.out.println();
System.out.print( "Prefix Undo: " );
System.out.print( _namespaceStack.get( i - 4 ) );
System.out.print( " -> " );
System.out.print( _namespaceStack.get( i - 3 ) );
System.out.println();
System.out.print( "Uri Rename: " );
System.out.print( _namespaceStack.get( i - 5 ) );
System.out.print( " -> " );
System.out.print( _namespaceStack.get( i - 6 ) );
System.out.println();
System.out.print( "UriUndo: " );
System.out.print( _namespaceStack.get( i - 7 ) );
System.out.print( " -> " );
System.out.print( _namespaceStack.get( i - 8 ) );
System.out.println();
System.out.println();
i -= 8;
}
}
private final String ensureMapping (
String uri, String candidatePrefix,
boolean considerCreatingDefault, boolean mustHavePrefix )
{
assert uri != null;
// Can be called for no-namespaced things
if (uri.length() == 0)
return null;
String prefix = (String) _uriMap.get( uri );
if (prefix != null && (prefix.length() > 0 || !mustHavePrefix))
return prefix;
//
// I try prefixes from a number of places, in order:
//
// 1) What was passed in
// 2) The optional suggestions (for uri's)
// 3) The default mapping is allowed
// 4) ns#++
//
if (candidatePrefix != null && candidatePrefix.length() == 0)
candidatePrefix = null;
if (candidatePrefix == null || !tryPrefix( candidatePrefix ))
{
if (_suggestedPrefixes != null &&
_suggestedPrefixes.containsKey( uri ) &&
tryPrefix( (String) _suggestedPrefixes.get( uri ) ))
{
candidatePrefix = (String) _suggestedPrefixes.get( uri );
}
else if (considerCreatingDefault && _useDefaultNamespace && tryPrefix( "" ))
candidatePrefix = "";
else
{
String basePrefix = QNameHelper.suggestPrefix( uri );
candidatePrefix = basePrefix;
for ( int i = 1 ; ; i++ )
{
if (tryPrefix( candidatePrefix ))
break;
candidatePrefix = basePrefix + i;
}
}
}
assert candidatePrefix != null;
syntheticNamespace( candidatePrefix, uri, considerCreatingDefault );
addMapping( candidatePrefix, uri );
return candidatePrefix;
}
protected final String getUriMapping ( String uri )
{
assert _uriMap.get( uri ) != null;
return (String) _uriMap.get( uri );
}
String getNonDefaultUriMapping ( String uri )
{
String prefix = (String) _uriMap.get( uri );
if (prefix != null && prefix.length() > 0)
return prefix;
for ( Iterator keys = _prefixMap.keySet().iterator() ; keys.hasNext() ; )
{
prefix = (String) keys.next();
if (prefix.length() > 0 && _prefixMap.get( prefix ).equals( uri ))
return prefix;
}
assert false : "Could not find non-default mapping";
return null;
}
private final boolean tryPrefix ( String prefix )
{
if (prefix == null || Locale.beginsWithXml( prefix ))
return false;
String existingUri = (String) _prefixMap.get( prefix );
// If the prefix is currently mapped, then try another prefix. A
// special case is that of trying to map the default prefix ("").
// Here, there always exists a default mapping. If this is the
// mapping we found, then remap it anyways. I use != to compare
// strings because I want to test for the specific initial default
// uri I added when I initialized the saver.
if (existingUri != null && (prefix.length() > 0 || existingUri != _initialDefaultUri))
return false;
return true;
}
public final String getNamespaceForPrefix ( String prefix )
{
assert !prefix.equals( "xml" ) || _prefixMap.get( prefix ).equals( Locale._xml1998Uri );
return (String) _prefixMap.get( prefix );
}
//
//
//
static final class SynthNamespaceSaver extends Saver
{
LinkedHashMap _synthNamespaces = new LinkedHashMap();
SynthNamespaceSaver ( Cur c, XmlOptions options )
{
super( c, options );
}
protected void syntheticNamespace (
String prefix, String uri, boolean considerCreatingDefault )
{
_synthNamespaces.put( uri, considerCreatingDefault ? "" : prefix );
}
protected boolean emitElement (
SaveCur c, ArrayList attrNames, ArrayList attrValues ) { return false; }
protected void emitFinish ( SaveCur c ) { }
protected void emitText ( SaveCur c ) { }
protected void emitComment ( SaveCur c ) { }
protected void emitProcinst ( SaveCur c ) { }
protected void emitDocType ( String docTypeName, String publicId, String systemId ) { }
}
//
//
//
static final class TextSaver extends Saver
{
TextSaver ( Cur c, XmlOptions options, String encoding )
{
super( c, options );
boolean noSaveDecl =
options != null && options.hasOption( XmlOptions.SAVE_NO_XML_DECL );
if (encoding != null && !noSaveDecl)
{
XmlDocumentProperties props = Locale.getDocProps( c, false );
String version = props == null ? null : props.getVersion();
if (version == null)
version = "1.0";
emit( "<?xml version=\"" );
emit( version );
emit( "\" encoding=\"" + encoding + "\"?>" + _newLine );
}
}
protected boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues )
{
assert c.isElem();
emit( '<' );
emitName( c.getName(), false );
if (saveNamespacesFirst())
emitNamespacesHelper();
for ( int i = 0 ; i < attrNames.size() ; i++ )
emitAttrHelper( (QName) attrNames.get( i ), (String) attrValues.get( i ) );
if (!saveNamespacesFirst())
emitNamespacesHelper();
if (!c.hasChildren() && !c.hasText())
{
emit( "/>" );
return true;
}
else
{
emit( '>' );
return false;
}
}
protected void emitFinish ( SaveCur c )
{
emit( "</" );
emitName( c.getName(), false );
emit( '>' );
}
protected void emitXmlns ( String prefix, String uri )
{
assert prefix != null;
assert uri != null;
emit( "xmlns" );
if (prefix.length() > 0)
{
emit( ":" );
emit( prefix );
}
emit( "=\"" );
// TODO - must encode uri properly
emit( uri );
entitizeAttrValue();
emit( '"' );
}
private void emitNamespacesHelper ( )
{
for ( iterateMappings() ; hasMapping() ; nextMapping() )
{
emit( ' ' );
emitXmlns( mappingPrefix(), mappingUri() );
}
}
private void emitAttrHelper ( QName attrName, String attrValue )
{
emit( ' ' );
emitName( attrName, true );
emit( "=\"" );
emit( attrValue );
entitizeAttrValue();
emit( '"' );
}
protected void emitText ( SaveCur c )
{
assert c.isText();
emit( c );
entitizeContent();
}
protected void emitComment ( SaveCur c )
{
assert c.isComment();
emit( "<!--" );
c.push();
c.next();
emit( c );
c.pop();
entitizeComment();
emit( "-->" );
}
protected void emitProcinst ( SaveCur c )
{
assert c.isProcinst();
emit( "<?" );
// TODO - encoding issues here?
emit( c.getName().getLocalPart() );
c.push();
c.next();
if (c.isText())
{
emit( " " );
emit( c );
entitizeProcinst();
}
c.pop();
emit( "?>" );
}
private void emitLiteral ( String literal )
{
// TODO: systemId production http://www.w3.org/TR/REC-xml/#NT-SystemLiteral
// TODO: publicId production http://www.w3.org/TR/REC-xml/#NT-PubidLiteral
if (literal.indexOf( "\"" ) < 0)
{
emit( "\"" );
emit( literal );
emit( "\"" );
}
else
{
emit( "'" );
emit( literal );
emit( "'" );
}
}
protected void emitDocType ( String docTypeName, String publicId, String systemId )
{
assert docTypeName != null;
emit( "<!DOCTYPE " );
emit( docTypeName );
if (publicId == null && systemId != null)
{
emit( " SYSTEM " );
emitLiteral( systemId );
}
else if (publicId != null)
{
emit( " PUBLIC " );
emitLiteral( publicId );
emit( " " );
emitLiteral( systemId );
}
emit( ">" );
emit( _newLine );
}
//
//
//
private void emitName ( QName name, boolean needsPrefix )
{
assert name != null;
String uri = name.getNamespaceURI();
assert uri != null;
if (uri.length() != 0)
{
String prefix = name.getPrefix();
String mappedUri = getNamespaceForPrefix( prefix );
if (mappedUri == null || !mappedUri.equals( uri ))
prefix = getUriMapping( uri );
// Attrs need a prefix. If I have not found one, then there must be a default
// prefix obscuring the prefix needed for this attr. Find it manually.
// NOTE - Consider keeping the currently mapped default URI separate fromn the
// _urpMap and _prefixMap. This way, I would not have to look it up manually
// here
if (needsPrefix && prefix.length() == 0)
prefix = getNonDefaultUriMapping( uri );
if (prefix.length() > 0)
{
emit( prefix );
emit( ":" );
}
}
assert name.getLocalPart().length() > 0;
emit( name.getLocalPart() );
}
private void emit ( char ch )
{
preEmit( 1 );
_buf[ _in ] = ch;
_in = (_in + 1) % _buf.length;
}
private void emit ( String s )
{
int cch = s == null ? 0 : s.length();
if (preEmit( cch ))
return;
int chunk;
if (_in <= _out || cch < (chunk = _buf.length - _in))
{
s.getChars( 0, cch, _buf, _in );
_in += cch;
}
else
{
s.getChars( 0, chunk, _buf, _in );
s.getChars( chunk, cch, _buf, 0 );
_in = (_in + cch) % _buf.length;
}
}
private void emit ( SaveCur c )
{
if (c.isText())
{
Object src = c.getChars();
int cch = c._cchSrc;
if (preEmit( cch ))
return;
int chunk;
if (_in <= _out || cch < (chunk = _buf.length - _in))
{
CharUtil.getChars( _buf, _in, src, c._offSrc, cch );
_in += cch;
}
else
{
CharUtil.getChars( _buf, _in, src, c._offSrc, chunk );
CharUtil.getChars( _buf, 0, src, c._offSrc + chunk, cch - chunk );
_in = (_in + cch) % _buf.length;
}
}
else
preEmit( 0 );
}
private boolean preEmit ( int cch )
{
assert cch >= 0;
_lastEmitCch = cch;
if (cch == 0)
return true;
if (_free < cch)
resize( cch, -1 );
assert cch <= _free;
int used = getAvailable();
// if we are about to emit and there is noting in the buffer, reset
// the buffer to be at the beginning so as to not grow it anymore
// than needed.
if (used == 0)
{
assert _in == _out;
assert _free == _buf.length;
_in = _out = 0;
}
_lastEmitIn = _in;
_free -= cch;
assert _free >= 0;
return false;
}
private void entitizeContent ( )
{
if (_lastEmitCch == 0)
return;
int i = _lastEmitIn;
final int n = _buf.length;
boolean hasCharToBeReplaced = false;
int count = 0;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (ch == '<' || ch == '&')
count++;
else if (isBadChar( ch ) || isEscapedChar( ch ))
hasCharToBeReplaced = true;
if (++i == n)
i = 0;
}
if (count == 0 && !hasCharToBeReplaced)
return;
i = _lastEmitIn;
//
// Heuristic for knowing when to save out stuff as a CDATA.
//
if (_lastEmitCch > 32 && count > 5 &&
count * 100 / _lastEmitCch > 1)
{
boolean lastWasBracket = _buf[ i ] == ']';
i = replace( i, "<![CDATA[" + _buf[ i ] );
boolean secondToLastWasBracket = lastWasBracket;
lastWasBracket = _buf[ i ] == ']';
if (++i == _buf.length)
i = 0;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (ch == '>' && secondToLastWasBracket && lastWasBracket)
i = replace( i, "]]>><![CDATA[" );
else if (isBadChar( ch ))
i = replace( i, "?" );
else
i++;
secondToLastWasBracket = lastWasBracket;
lastWasBracket = ch == ']';
if (i == _buf.length)
i = 0;
}
emit( "]]>" );
}
else
{
char ch = 0, ch_1 = 0, ch_2;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
ch_2 = ch_1;
ch_1 = ch;
ch = _buf[ i ];
if (ch == '<')
i = replace( i, "<" );
else if (ch == '&')
i = replace( i, "&" );
else if (ch == '>' && ch_1 == ']' && ch_2 == ']')
i = replace( i, ">" );
else if (isBadChar( ch ))
i = replace( i, "?" );
else if (isEscapedChar( ch ))
i = replace( i, _replaceChar.getEscapedString( ch ) );
else
i++;
if (i == _buf.length)
i = 0;
}
}
}
private void entitizeAttrValue ( )
{
if (_lastEmitCch == 0)
return;
int i = _lastEmitIn;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (ch == '<')
i = replace( i, "<" );
else if (ch == '&')
i = replace( i, "&" );
else if (ch == '"')
i = replace( i, """ );
else
i++;
if (i == _buf.length)
i = 0;
}
}
private void entitizeComment ( )
{
if (_lastEmitCch == 0)
return;
int i = _lastEmitIn;
boolean lastWasDash = false;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (isBadChar( ch ))
i = replace( i, "?" );
else if (ch == '-')
{
if (lastWasDash)
{
// Replace "--" with "- " to make well formed
i = replace( i, " " );
lastWasDash = false;
}
else
{
lastWasDash = true;
i++;
}
}
else
{
lastWasDash = false;
i++;
}
if (i == _buf.length)
i = 0;
}
// Because I have only replaced chars with single chars,
// _lastEmitIn will still be ok
int offset = (_lastEmitIn + _lastEmitCch - 1) % _buf.length;
if (_buf[ offset ] == '-')
i = replace( offset, " " );
}
private void entitizeProcinst ( )
{
if (_lastEmitCch == 0)
return;
int i = _lastEmitIn;
boolean lastWasQuestion = false;
for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
{
char ch = _buf[ i ];
if (isBadChar( ch ))
i = replace( i, "?" );
if (ch == '>')
{
// TODO - Had to convert to a space here ... imples not well formed XML
if (lastWasQuestion)
i = replace( i, " " );
else
i++;
lastWasQuestion = false;
}
else
{
lastWasQuestion = ch == '?';
i++;
}
if (i == _buf.length)
i = 0;
}
}
/**
* Test if a character is valid in xml character content. See
* http://www.w3.org/TR/REC-xml#NT-Char
*/
private boolean isBadChar ( char ch )
{
return ! (
(ch >= 0x20 && ch <= 0xD7FF ) ||
(ch >= 0xE000 && ch <= 0xFFFD) ||
(ch >= 0x10000 && ch <= 0x10FFFF) ||
(ch == 0x9) || (ch == 0xA) || (ch == 0xD)
);
}
/**
* Test if a character is to be replaced with an escaped value
*/
private boolean isEscapedChar ( char ch )
{
return ( null != _replaceChar && _replaceChar.containsChar( ch ) );
}
private int replace ( int i, String replacement )
{
assert replacement.length() > 0;
int dCch = replacement.length() - 1;
if (dCch == 0)
{
_buf[ i ] = replacement.charAt( 0 );
return i + 1;
}
assert _free >= 0;
if (dCch > _free)
i = resize( dCch, i );
assert _free >= 0;
assert _free >= dCch;
assert getAvailable() > 0;
if (_out > _in && i >= _out)
{
System.arraycopy( _buf, _out, _buf, _out - dCch, i - _out );
_out -= dCch;
i -= dCch;
}
else
{
assert i < _in;
System.arraycopy( _buf, i, _buf, i + dCch, _in - i );
_in += dCch;
}
replacement.getChars( 0, dCch + 1, _buf, i );
_free -= dCch;
assert _free >= 0;
return i + dCch + 1;
}
//
//
//
private int ensure ( int cch )
{
// Even if we're asked to ensure nothing, still try to ensure
// atleast one character so we can determine if we're at the
// end of the stream.
if (cch <= 0)
cch = 1;
int available = getAvailable();
for ( ; available < cch ; available = getAvailable() )
if (!process())
break;
assert available == getAvailable();
// if (available == 0)
// return 0;
return available;
}
int getAvailable ( )
{
return _buf == null ? 0 : _buf.length - _free;
}
private int resize ( int cch, int i )
{
assert _free >= 0;
assert cch > 0;
assert cch > _free;
int newLen = _buf == null ? _initialBufSize : _buf.length * 2;
int used = getAvailable();
while ( newLen - used < cch )
newLen *= 2;
char[] newBuf = new char [ newLen ];
if (used > 0)
{
if (_in > _out)
{
assert i == -1 || (i >= _out && i < _in);
System.arraycopy( _buf, _out, newBuf, 0, used );
i -= _out;
}
else
{
assert i == -1 || (i >= _out || i < _in);
System.arraycopy( _buf, _out, newBuf, 0, used - _in );
System.arraycopy( _buf, 0, newBuf, used - _in, _in );
i = i >= _out ? i - _out : i + _out;
}
_out = 0;
_in = used;
_free += newBuf.length - _buf.length;
}
else
{
_free += newBuf.length;
assert _in == 0 && _out == 0;
assert i == -1;
}
_buf = newBuf;
assert _free >= 0;
return i;
}
public int read ( )
{
if (ensure( 1 ) == 0)
return -1;
assert getAvailable() > 0;
int ch = _buf[ _out ];
_out = (_out + 1) % _buf.length;
_free++;
return ch;
}
public int read ( char[] cbuf, int off, int len )
{
// Check for end of stream even if there is no way to return
// characters because the Reader doc says to return -1 at end of
// stream.
int n;
if ((n = ensure( len )) == 0)
return -1;
if (cbuf == null || len <= 0)
return 0;
if (n < len)
len = n;
if (_out < _in)
{
System.arraycopy( _buf, _out, cbuf, off, len );
}
else
{
int chunk = _buf.length - _out;
if (chunk >= len)
System.arraycopy( _buf, _out, cbuf, off, len );
else
{
System.arraycopy( _buf, _out, cbuf, off, chunk );
System.arraycopy( _buf, 0, cbuf, off + chunk, len - chunk );
}
}
_out = (_out + len) % _buf.length;
_free += len;
assert _free >= 0;
return len;
}
public int write ( Writer writer, int cchMin )
{
while ( getAvailable() < cchMin)
{
if (!process())
break;
}
int charsAvailable = getAvailable();
if (charsAvailable > 0)
{
// I don't want to deal with the circular cases
assert _out == 0;
try
{
writer.write( _buf, 0, charsAvailable );
writer.flush();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
_free += charsAvailable;
assert _free >= 0;
_in = 0;
}
return charsAvailable;
}
public String saveToString ( )
{
// We're gonna build a string. Instead of using StringBuffer, may
// as well use my buffer here. Fill the whole sucker up and
// create a String!
while ( process() )
;
assert _out == 0;
int available = getAvailable();
return available == 0 ? "" : new String( _buf, _out, available );
}
//
//
//
private static final int _initialBufSize = 4096;
private int _lastEmitIn;
private int _lastEmitCch;
private int _free;
private int _in;
private int _out;
private char[] _buf;
}
static final class TextReader extends Reader
{
TextReader ( Cur c, XmlOptions options )
{
_textSaver = new TextSaver( c, options, null );
_locale = c._locale;
_closed = false;
}
public void close ( ) throws IOException { _closed = true; }
public boolean ready ( ) throws IOException { return !_closed; }
public int read ( ) throws IOException
{
checkClosed();
if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read(); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read(); } finally { _locale.exit(); } }
}
public int read ( char[] cbuf ) throws IOException
{
checkClosed();
if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read( cbuf, 0, cbuf == null ? 0 : cbuf.length ); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read( cbuf, 0, cbuf == null ? 0 : cbuf.length ); } finally { _locale.exit(); } }
}
public int read ( char[] cbuf, int off, int len ) throws IOException
{
checkClosed();
if (_locale.noSync()) { _locale.enter(); try { return _textSaver.read( cbuf, off, len ); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _textSaver.read( cbuf, off, len ); } finally { _locale.exit(); } }
}
private void checkClosed ( ) throws IOException
{
if (_closed)
throw new IOException( "Reader has been closed" );
}
private Locale _locale;
private TextSaver _textSaver;
private boolean _closed;
}
static final class InputStreamSaver extends InputStream
{
InputStreamSaver ( Cur c, XmlOptions options )
{
_locale = c._locale;
_closed = false;
assert _locale.entered();
options = XmlOptions.maskNull( options );
_outStreamImpl = new OutputStreamImpl();
String encoding = null;
XmlDocumentProperties props = Locale.getDocProps( c, false );
if (props != null && props.getEncoding() != null)
encoding = EncodingMap.getIANA2JavaMapping( props.getEncoding() );
if (options.hasOption( XmlOptions.CHARACTER_ENCODING ))
encoding = (String) options.get( XmlOptions.CHARACTER_ENCODING );
if (encoding != null)
{
String ianaEncoding = EncodingMap.getJava2IANAMapping( encoding );
if (ianaEncoding != null)
encoding = ianaEncoding;
}
if (encoding == null)
encoding = EncodingMap.getJava2IANAMapping( "UTF8" );
String javaEncoding = EncodingMap.getIANA2JavaMapping( encoding );
if (javaEncoding == null)
throw new IllegalStateException( "Unknown encoding: " + encoding );
try
{
_converter = new OutputStreamWriter( _outStreamImpl, javaEncoding );
}
catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( e );
}
_textSaver = new TextSaver( c, options, encoding );
}
public void close ( ) throws IOException
{
_closed = true;
}
private void checkClosed ( ) throws IOException
{
if (_closed)
throw new IOException( "Stream closed" );
}
// Having the gateway here is kinda slow for the single character case. It may be possible
// to only enter the gate when there are no chars in the buffer.
public int read ( ) throws IOException
{
checkClosed();
if (_locale.noSync()) { _locale.enter(); try { return _outStreamImpl.read(); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _outStreamImpl.read(); } finally { _locale.exit(); } }
}
public int read ( byte[] bbuf, int off, int len ) throws IOException
{
checkClosed();
if (bbuf == null)
throw new NullPointerException( "buf to read into is null" );
if (off < 0 || off > bbuf.length)
throw new IndexOutOfBoundsException( "Offset is not within buf" );
if (_locale.noSync()) { _locale.enter(); try { return _outStreamImpl.read( bbuf, off, len ); } finally { _locale.exit(); } }
else synchronized ( _locale ) { _locale.enter(); try { return _outStreamImpl.read( bbuf, off, len ); } finally { _locale.exit(); } }
}
private int ensure ( int cbyte )
{
// Even if we're asked to ensure nothing, still try to ensure
// atleast one byte so we can determine if we're at the
// end of the stream.
if (cbyte <= 0)
cbyte = 1;
int bytesAvailable = _outStreamImpl.getAvailable();
for ( ; bytesAvailable < cbyte ;
bytesAvailable = _outStreamImpl.getAvailable() )
{
if (_textSaver.write( _converter, 2048 ) < 2048)
break;
}
bytesAvailable = _outStreamImpl.getAvailable();
if (bytesAvailable == 0)
return 0;
return bytesAvailable;
}
private final class OutputStreamImpl extends OutputStream
{
int read ( )
{
if (InputStreamSaver.this.ensure( 1 ) == 0)
return -1;
assert getAvailable() > 0;
int bite = _buf[ _out ];
_out = (_out + 1) % _buf.length;
_free++;
return bite;
}
int read ( byte[] bbuf, int off, int len )
{
// Check for end of stream even if there is no way to return
// characters because the Reader doc says to return -1 at end of
// stream.
int n;
if ((n = ensure( len )) == 0)
return -1;
if (bbuf == null || len <= 0)
return 0;
if (n < len)
len = n;
if (_out < _in)
{
System.arraycopy( _buf, _out, bbuf, off, len );
}
else
{
int chunk = _buf.length - _out;
if (chunk >= len)
System.arraycopy( _buf, _out, bbuf, off, len );
else
{
System.arraycopy( _buf, _out, bbuf, off, chunk );
System.arraycopy(
_buf, 0, bbuf, off + chunk, len - chunk );
}
}
_out = (_out + len) % _buf.length;
_free += len;
return len;
}
int getAvailable ( )
{
return _buf == null ? 0 : _buf.length - _free;
}
public void write ( int bite )
{
if (_free == 0)
resize( 1 );
assert _free > 0;
_buf[ _in ] = (byte) bite;
_in = (_in + 1) % _buf.length;
_free--;
}
public void write ( byte[] buf, int off, int cbyte )
{
assert cbyte >= 0;
if (cbyte == 0)
return;
if (_free < cbyte)
resize( cbyte );
if (_in == _out)
{
assert getAvailable() == 0;
assert _free == _buf.length - getAvailable();
_in = _out = 0;
}
int chunk;
if (_in <= _out || cbyte < (chunk = _buf.length - _in))
{
System.arraycopy( buf, off, _buf, _in, cbyte );
_in += cbyte;
}
else
{
System.arraycopy( buf, off, _buf, _in, chunk );
System.arraycopy(
buf, off + chunk, _buf, 0, cbyte - chunk );
_in = (_in + cbyte) % _buf.length;
}
_free -= cbyte;
}
void resize ( int cbyte )
{
assert cbyte > _free;
int newLen = _buf == null ? _initialBufSize : _buf.length * 2;
int used = getAvailable();
while ( newLen - used < cbyte )
newLen *= 2;
byte[] newBuf = new byte [ newLen ];
if (used > 0)
{
if (_out == _in)
System.arraycopy( _buf, 0, newBuf, 0, used );
else if (_in > _out)
System.arraycopy( _buf, _out, newBuf, 0, used );
else
{
System.arraycopy(
_buf, _out, newBuf, 0, used - _in );
System.arraycopy(
_buf, 0, newBuf, used - _in, _in );
}
_out = 0;
_in = used;
_free += newBuf.length - _buf.length;
}
else
{
_free += newBuf.length;
assert _in == 0 && _out == 0;
}
_buf = newBuf;
}
private static final int _initialBufSize = 4096;
int _free;
int _in;
int _out;
byte[] _buf;
}
private Locale _locale;
private boolean _closed;
private OutputStreamImpl _outStreamImpl;
private TextSaver _textSaver;
private OutputStreamWriter _converter;
}
static final class SaxSaver extends Saver
{
SaxSaver ( Cur c, XmlOptions options, ContentHandler ch, LexicalHandler lh )
throws SAXException
{
super( c, options );
_contentHandler = ch;
_lexicalHandler = lh;
_attributes = new AttributesImpl();
_contentHandler.startDocument();
try
{
while ( process() )
;
}
catch ( SaverSAXException e )
{
throw e._saxException;
}
_contentHandler.endDocument();
}
private class SaverSAXException extends RuntimeException
{
SaverSAXException ( SAXException e )
{
_saxException = e;
}
SAXException _saxException;
}
private String getPrefixedName ( QName name )
{
String uri = name.getNamespaceURI();
String local = name.getLocalPart();
if (uri.length() == 0)
return local;
String prefix = getUriMapping( uri );
if (prefix.length() == 0)
return local;
return prefix + ":" + local;
}
private void emitNamespacesHelper ( )
{
for ( iterateMappings() ; hasMapping() ; nextMapping() )
{
String prefix = mappingPrefix();
String uri = mappingUri();
try
{
_contentHandler.startPrefixMapping( prefix, uri );
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
if (prefix == null || prefix.length() == 0)
_attributes.addAttribute( "http://www.w3.org/2000/xmlns/", "", "xmlns", "CDATA", uri );
else
_attributes.addAttribute( "http://www.w3.org/2000/xmlns/", "", "xmlns:" + prefix, "CDATA", uri );
}
}
protected boolean emitElement ( SaveCur c, ArrayList attrNames, ArrayList attrValues )
{
_attributes.clear();
if (saveNamespacesFirst())
emitNamespacesHelper();
for ( int i = 0 ; i < attrNames.size() ; i++ )
{
QName name = (QName) attrNames.get( i );
_attributes.addAttribute(
name.getNamespaceURI(), name.getLocalPart(), getPrefixedName( name ),
"CDATA", (String) attrValues.get( i ) );
}
if (!saveNamespacesFirst())
emitNamespacesHelper();
QName elemName = c.getName();
try
{
_contentHandler.startElement(
elemName.getNamespaceURI(), elemName.getLocalPart(),
getPrefixedName( elemName ), _attributes );
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
return false;
}
protected void emitFinish ( SaveCur c )
{
QName name = c.getName();
try
{
_contentHandler.endElement(
name.getNamespaceURI(), name.getLocalPart(), getPrefixedName( name ) );
for ( iterateMappings() ; hasMapping() ; nextMapping() )
_contentHandler.endPrefixMapping( mappingPrefix() );
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
}
protected void emitText ( SaveCur c )
{
assert c.isText();
Object src = c.getChars();
try
{
if (src instanceof char[])
{
// Pray the user does not modify the buffer ....
_contentHandler.characters( (char[]) src, c._offSrc, c._cchSrc );
}
else
{
if (_buf == null)
_buf = new char [ 1024 ];
while ( c._cchSrc > 0 )
{
int cch = java.lang.Math.min( _buf.length, c._cchSrc );
CharUtil.getChars( _buf, 0, src, c._offSrc, cch );
_contentHandler.characters( _buf, 0, cch );
c._offSrc += cch;
c._cchSrc -= cch;
}
}
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
}
protected void emitComment ( SaveCur c )
{
if (_lexicalHandler != null)
{
c.push();
c.next();
try
{
if (!c.isText())
_lexicalHandler.comment( null, 0, 0 );
else
{
Object src = c.getChars();
if (src instanceof char[])
{
// Pray the user does not modify the buffer ....
_lexicalHandler.comment( (char[]) src, c._offSrc, c._cchSrc );
}
else
{
if (_buf == null || _buf.length < c._cchSrc)
_buf = new char [ java.lang.Math.min( 1024, c._cchSrc ) ];
CharUtil.getChars( _buf, 0, src, c._offSrc, c._cchSrc );
_lexicalHandler.comment( _buf, 0, c._cchSrc );
}
}
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
c.pop();
}
}
protected void emitProcinst ( SaveCur c )
{
String target = c.getName().getLocalPart();
c.push();
c.next();
String value = CharUtil.getString( c.getChars(), c._offSrc, c._cchSrc );
c.pop();
try
{
_contentHandler.processingInstruction( c.getName().getLocalPart(), value );
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
}
protected void emitDocType ( String docTypeName, String publicId, String systemId )
{
if (_lexicalHandler != null)
{
try
{
_lexicalHandler.startDTD( docTypeName, publicId, systemId );
_lexicalHandler.endDTD();
}
catch ( SAXException e )
{
throw new SaverSAXException( e );
}
}
}
private ContentHandler _contentHandler;
private LexicalHandler _lexicalHandler;
private AttributesImpl _attributes;
private char[] _buf;
}
//
//
//
static abstract class SaveCur
{
final boolean isRoot ( ) { return kind() == ROOT; }
final boolean isElem ( ) { return kind() == ELEM; }
final boolean isAttr ( ) { return kind() == ATTR; }
final boolean isText ( ) { return kind() == TEXT; }
final boolean isComment ( ) { return kind() == COMMENT; }
final boolean isProcinst ( ) { return kind() == PROCINST; }
final boolean isFinish ( ) { return Cur.kindIsFinish( kind() ); }
final boolean isContainer ( ) { return Cur.kindIsContainer( kind() ); }
final boolean isNormalAttr ( ) { return kind() == ATTR && !isXmlns(); }
final boolean skip ( ) { toEnd(); return next(); }
abstract void release ( );
abstract int kind ( );
abstract QName getName ( );
abstract String getXmlnsPrefix ( );
abstract String getXmlnsUri ( );
abstract boolean isXmlns ( );
abstract boolean hasChildren ( );
abstract boolean hasText ( );
abstract boolean toFirstAttr ( );
abstract boolean toNextAttr ( );
abstract String getAttrValue ( );
abstract boolean next ( );
abstract void toEnd ( );
abstract void push ( );
abstract void pop ( );
abstract Object getChars ( );
abstract List getAncestorNamespaces ( );
abstract XmlDocumentProperties getDocProps ( );
int _offSrc;
int _cchSrc;
}
// TODO - saving a fragment need to take namesapces from root and
// reflect them on the document element
private static final class DocSaveCur extends SaveCur
{
DocSaveCur ( Cur c )
{
assert c.isRoot();
_cur = c.weakCur( this );
}
void release ( )
{
_cur.release();
_cur = null;
}
int kind ( ) { return _cur.kind(); }
QName getName ( ) { return _cur.getName(); }
String getXmlnsPrefix ( ) { return _cur.getXmlnsPrefix(); }
String getXmlnsUri ( ) { return _cur.getXmlnsUri(); }
boolean isXmlns ( ) { return _cur.isXmlns(); }
boolean hasChildren ( ) { return _cur.hasChildren(); }
boolean hasText ( ) { return _cur.hasText(); }
boolean toFirstAttr ( ) { return _cur.toFirstAttr(); }
boolean toNextAttr ( ) { return _cur.toNextAttr(); }
String getAttrValue ( ) { assert _cur.isAttr(); return _cur.getValueAsString(); }
void toEnd ( ) { _cur.toEnd(); }
boolean next ( ) { return _cur.next(); }
void push ( ) { _cur.push(); }
void pop ( ) { _cur.pop(); }
List getAncestorNamespaces ( ) { return null; }
Object getChars ( )
{
Object o = _cur.getChars( -1 );
_offSrc = _cur._offSrc;
_cchSrc = _cur._cchSrc;
return o;
}
XmlDocumentProperties getDocProps ( ) { return Locale.getDocProps(_cur, false); }
private Cur _cur;
}
private static abstract class FilterSaveCur extends SaveCur
{
FilterSaveCur ( SaveCur c )
{
assert c.isRoot();
_cur = c;
}
// Can filter anything by root and attributes and text
protected abstract boolean filter ( );
void release ( )
{
_cur.release();
_cur = null;
}
int kind ( ) { return _cur.kind(); }
QName getName ( ) { return _cur.getName(); }
String getXmlnsPrefix ( ) { return _cur.getXmlnsPrefix(); }
String getXmlnsUri ( ) { return _cur.getXmlnsUri(); }
boolean isXmlns ( ) { return _cur.isXmlns(); }
boolean hasChildren ( ) { return _cur.hasChildren(); }
boolean hasText ( ) { return _cur.hasText(); }
boolean toFirstAttr ( ) { return _cur.toFirstAttr(); }
boolean toNextAttr ( ) { return _cur.toNextAttr(); }
String getAttrValue ( ) { return _cur.getAttrValue(); }
void toEnd ( ) { _cur.toEnd(); }
boolean next ( )
{
if (!_cur.next())
return false;
if (!filter())
return true;
assert !isRoot() && !isText() && !isAttr();
toEnd();
return next();
}
void push ( ) { _cur.push(); }
void pop ( ) { _cur.pop(); }
List getAncestorNamespaces ( ) { return _cur.getAncestorNamespaces(); }
Object getChars ( )
{
Object o = _cur.getChars();
_offSrc = _cur._offSrc;
_cchSrc = _cur._cchSrc;
return o;
}
XmlDocumentProperties getDocProps ( ) { return _cur.getDocProps(); }
private SaveCur _cur;
}
private static final class FilterPiSaveCur extends FilterSaveCur
{
FilterPiSaveCur ( SaveCur c, String target )
{
super( c );
_piTarget = target;
}
protected boolean filter ( )
{
return kind() == PROCINST && getName().getLocalPart().equals( _piTarget );
}
private String _piTarget;
}
private static final class FragSaveCur extends SaveCur
{
FragSaveCur ( Cur start, Cur end, QName synthElem )
{
_saveAttr = start.isAttr() && start.isSamePos( end );
_cur = start.weakCur( this );
_end = end.weakCur( this );
_elem = synthElem;
_state = ROOT_START;
_stateStack = new int [ 8 ];
start.push();
computeAncestorNamespaces( start );
start.pop();
}
List getAncestorNamespaces ( )
{
return _ancestorNamespaces;
}
private void computeAncestorNamespaces ( Cur c )
{
_ancestorNamespaces = new ArrayList();
while ( c.toParentRaw() )
{
if (c.toFirstAttr())
{
do
{
if (c.isXmlns())
{
String prefix = c.getXmlnsPrefix();
String uri = c.getXmlnsUri();
// Don't let xmlns:foo="" get used
if (uri.length() > 0 || prefix.length() == 0)
{
_ancestorNamespaces.add( c.getXmlnsPrefix() );
_ancestorNamespaces.add( c.getXmlnsUri() );
}
}
}
while ( c.toNextAttr() );
c.toParent();
}
}
}
//
//
//
void release ( )
{
_cur.release();
_cur = null;
_end.release();
_end = null;
}
int kind ( )
{
switch ( _state )
{
case ROOT_START : return ROOT;
case ELEM_START : return ELEM;
case ELEM_END : return -ELEM;
case ROOT_END : return -ROOT;
}
assert _state == CUR;
return _cur.kind();
}
QName getName ( )
{
switch ( _state )
{
case ROOT_START :
case ROOT_END : return null;
case ELEM_START :
case ELEM_END : return _elem;
}
assert _state == CUR;
return _cur.getName();
}
String getXmlnsPrefix ( )
{
assert _state == CUR && _cur.isAttr();
return _cur.getXmlnsPrefix();
}
String getXmlnsUri ( )
{
assert _state == CUR && _cur.isAttr();
return _cur.getXmlnsUri();
}
boolean isXmlns ( )
{
assert _state == CUR && _cur.isAttr();
return _cur.isXmlns();
}
boolean hasChildren ( )
{
boolean hasChildren = false;
if (isContainer())
{ // is there a faster way to do this?
push();
next();
if (!isText() && !isFinish())
hasChildren = true;
pop();
}
return hasChildren;
}
boolean hasText ( )
{
boolean hasText = false;
if (isContainer())
{
push();
next();
if (isText())
hasText = true;
pop();
}
return hasText;
}
Object getChars ( )
{
assert _state == CUR && _cur.isText();
Object src = _cur.getChars( -1 );
_offSrc = _cur._offSrc;
_cchSrc = _cur._cchSrc;
return src;
}
boolean next ( )
{
switch ( _state )
{
case ROOT_START :
{
_state = _elem == null ? CUR : ELEM_START;
break;
}
case ELEM_START :
{
if (_saveAttr)
_state = ELEM_END;
else
{
if (_cur.isAttr())
{
_cur.toParent();
_cur.next();
}
if (_cur.isSamePos( _end ))
_state = ELEM_END;
else
_state = CUR;
}
break;
}
case CUR :
{
assert !_cur.isAttr();
_cur.next();
if (_cur.isSamePos( _end ))
_state = _elem == null ? ROOT_END : ELEM_END;
break;
}
case ELEM_END :
{
_state = ROOT_END;
break;
}
case ROOT_END :
return false;
}
return true;
}
void toEnd ( )
{
switch ( _state )
{
case ROOT_START : _state = ROOT_END; return;
case ELEM_START : _state = ELEM_END; return;
case ROOT_END :
case ELEM_END : return;
}
assert _state == CUR && !_cur.isAttr() && !_cur.isText();
_cur.toEnd();
}
boolean toFirstAttr ( )
{
switch ( _state )
{
case ROOT_END :
case ELEM_END :
case ROOT_START : return false;
case CUR : return _cur.toFirstAttr();
}
assert _state == ELEM_START;
if (!_cur.isAttr())
return false;
_state = CUR;
return true;
}
boolean toNextAttr ( )
{
assert _state == CUR;
return !_saveAttr && _cur.toNextAttr();
}
String getAttrValue ( )
{
assert _state == CUR && _cur.isAttr();
return _cur.getValueAsString();
}
void push ( )
{
if (_stateStackSize == _stateStack.length)
{
int[] newStateStack = new int [ _stateStackSize * 2 ];
System.arraycopy( _stateStack, 0, newStateStack, 0, _stateStackSize );
_stateStack = newStateStack;
}
_stateStack [ _stateStackSize++ ] = _state;
_cur.push();
}
void pop ()
{
_cur.pop();
_state = _stateStack [ --_stateStackSize ];
}
XmlDocumentProperties getDocProps ( ) { return Locale.getDocProps(_cur, false); }
//
//
//
private Cur _cur;
private Cur _end;
private ArrayList _ancestorNamespaces;
private QName _elem;
private boolean _saveAttr;
private static final int ROOT_START = 1;
private static final int ELEM_START = 2;
private static final int ROOT_END = 3;
private static final int ELEM_END = 4;
private static final int CUR = 5;
private int _state;
private int[] _stateStack;
private int _stateStackSize;
}
private static final class PrettySaveCur extends SaveCur
{
PrettySaveCur ( SaveCur c, XmlOptions options )
{
_sb = new StringBuffer();
_stack = new ArrayList();
_cur = c;
assert options != null;
_prettyIndent = 2;
if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT_INDENT ))
{
_prettyIndent =
((Integer) options.get( XmlOptions.SAVE_PRETTY_PRINT_INDENT )).intValue();
}
if (options.hasOption( XmlOptions.SAVE_PRETTY_PRINT_OFFSET ))
{
_prettyOffset =
((Integer) options.get( XmlOptions.SAVE_PRETTY_PRINT_OFFSET )).intValue();
}
}
List getAncestorNamespaces ( ) { return _cur.getAncestorNamespaces(); }
void release ( ) { _cur.release(); }
int kind ( ) { return _txt == null ? _cur.kind() : TEXT; }
QName getName ( ) { assert _txt == null; return _cur.getName(); }
String getXmlnsPrefix ( ) { assert _txt == null; return _cur.getXmlnsPrefix(); }
String getXmlnsUri ( ) { assert _txt == null; return _cur.getXmlnsUri(); }
boolean isXmlns ( ) { return _txt == null ? _cur.isXmlns() : false; }
boolean hasChildren ( ) { return _txt == null ? _cur.hasChildren() : false; }
boolean hasText ( ) { return _txt == null ? _cur.hasText() : false; }
boolean toFirstAttr ( ) { assert _txt == null; return _cur.toFirstAttr(); }
boolean toNextAttr ( ) { assert _txt == null; return _cur.toNextAttr(); }
String getAttrValue ( ) { assert _txt == null; return _cur.getAttrValue(); }
void toEnd ( )
{
assert _txt == null;
_cur.toEnd();
if (_cur.kind() == -ELEM)
_depth--;
}
boolean next ( )
{
int k;
if (_txt != null)
{
assert _txt.length() > 0;
assert !_cur.isText();
_txt = null;
k = _cur.kind();
}
else
{
int prevKind = k = _cur.kind();
if (!_cur.next())
return false;
_sb.delete( 0, _sb.length() );
assert _txt == null;
// place any text encountered in the buffer
if (_cur.isText())
{
CharUtil.getString( _sb, _cur.getChars(), _cur._offSrc, _cur._cchSrc );
_cur.next();
trim( _sb );
}
k = _cur.kind();
// Check for non leaf, _prettyIndent < 0 means that the save is all on one line
if (_prettyIndent >= 0 &&
prevKind != COMMENT && prevKind != PROCINST && (prevKind != ELEM || k != -ELEM))
// if (prevKind != COMMENT && prevKind != PROCINST && (prevKind != ELEM || k != -ELEM))
{
if (_sb.length() > 0)
{
_sb.insert( 0, _newLine );
spaces( _sb, _newLine.length(), _prettyOffset + _prettyIndent * _depth );
}
if (k != -ROOT)
{
if (prevKind != ROOT)
_sb.append( _newLine );
int d = k < 0 ? _depth - 1 : _depth;
spaces( _sb, _sb.length(), _prettyOffset + _prettyIndent * d );
}
}
if (_sb.length() > 0)
{
_txt = _sb.toString();
k = TEXT;
}
}
if (k == ELEM)
_depth++;
else if (k == -ELEM)
_depth--;
return true;
}
void push ( )
{
_cur.push();
_stack.add( _txt );
_stack.add( new Integer( _depth ) );
}
void pop ( )
{
_cur.pop();
_depth = ((Integer) _stack.remove( _stack.size() - 1 )).intValue();
_txt = (String) _stack.remove( _stack.size() - 1 );
}
Object getChars ( )
{
if (_txt != null)
{
_offSrc = 0;
_cchSrc = _txt.length();
return _txt;
}
Object o = _cur.getChars();
_offSrc = _cur._offSrc;
_cchSrc = _cur._cchSrc;
return o;
}
XmlDocumentProperties getDocProps ( ) { return _cur.getDocProps(); }
final static void spaces ( StringBuffer sb, int offset, int count )
{
while ( count-- > 0 )
sb.insert( offset, ' ' );
}
final static void trim ( StringBuffer sb )
{
int i;
for ( i = 0 ; i < sb.length() ; i++ )
if (!CharUtil.isWhiteSpace( sb.charAt( i ) ))
break;
sb.delete( 0, i );
for ( i = sb.length() ; i > 0 ; i-- )
if (!CharUtil.isWhiteSpace( sb.charAt( i - 1 ) ))
break;
sb.delete( i, sb.length() );
}
private SaveCur _cur;
private int _prettyIndent;
private int _prettyOffset;
private String _txt;
private StringBuffer _sb;
private int _depth;
private ArrayList _stack;
}
//
//
//
private final Locale _locale;
private final long _version;
private SaveCur _cur;
private List _ancestorNamespaces;
private Map _suggestedPrefixes;
protected XmlOptionCharEscapeMap _replaceChar;
private boolean _useDefaultNamespace;
private Map _preComputedNamespaces;
private boolean _saveNamespacesFirst;
private ArrayList _attrNames;
private ArrayList _attrValues;
private ArrayList _namespaceStack;
private int _currentMapping;
private HashMap _uriMap;
private HashMap _prefixMap;
private String _initialDefaultUri;
static final String _newLine =
SystemProperties.getProperty( "line.separator" ) == null
? "\n"
: SystemProperties.getProperty( "line.separator" );
}
|
Fix for XMLBEANS-192. The character sequence ]]> should not be output with the > unescaped unless it marks the end of a CDATA section.
Contributed by Lawrence Jones
git-svn-id: 297cb4147f50b389680bb5ad136787e97b9148ae@314983 13f79535-47bb-0310-9956-ffa450edef68
|
src/store/org/apache/xmlbeans/impl/store/Saver.java
|
Fix for XMLBEANS-192. The character sequence ]]> should not be output with the > unescaped unless it marks the end of a CDATA section.
|
<ide><path>rc/store/org/apache/xmlbeans/impl/store/Saver.java
<ide> boolean hasCharToBeReplaced = false;
<ide>
<ide> int count = 0;
<add> char prevChar = 0;
<add> char prevPrevChar = 0;
<ide> for ( int cch = _lastEmitCch ; cch > 0 ; cch-- )
<ide> {
<ide> char ch = _buf[ i ];
<ide>
<ide> if (ch == '<' || ch == '&')
<ide> count++;
<add> else if (prevPrevChar == ']' && prevChar == ']' && ch == '>' )
<add> hasCharToBeReplaced = true;
<ide> else if (isBadChar( ch ) || isEscapedChar( ch ))
<ide> hasCharToBeReplaced = true;
<ide>
<ide> if (++i == n)
<ide> i = 0;
<add>
<add> prevPrevChar = prevChar;
<add> prevChar = ch;
<ide> }
<ide>
<ide> if (count == 0 && !hasCharToBeReplaced)
|
|
Java
|
apache-2.0
|
b412278309bd7ea87f4b9dbf740ed0d0af781f00
| 0 |
antoinesd/weld-core,antoinesd/weld-core,manovotn/core,antoinesd/weld-core,weld/core,weld/core,manovotn/core,manovotn/core
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.weld.probe;
import static org.jboss.weld.probe.Strings.TEXT_HTML;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.jboss.weld.bean.builtin.BeanManagerProxy;
import org.jboss.weld.config.ConfigurationKey;
import org.jboss.weld.config.WeldConfiguration;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.probe.Invocation.Type;
import org.jboss.weld.probe.InvocationMonitor.Action;
import org.jboss.weld.probe.Resource.HttpMethod;
import org.jboss.weld.util.reflection.Formats;
/**
* This filter takes care of the servlet integration. Basically, it:
*
* <ul>
* <li>implements a simple REST API,</li>
* <li>allows to group together monitored invocations within the same request,</li>
* <li>allows to embed an informative HTML snippet to every response with Content-Type of value <code>text/html</code>.</li>
* </ul>
*
* <p>
* An integrator is required to register this filter. The filter should only be mapped to a single URL pattern of value <code>/*</code>.
* </p>
*
* <p>
* To disable the clippy support, set {@link ConfigurationKey#PROBE_EMBED_INFO_SNIPPET} to <code>false</code>. It's also possible to use the
* {@link ConfigurationKey#PROBE_INVOCATION_MONITOR_EXCLUDE_TYPE} to skip the monitoring.
* </p>
*
* @see ConfigurationKey#PROBE_EMBED_INFO_SNIPPET
* @see ConfigurationKey#PROBE_INVOCATION_MONITOR_EXCLUDE_TYPE
* @author Martin Kouba
*/
public class ProbeFilter implements Filter {
static final String REST_URL_PATTERN_BASE = "/weld-probe";
static final String WELD_SERVLET_BEAN_MANAGER_KEY = "org.jboss.weld.environment.servlet.javax.enterprise.inject.spi.BeanManager";
@Inject
private BeanManagerImpl beanManager;
// It shouldn't be necessary to make these fields volatile - see also javax.servlet.GenericServlet.config
private String snippetBase;
private Probe probe;
private JsonDataProvider jsonDataProvider;
private boolean skipMonitoring;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (beanManager == null) {
beanManager = BeanManagerProxy.tryUnwrap(filterConfig.getServletContext().getAttribute(WELD_SERVLET_BEAN_MANAGER_KEY));
if (beanManager == null) {
throw ProbeLogger.LOG.probeFilterUnableToOperate(BeanManagerImpl.class);
}
}
ProbeExtension probeExtension = beanManager.getExtension(ProbeExtension.class);
if (probeExtension == null) {
throw ProbeLogger.LOG.probeFilterUnableToOperate(ProbeExtension.class);
}
probe = probeExtension.getProbe();
if (!probe.isInitialized()) {
throw ProbeLogger.LOG.probeNotInitialized();
}
jsonDataProvider = probeExtension.getJsonDataProvider();
WeldConfiguration configuration = beanManager.getServices().get(WeldConfiguration.class);
if (configuration.getBooleanProperty(ConfigurationKey.PROBE_EMBED_INFO_SNIPPET)) {
snippetBase = initSnippetBase(filterConfig.getServletContext());
}
String exclude = configuration.getStringProperty(ConfigurationKey.PROBE_INVOCATION_MONITOR_EXCLUDE_TYPE);
skipMonitoring = !exclude.isEmpty() && Pattern.compile(exclude).matcher(ProbeFilter.class.getName()).matches();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
chain.doFilter(request, response);
return;
}
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final String[] resourcePathParts = getResourcePathParts(httpRequest.getRequestURI(), httpRequest.getServletContext().getContextPath());
if (resourcePathParts != null) {
// Probe resource
HttpMethod method = HttpMethod.from(httpRequest.getMethod());
if (method == null) {
// Unsupported protocol
if (httpRequest.getProtocol().endsWith("1.1")) {
httpResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
} else {
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
return;
}
processResourceRequest(httpRequest, httpResponse, method, resourcePathParts);
} else {
// Application request - init monitoring and embed info snippet if required
final Invocation.Builder builder;
if (!skipMonitoring) {
// Don't initialize a new builder if an entry point already exists
builder = InvocationMonitor.initBuilder(false);
if (builder != null) {
builder.setDeclaringClassName(ProbeFilter.class.getName());
builder.setStart(System.currentTimeMillis());
builder.setMethodName("doFilter");
builder.setType(Type.BUSINESS);
builder.setDescription(getDescription(httpRequest));
builder.ignoreIfNoChildren();
}
} else {
builder = null;
}
if (snippetBase == null) {
FilterAction.of(request, response).doFilter(builder, probe, chain);
} else {
embedInfoSnippet(httpRequest, httpResponse, builder, chain);
}
}
}
@Override
public void destroy() {
}
private void embedInfoSnippet(HttpServletRequest req, HttpServletResponse resp, Invocation.Builder builder, FilterChain chain)
throws IOException, ServletException {
ResponseWrapper responseWrapper = new ResponseWrapper(resp);
FilterAction.of(req, responseWrapper).doFilter(builder, probe, chain);
String captured = responseWrapper.getOutput();
if (captured != null && !captured.isEmpty()) {
// Writer was used
PrintWriter out = resp.getWriter();
if (resp.getContentType() != null && resp.getContentType().startsWith(TEXT_HTML)) {
int idx = captured.indexOf("</body>");
if (idx == -1) {
// </body> not found
out.write(captured);
} else {
CharArrayWriter writer = new CharArrayWriter();
writer.write(captured.substring(0, idx));
writer.write(snippetBase);
if (builder != null && !builder.isIgnored()) {
writer.write("See <a style=\"color:#337ab7;text-decoration:underline;\" href=\"");
writer.write(req.getServletContext().getContextPath());
// This path must be hardcoded unless we find an easy way to reference the client-specific configuration
writer.write(REST_URL_PATTERN_BASE + "/#/invocation/");
writer.write("" + builder.getEntryPointIdx());
writer.write("\" target=\"_blank\">all bean invocations</a> within the HTTP request which rendered this page.");
}
writer.write("</div>");
writer.write(captured.substring(idx, captured.length()));
out.write(writer.toString());
}
} else {
out.write(captured);
}
}
}
private String getDescription(HttpServletRequest req) {
StringBuilder builder = new StringBuilder();
builder.append(req.getMethod());
builder.append(' ');
builder.append(req.getRequestURI());
String queryString = req.getQueryString();
if (queryString != null) {
builder.append('?');
builder.append(queryString);
}
return builder.toString();
}
private String initSnippetBase(ServletContext servletContext) {
// Note that we have to use in-line CSS
StringBuilder builder = new StringBuilder();
builder.append("<!-- The following snippet was automatically added by Weld, see the documentation to disable this functionality -->");
builder.append(
"<div id=\"weld-dev-mode-info\" style=\"position: fixed !important;bottom:0;left:0;width:100%;background-color:#f8f8f8;border:2px solid silver;padding:10px;border-radius:2px;margin:0px;font-size:14px;font-family:sans-serif;color:black;\">");
builder.append("<img alt=\"Weld logo\" style=\"vertical-align: middle;border-width:0px;\" src=\"");
builder.append(servletContext.getContextPath());
builder.append(REST_URL_PATTERN_BASE + "/client/weld_icon_32x.png\">");
builder.append(" Running on Weld <span style=\"color:gray\">");
builder.append(Formats.getSimpleVersion());
builder.append(
"</span>. The development mode is <span style=\"color:white;background-color:#d62728;padding:6px;border-radius:4px;font-size:12px;\">ENABLED</span>. Inspect your application with <a style=\"color:#337ab7;text-decoration:underline;\" href=\"");
builder.append(servletContext.getContextPath());
builder.append(REST_URL_PATTERN_BASE);
builder.append("\" target=\"_blank\">Probe Development Tool</a>.");
builder.append(
" <button style=\"float:right;background-color:#f8f8f8;border:1px solid silver; color:gray;border-radius:4px;padding:4px 10px 4px 10px;margin-left:2em;font-weight: bold;\" onclick=\"document.getElementById('weld-dev-mode-info').style.display='none';\">x</button>");
return builder.toString();
}
private void processResourceRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod httpMethod, String[] resourcePathParts)
throws IOException {
Resource resource;
if (resourcePathParts.length == 0) {
resource = Resource.CLIENT_RESOURCE;
} else {
resource = matchResource(resourcePathParts);
if (resource == null) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
ProbeLogger.LOG.resourceMatched(resource, req.getRequestURI());
resource.handle(httpMethod, jsonDataProvider, resourcePathParts, req, resp);
}
private Resource matchResource(String[] resourcePathParts) {
for (Resource resource : Resource.values()) {
if (resource.matches(resourcePathParts)) {
return resource;
}
}
return null;
}
/**
*
* @return the array of resource path parts or <code>null</code> if the given URI does not represent a Probe resource
*/
static String[] getResourcePathParts(String requestUri, String contextPath) {
final String path = requestUri.substring(contextPath.length(), requestUri.length());
if (path.startsWith(REST_URL_PATTERN_BASE)) {
return Resource.splitPath(path.substring(REST_URL_PATTERN_BASE.length(), path.length()));
}
return null;
}
private static class ResponseWrapper extends HttpServletResponseWrapper {
private final CharArrayWriter output;
private final PrintWriter writer;
ResponseWrapper(HttpServletResponse response) {
super(response);
output = new CharArrayWriter();
writer = new PrintWriter(output);
}
public PrintWriter getWriter() {
return writer;
}
String getOutput() {
return output.toString();
}
}
private static class FilterAction extends Action<FilterChain> {
private static FilterAction of(ServletRequest request, ServletResponse response) {
return new FilterAction(request, response);
}
private final ServletRequest request;
private final ServletResponse response;
private FilterAction(ServletRequest request, ServletResponse response) {
this.request = request;
this.response = response;
}
@Override
protected Object proceed(FilterChain chain) throws Exception {
chain.doFilter(request, response);
return null;
}
void doFilter(Invocation.Builder builder, Probe probe, FilterChain chain) throws ServletException, IOException {
if (builder == null) {
chain.doFilter(request, response);
} else {
try {
perform(builder, probe, chain);
} catch (Exception e) {
throw new ServletException(e);
}
}
}
}
}
|
probe/core/src/main/java/org/jboss/weld/probe/ProbeFilter.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.jboss.weld.probe;
import static org.jboss.weld.probe.Strings.TEXT_HTML;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.jboss.weld.bean.builtin.BeanManagerProxy;
import org.jboss.weld.bootstrap.WeldBootstrap;
import org.jboss.weld.config.ConfigurationKey;
import org.jboss.weld.config.WeldConfiguration;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.probe.Invocation.Type;
import org.jboss.weld.probe.InvocationMonitor.Action;
import org.jboss.weld.probe.Resource.HttpMethod;
import org.jboss.weld.util.reflection.Formats;
/**
* This filter takes care of the servlet integration. Basically, it:
*
* <ul>
* <li>implements a simple REST API,</li>
* <li>allows to group together monitored invocations within the same request,</li>
* <li>allows to embed an informative HTML snippet to every response with Content-Type of value <code>text/html</code>.</li>
* </ul>
*
* <p>
* An integrator is required to register this filter. The filter should only be mapped to a single URL pattern of value <code>/*</code>.
* </p>
*
* <p>
* To disable the clippy support, set {@link ConfigurationKey#PROBE_EMBED_INFO_SNIPPET} to <code>false</code>. It's also possible to use the
* {@link ConfigurationKey#PROBE_INVOCATION_MONITOR_EXCLUDE_TYPE} to skip the monitoring.
* </p>
*
* @see ConfigurationKey#PROBE_EMBED_INFO_SNIPPET
* @see ConfigurationKey#PROBE_INVOCATION_MONITOR_EXCLUDE_TYPE
* @author Martin Kouba
*/
public class ProbeFilter implements Filter {
static final String REST_URL_PATTERN_BASE = "/weld-probe";
static final String WELD_SERVLET_BEAN_MANAGER_KEY = "org.jboss.weld.environment.servlet.javax.enterprise.inject.spi.BeanManager";
@Inject
private BeanManagerImpl beanManager;
// It shouldn't be necessary to make these fields volatile - see also javax.servlet.GenericServlet.config
private String snippetBase;
private Probe probe;
private JsonDataProvider jsonDataProvider;
private boolean skipMonitoring;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (beanManager == null) {
beanManager = BeanManagerProxy.tryUnwrap(filterConfig.getServletContext().getAttribute(WELD_SERVLET_BEAN_MANAGER_KEY));
if (beanManager == null) {
throw ProbeLogger.LOG.probeFilterUnableToOperate(BeanManagerImpl.class);
}
}
ProbeExtension probeExtension = beanManager.getExtension(ProbeExtension.class);
if (probeExtension == null) {
throw ProbeLogger.LOG.probeFilterUnableToOperate(ProbeExtension.class);
}
probe = probeExtension.getProbe();
if (!probe.isInitialized()) {
throw ProbeLogger.LOG.probeNotInitialized();
}
jsonDataProvider = probeExtension.getJsonDataProvider();
WeldConfiguration configuration = beanManager.getServices().get(WeldConfiguration.class);
if (configuration.getBooleanProperty(ConfigurationKey.PROBE_EMBED_INFO_SNIPPET)) {
snippetBase = initSnippetBase(filterConfig.getServletContext());
}
String exclude = configuration.getStringProperty(ConfigurationKey.PROBE_INVOCATION_MONITOR_EXCLUDE_TYPE);
skipMonitoring = !exclude.isEmpty() && Pattern.compile(exclude).matcher(ProbeFilter.class.getName()).matches();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
chain.doFilter(request, response);
return;
}
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final String[] resourcePathParts = getResourcePathParts(httpRequest.getRequestURI(), httpRequest.getServletContext().getContextPath());
if (resourcePathParts != null) {
// Probe resource
HttpMethod method = HttpMethod.from(httpRequest.getMethod());
if (method == null) {
// Unsupported protocol
if (httpRequest.getProtocol().endsWith("1.1")) {
httpResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
} else {
httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
return;
}
processResourceRequest(httpRequest, httpResponse, method, resourcePathParts);
} else {
// Application request - init monitoring and embed info snippet if required
final Invocation.Builder builder;
if (!skipMonitoring) {
// Don't initialize a new builder if an entry point already exists
builder = InvocationMonitor.initBuilder(false);
if (builder != null) {
builder.setDeclaringClassName(ProbeFilter.class.getName());
builder.setStart(System.currentTimeMillis());
builder.setMethodName("doFilter");
builder.setType(Type.BUSINESS);
builder.setDescription(getDescription(httpRequest));
builder.ignoreIfNoChildren();
}
} else {
builder = null;
}
if (snippetBase == null) {
FilterAction.of(request, response).doFilter(builder, probe, chain);
} else {
embedInfoSnippet(httpRequest, httpResponse, builder, chain);
}
}
}
@Override
public void destroy() {
}
private void embedInfoSnippet(HttpServletRequest req, HttpServletResponse resp, Invocation.Builder builder, FilterChain chain)
throws IOException, ServletException {
ResponseWrapper responseWrapper = new ResponseWrapper(resp);
FilterAction.of(req, responseWrapper).doFilter(builder, probe, chain);
String captured = responseWrapper.getOutput();
if (captured != null && !captured.isEmpty()) {
// Writer was used
PrintWriter out = resp.getWriter();
if (resp.getContentType() != null && resp.getContentType().startsWith(TEXT_HTML)) {
int idx = captured.indexOf("</body>");
if (idx == -1) {
// </body> not found
out.write(captured);
} else {
CharArrayWriter writer = new CharArrayWriter();
writer.write(captured.substring(0, idx));
writer.write(snippetBase);
if (builder != null && !builder.isIgnored()) {
writer.write("See <a style=\"color:#337ab7;text-decoration:underline;\" href=\"");
writer.write(req.getServletContext().getContextPath());
// This path must be hardcoded unless we find an easy way to reference the client-specific configuration
writer.write(REST_URL_PATTERN_BASE + "/#/invocation/");
writer.write("" + builder.getEntryPointIdx());
writer.write("\" target=\"_blank\">all bean invocations</a> within the HTTP request which rendered this page.");
}
writer.write("</div>");
writer.write(captured.substring(idx, captured.length()));
out.write(writer.toString());
}
} else {
out.write(captured);
}
}
}
private String getDescription(HttpServletRequest req) {
StringBuilder builder = new StringBuilder();
builder.append(req.getMethod());
builder.append(' ');
builder.append(req.getRequestURI());
String queryString = req.getQueryString();
if (queryString != null) {
builder.append('?');
builder.append(queryString);
}
return builder.toString();
}
private String initSnippetBase(ServletContext servletContext) {
// Note that we have to use in-line CSS
StringBuilder builder = new StringBuilder();
builder.append("<!-- The following snippet was automatically added by Weld, see the documentation to disable this functionality -->");
builder.append(
"<div id=\"weld-dev-mode-info\" style=\"position: fixed !important;bottom:0;left:0;width:100%;background-color:#f8f8f8;border:2px solid silver;padding:10px;border-radius:2px;margin:0px;font-size:14px;font-family:sans-serif;color:black;\">");
builder.append("<img alt=\"Weld logo\" style=\"vertical-align: middle;border-width:0px;\" src=\"");
builder.append(servletContext.getContextPath());
builder.append(REST_URL_PATTERN_BASE + "/client/weld_icon_32x.png\">");
builder.append(" Running on Weld <span style=\"color:gray\">");
builder.append(Formats.version(WeldBootstrap.class.getPackage().getSpecificationVersion(), null));
builder.append(
"</span>. The development mode is <span style=\"color:white;background-color:#d62728;padding:6px;border-radius:4px;font-size:12px;\">ENABLED</span>. Inspect your application with <a style=\"color:#337ab7;text-decoration:underline;\" href=\"");
builder.append(servletContext.getContextPath());
builder.append(REST_URL_PATTERN_BASE);
builder.append("\" target=\"_blank\">Probe Development Tool</a>.");
builder.append(
" <button style=\"float:right;background-color:#f8f8f8;border:1px solid silver; color:gray;border-radius:4px;padding:4px 10px 4px 10px;margin-left:2em;font-weight: bold;\" onclick=\"document.getElementById('weld-dev-mode-info').style.display='none';\">x</button>");
return builder.toString();
}
private void processResourceRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod httpMethod, String[] resourcePathParts)
throws IOException {
Resource resource;
if (resourcePathParts.length == 0) {
resource = Resource.CLIENT_RESOURCE;
} else {
resource = matchResource(resourcePathParts);
if (resource == null) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
ProbeLogger.LOG.resourceMatched(resource, req.getRequestURI());
resource.handle(httpMethod, jsonDataProvider, resourcePathParts, req, resp);
}
private Resource matchResource(String[] resourcePathParts) {
for (Resource resource : Resource.values()) {
if (resource.matches(resourcePathParts)) {
return resource;
}
}
return null;
}
/**
*
* @return the array of resource path parts or <code>null</code> if the given URI does not represent a Probe resource
*/
static String[] getResourcePathParts(String requestUri, String contextPath) {
final String path = requestUri.substring(contextPath.length(), requestUri.length());
if (path.startsWith(REST_URL_PATTERN_BASE)) {
return Resource.splitPath(path.substring(REST_URL_PATTERN_BASE.length(), path.length()));
}
return null;
}
private static class ResponseWrapper extends HttpServletResponseWrapper {
private final CharArrayWriter output;
private final PrintWriter writer;
ResponseWrapper(HttpServletResponse response) {
super(response);
output = new CharArrayWriter();
writer = new PrintWriter(output);
}
public PrintWriter getWriter() {
return writer;
}
String getOutput() {
return output.toString();
}
}
private static class FilterAction extends Action<FilterChain> {
private static FilterAction of(ServletRequest request, ServletResponse response) {
return new FilterAction(request, response);
}
private final ServletRequest request;
private final ServletResponse response;
private FilterAction(ServletRequest request, ServletResponse response) {
this.request = request;
this.response = response;
}
@Override
protected Object proceed(FilterChain chain) throws Exception {
chain.doFilter(request, response);
return null;
}
void doFilter(Invocation.Builder builder, Probe probe, FilterChain chain) throws ServletException, IOException {
if (builder == null) {
chain.doFilter(request, response);
} else {
try {
perform(builder, probe, chain);
} catch (Exception e) {
throw new ServletException(e);
}
}
}
}
}
|
WELD-2016 ProbeFilter - use Formats.getSimpleVersion()
|
probe/core/src/main/java/org/jboss/weld/probe/ProbeFilter.java
|
WELD-2016 ProbeFilter - use Formats.getSimpleVersion()
|
<ide><path>robe/core/src/main/java/org/jboss/weld/probe/ProbeFilter.java
<ide> import javax.servlet.http.HttpServletResponseWrapper;
<ide>
<ide> import org.jboss.weld.bean.builtin.BeanManagerProxy;
<del>import org.jboss.weld.bootstrap.WeldBootstrap;
<ide> import org.jboss.weld.config.ConfigurationKey;
<ide> import org.jboss.weld.config.WeldConfiguration;
<ide> import org.jboss.weld.manager.BeanManagerImpl;
<ide> builder.append(servletContext.getContextPath());
<ide> builder.append(REST_URL_PATTERN_BASE + "/client/weld_icon_32x.png\">");
<ide> builder.append(" Running on Weld <span style=\"color:gray\">");
<del> builder.append(Formats.version(WeldBootstrap.class.getPackage().getSpecificationVersion(), null));
<add> builder.append(Formats.getSimpleVersion());
<ide> builder.append(
<ide> "</span>. The development mode is <span style=\"color:white;background-color:#d62728;padding:6px;border-radius:4px;font-size:12px;\">ENABLED</span>. Inspect your application with <a style=\"color:#337ab7;text-decoration:underline;\" href=\"");
<ide> builder.append(servletContext.getContextPath());
|
|
Java
|
apache-2.0
|
a7f879db7682841539468f9af71f8b28423d9321
| 0 |
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
|
package org.apache.solr.cloud;
/*
* 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.
*/
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.cloud.BeforeReconnect;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DefaultConnectionStrategy;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.OnReconnect;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkCmdExecutor;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.cloud.ZooKeeperException;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.component.ShardHandler;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.UpdateShardHandler;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.SessionExpiredException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Handle ZooKeeper interactions.
*
* notes: loads everything on init, creates what's not there - further updates
* are prompted with Watches.
*
* TODO: exceptions during shutdown on attempts to update cloud state
*
*/
public final class ZkController {
private static Logger log = LoggerFactory.getLogger(ZkController.class);
static final String NEWL = System.getProperty("line.separator");
private final static Pattern URL_POST = Pattern.compile("https?://(.*)");
private final static Pattern URL_PREFIX = Pattern.compile("(https?://).*");
private final boolean SKIP_AUTO_RECOVERY = Boolean.getBoolean("solrcloud.skip.autorecovery");
private final DistributedQueue overseerJobQueue;
private final DistributedQueue overseerCollectionQueue;
public static final String CONFIGS_ZKNODE = "/configs";
public final static String COLLECTION_PARAM_PREFIX="collection.";
public final static String CONFIGNAME_PROP="configName";
static class ContextKey {
private String collection;
private String coreNodeName;
public ContextKey(String collection, String coreNodeName) {
this.collection = collection;
this.coreNodeName = coreNodeName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((collection == null) ? 0 : collection.hashCode());
result = prime * result
+ ((coreNodeName == null) ? 0 : coreNodeName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ContextKey other = (ContextKey) obj;
if (collection == null) {
if (other.collection != null) return false;
} else if (!collection.equals(other.collection)) return false;
if (coreNodeName == null) {
if (other.coreNodeName != null) return false;
} else if (!coreNodeName.equals(other.coreNodeName)) return false;
return true;
}
}
private final Map<ContextKey, ElectionContext> electionContexts = Collections.synchronizedMap(new HashMap<ContextKey, ElectionContext>());
private SolrZkClient zkClient;
private ZkCmdExecutor cmdExecutor;
private ZkStateReader zkStateReader;
private LeaderElector leaderElector;
private String zkServerAddress; // example: 127.0.0.1:54062/solr
private final String localHostPort; // example: 54065
private final String localHostContext; // example: solr
private final String localHost; // example: http://127.0.0.1
private final String hostName; // example: 127.0.0.1
private final String nodeName; // example: 127.0.0.1:54065_solr
private final String baseURL; // example: http://127.0.0.1:54065/solr
private LeaderElector overseerElector;
// for now, this can be null in tests, in which case recovery will be inactive, and other features
// may accept defaults or use mocks rather than pulling things from a CoreContainer
private CoreContainer cc;
protected volatile Overseer overseer;
private int leaderVoteWait;
private boolean genericCoreNodeNames;
private int clientTimeout;
private volatile boolean isClosed;
public ZkController(final CoreContainer cc, String zkServerAddress, int zkClientTimeout, int zkClientConnectTimeout, String localHost, String locaHostPort,
String localHostContext, int leaderVoteWait, boolean genericCoreNodeNames, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException,
TimeoutException, IOException {
if (cc == null) throw new IllegalArgumentException("CoreContainer cannot be null.");
this.cc = cc;
this.genericCoreNodeNames = genericCoreNodeNames;
// be forgiving and strip this off leading/trailing slashes
// this allows us to support users specifying hostContext="/" in
// solr.xml to indicate the root context, instead of hostContext=""
// which means the default of "solr"
localHostContext = trimLeadingAndTrailingSlashes(localHostContext);
this.zkServerAddress = zkServerAddress;
this.localHostPort = locaHostPort;
this.localHostContext = localHostContext;
this.localHost = getHostAddress(localHost);
this.baseURL = this.localHost + ":" + this.localHostPort +
(this.localHostContext.isEmpty() ? "" : ("/" + this.localHostContext));
this.hostName = getHostNameFromAddress(this.localHost);
this.nodeName = generateNodeName(this.hostName,
this.localHostPort,
this.localHostContext);
this.leaderVoteWait = leaderVoteWait;
this.clientTimeout = zkClientTimeout;
zkClient = new SolrZkClient(zkServerAddress, zkClientTimeout,
zkClientConnectTimeout, new DefaultConnectionStrategy(),
// on reconnect, reload cloud info
new OnReconnect() {
@Override
public void command() {
try {
markAllAsNotLeader(registerOnReconnect);
// this is troublesome - we dont want to kill anything the old
// leader accepted
// though I guess sync will likely get those updates back? But
// only if
// he is involved in the sync, and he certainly may not be
// ExecutorUtil.shutdownAndAwaitTermination(cc.getCmdDistribExecutor());
// we need to create all of our lost watches
// seems we dont need to do this again...
// Overseer.createClientNodes(zkClient, getNodeName());
ShardHandler shardHandler;
String adminPath;
shardHandler = cc.getShardHandlerFactory().getShardHandler();
adminPath = cc.getAdminPath();
cc.cancelCoreRecoveries();
registerAllCoresAsDown(registerOnReconnect, false);
ElectionContext context = new OverseerElectionContext(zkClient,
overseer, getNodeName());
overseerElector.joinElection(context, true);
zkStateReader.createClusterStateWatchersAndUpdate();
// we have to register as live first to pick up docs in the buffer
createEphemeralLiveNode();
List<CoreDescriptor> descriptors = registerOnReconnect
.getCurrentDescriptors();
// re register all descriptors
if (descriptors != null) {
for (CoreDescriptor descriptor : descriptors) {
// TODO: we need to think carefully about what happens when it
// was
// a leader that was expired - as well as what to do about
// leaders/overseers
// with connection loss
try {
register(descriptor.getName(), descriptor, true, true);
} catch (Throwable t) {
SolrException.log(log, "Error registering SolrCore", t);
}
}
}
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
throw new ZooKeeperException(
SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (Exception e) {
SolrException.log(log, "", e);
throw new ZooKeeperException(
SolrException.ErrorCode.SERVER_ERROR, "", e);
}
}
}, new BeforeReconnect() {
@Override
public void command() {
try {
ZkController.this.overseer.close();
} catch (Exception e) {
log.error("Error trying to stop any Overseer threads", e);
}
}
});
this.overseerJobQueue = Overseer.getInQueue(zkClient);
this.overseerCollectionQueue = Overseer.getCollectionQueue(zkClient);
cmdExecutor = new ZkCmdExecutor(zkClientTimeout);
leaderElector = new LeaderElector(zkClient);
zkStateReader = new ZkStateReader(zkClient);
init(registerOnReconnect);
}
public int getLeaderVoteWait() {
return leaderVoteWait;
}
private void registerAllCoresAsDown(
final CurrentCoreDescriptorProvider registerOnReconnect, boolean updateLastPublished) {
List<CoreDescriptor> descriptors = registerOnReconnect
.getCurrentDescriptors();
if (isClosed) return;
if (descriptors != null) {
// before registering as live, make sure everyone is in a
// down state
for (CoreDescriptor descriptor : descriptors) {
final String coreZkNodeName = descriptor.getCloudDescriptor().getCoreNodeName();
try {
descriptor.getCloudDescriptor().setLeader(false);
publish(descriptor, ZkStateReader.DOWN, updateLastPublished);
} catch (Exception e) {
if (isClosed) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
try {
publish(descriptor, ZkStateReader.DOWN);
} catch (Exception e2) {
SolrException.log(log, "", e2);
continue;
}
}
// if it looks like we are going to be the leader, we don't
// want to wait for the following stuff
CloudDescriptor cloudDesc = descriptor.getCloudDescriptor();
String collection = cloudDesc.getCollectionName();
String slice = cloudDesc.getShardId();
try {
int children = zkStateReader
.getZkClient()
.getChildren(
ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection
+ "/leader_elect/" + slice + "/election", null, true).size();
if (children == 0) {
return;
}
} catch (NoNodeException e) {
return;
} catch (InterruptedException e2) {
Thread.currentThread().interrupt();
} catch (KeeperException e) {
log.warn("", e);
Thread.currentThread().interrupt();
}
try {
waitForLeaderToSeeDownState(descriptor, coreZkNodeName);
} catch (Exception e) {
SolrException.log(log, "", e);
if (isClosed) {
return;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
}
}
}
private void markAllAsNotLeader(
final CurrentCoreDescriptorProvider registerOnReconnect) {
List<CoreDescriptor> descriptors = registerOnReconnect
.getCurrentDescriptors();
if (descriptors != null) {
for (CoreDescriptor descriptor : descriptors) {
descriptor.getCloudDescriptor().setLeader(false);
}
}
}
/**
* Closes the underlying ZooKeeper client.
*/
public void close() {
this.isClosed = true;
for (ElectionContext context : electionContexts.values()) {
try {
context.close();
} catch (Throwable t) {
log.error("Error closing overseer", t);
}
}
try {
overseer.close();
} catch(Throwable t) {
log.error("Error closing overseer", t);
}
try {
zkStateReader.close();
} catch(Throwable t) {
log.error("Error closing zkStateReader", t);
}
try {
zkClient.close();;
} catch(Throwable t) {
log.error("Error closing zkClient", t);
}
}
/**
* Returns true if config file exists
*/
public boolean configFileExists(String collection, String fileName)
throws KeeperException, InterruptedException {
Stat stat = zkClient.exists(CONFIGS_ZKNODE + "/" + collection + "/" + fileName, null, true);
return stat != null;
}
/**
* @return information about the cluster from ZooKeeper
*/
public ClusterState getClusterState() {
return zkStateReader.getClusterState();
}
/**
* Returns config file data (in bytes)
*/
public byte[] getConfigFileData(String zkConfigName, String fileName)
throws KeeperException, InterruptedException {
String zkPath = CONFIGS_ZKNODE + "/" + zkConfigName + "/" + fileName;
byte[] bytes = zkClient.getData(zkPath, null, null, true);
if (bytes == null) {
log.error("Config file contains no data:" + zkPath);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
"Config file contains no data:" + zkPath);
}
return bytes;
}
// normalize host to url_prefix://host
// input can be null, host, or url_prefix://host
private String getHostAddress(String host) throws IOException {
if (host == null || host.length() == 0) {
String hostaddress;
try {
hostaddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
hostaddress = "127.0.0.1"; // cannot resolve system hostname, fall through
}
// Re-get the IP again for "127.0.0.1", the other case we trust the hosts
// file is right.
if ("127.0.0.1".equals(hostaddress)) {
Enumeration<NetworkInterface> netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress ip = ips.nextElement();
if (ip.isSiteLocalAddress()) {
hostaddress = ip.getHostAddress();
}
}
}
} catch (Throwable e) {
SolrException.log(log,
"Error while looking for a better host name than 127.0.0.1", e);
}
}
host = "http://" + hostaddress;
} else {
Matcher m = URL_PREFIX.matcher(host);
if (m.matches()) {
String prefix = m.group(1);
host = prefix + host;
} else {
host = "http://" + host;
}
}
return host;
}
// extract host from url_prefix://host
private String getHostNameFromAddress(String addr) {
Matcher m = URL_POST.matcher(addr);
if (m.matches()) {
return m.group(1);
} else {
log.error("Unrecognized host:" + addr);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
"Unrecognized host:" + addr);
}
}
public String getHostName() {
return hostName;
}
public String getHostPort() {
return localHostPort;
}
public SolrZkClient getZkClient() {
return zkClient;
}
/**
* @return zookeeper server address
*/
public String getZkServerAddress() {
return zkServerAddress;
}
private void init(CurrentCoreDescriptorProvider registerOnReconnect) {
try {
boolean createdWatchesAndUpdated = false;
if (zkClient.exists(ZkStateReader.LIVE_NODES_ZKNODE, true)) {
zkStateReader.createClusterStateWatchersAndUpdate();
createdWatchesAndUpdated = true;
publishAndWaitForDownStates();
}
// makes nodes zkNode
cmdExecutor.ensureExists(ZkStateReader.LIVE_NODES_ZKNODE, zkClient);
createEphemeralLiveNode();
cmdExecutor.ensureExists(ZkStateReader.COLLECTIONS_ZKNODE, zkClient);
ShardHandler shardHandler;
String adminPath;
shardHandler = cc.getShardHandlerFactory().getShardHandler();
adminPath = cc.getAdminPath();
overseerElector = new LeaderElector(zkClient);
this.overseer = new Overseer(shardHandler, adminPath, zkStateReader);
ElectionContext context = new OverseerElectionContext(zkClient, overseer, getNodeName());
overseerElector.setup(context);
overseerElector.joinElection(context, false);
if (!createdWatchesAndUpdated) {
zkStateReader.createClusterStateWatchersAndUpdate();
}
} catch (IOException e) {
log.error("", e);
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Can't create ZooKeeperController", e);
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
"", e);
} catch (KeeperException e) {
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
"", e);
}
}
public void publishAndWaitForDownStates() throws KeeperException,
InterruptedException {
ClusterState clusterState = zkStateReader.getClusterState();
Set<String> collections = clusterState.getCollections();
List<String> updatedNodes = new ArrayList<String>();
for (String collectionName : collections) {
DocCollection collection = clusterState.getCollection(collectionName);
Collection<Slice> slices = collection.getSlices();
for (Slice slice : slices) {
Collection<Replica> replicas = slice.getReplicas();
for (Replica replica : replicas) {
if (replica.getNodeName().equals(getNodeName())
&& !(replica.getStr(ZkStateReader.STATE_PROP)
.equals(ZkStateReader.DOWN))) {
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",
ZkStateReader.STATE_PROP, ZkStateReader.DOWN,
ZkStateReader.BASE_URL_PROP, getBaseUrl(),
ZkStateReader.CORE_NAME_PROP,
replica.getStr(ZkStateReader.CORE_NAME_PROP),
ZkStateReader.ROLES_PROP,
replica.getStr(ZkStateReader.ROLES_PROP),
ZkStateReader.NODE_NAME_PROP, getNodeName(),
ZkStateReader.SHARD_ID_PROP,
replica.getStr(ZkStateReader.SHARD_ID_PROP),
ZkStateReader.COLLECTION_PROP, collectionName,
ZkStateReader.CORE_NODE_NAME_PROP, replica.getName());
updatedNodes.add(replica.getStr(ZkStateReader.CORE_NAME_PROP));
overseerJobQueue.offer(ZkStateReader.toJSON(m));
}
}
}
}
// now wait till the updates are in our state
long now = System.currentTimeMillis();
long timeout = now + 1000 * 30;
boolean foundStates = false;
while (System.currentTimeMillis() < timeout) {
clusterState = zkStateReader.getClusterState();
collections = clusterState.getCollections();
for (String collectionName : collections) {
DocCollection collection = clusterState.getCollection(collectionName);
Collection<Slice> slices = collection.getSlices();
for (Slice slice : slices) {
Collection<Replica> replicas = slice.getReplicas();
for (Replica replica : replicas) {
if (replica.getStr(ZkStateReader.STATE_PROP).equals(
ZkStateReader.DOWN)) {
updatedNodes.remove(replica.getStr(ZkStateReader.CORE_NAME_PROP));
}
}
}
}
if (updatedNodes.size() == 0) {
foundStates = true;
Thread.sleep(1000);
break;
}
Thread.sleep(1000);
}
if (!foundStates) {
log.warn("Timed out waiting to see all nodes published as DOWN in our cluster state.");
}
}
/**
* Validates if the chroot exists in zk (or if it is successfully created).
* Optionally, if create is set to true this method will create the path in
* case it doesn't exist
*
* @return true if the path exists or is created false if the path doesn't
* exist and 'create' = false
*/
public static boolean checkChrootPath(String zkHost, boolean create)
throws KeeperException, InterruptedException {
if (!containsChroot(zkHost)) {
return true;
}
log.info("zkHost includes chroot");
String chrootPath = zkHost.substring(zkHost.indexOf("/"), zkHost.length());
SolrZkClient tmpClient = new SolrZkClient(zkHost.substring(0,
zkHost.indexOf("/")), 60 * 1000);
boolean exists = tmpClient.exists(chrootPath, true);
if (!exists && create) {
tmpClient.makePath(chrootPath, false, true);
exists = true;
}
tmpClient.close();
return exists;
}
/**
* Validates if zkHost contains a chroot. See http://zookeeper.apache.org/doc/r3.2.2/zookeeperProgrammers.html#ch_zkSessions
*/
private static boolean containsChroot(String zkHost) {
return zkHost.contains("/");
}
public boolean isConnected() {
return zkClient.isConnected();
}
private void createEphemeralLiveNode() throws KeeperException,
InterruptedException {
String nodeName = getNodeName();
String nodePath = ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName;
log.info("Register node as live in ZooKeeper:" + nodePath);
try {
boolean nodeDeleted = true;
try {
// we attempt a delete in the case of a quick server bounce -
// if there was not a graceful shutdown, the node may exist
// until expiration timeout - so a node won't be created here because
// it exists, but eventually the node will be removed. So delete
// in case it exists and create a new node.
zkClient.delete(nodePath, -1, true);
} catch (KeeperException.NoNodeException e) {
// fine if there is nothing to delete
// TODO: annoying that ZK logs a warning on us
nodeDeleted = false;
}
if (nodeDeleted) {
log
.info("Found a previous node that still exists while trying to register a new live node "
+ nodePath + " - removing existing node to create another.");
}
zkClient.makePath(nodePath, CreateMode.EPHEMERAL, true);
} catch (KeeperException e) {
// its okay if the node already exists
if (e.code() != KeeperException.Code.NODEEXISTS) {
throw e;
}
}
}
public String getNodeName() {
return nodeName;
}
/**
* Returns true if the path exists
*/
public boolean pathExists(String path) throws KeeperException,
InterruptedException {
return zkClient.exists(path, true);
}
/**
* Register shard with ZooKeeper.
*
* @return the shardId for the SolrCore
*/
public String register(String coreName, final CoreDescriptor desc) throws Exception {
return register(coreName, desc, false, false);
}
/**
* Register shard with ZooKeeper.
*
* @return the shardId for the SolrCore
*/
public String register(String coreName, final CoreDescriptor desc, boolean recoverReloadedCores, boolean afterExpiration) throws Exception {
final String baseUrl = getBaseUrl();
final CloudDescriptor cloudDesc = desc.getCloudDescriptor();
final String collection = cloudDesc.getCollectionName();
final String coreZkNodeName = desc.getCloudDescriptor().getCoreNodeName();
assert coreZkNodeName != null : "we should have a coreNodeName by now";
String shardId = cloudDesc.getShardId();
Map<String,Object> props = new HashMap<String,Object>();
// we only put a subset of props into the leader node
props.put(ZkStateReader.BASE_URL_PROP, baseUrl);
props.put(ZkStateReader.CORE_NAME_PROP, coreName);
props.put(ZkStateReader.NODE_NAME_PROP, getNodeName());
if (log.isInfoEnabled()) {
log.info("Register replica - core:" + coreName + " address:"
+ baseUrl + " collection:" + cloudDesc.getCollectionName() + " shard:" + shardId);
}
ZkNodeProps leaderProps = new ZkNodeProps(props);
try {
joinElection(desc, afterExpiration);
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (KeeperException e) {
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (IOException e) {
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
}
// in this case, we want to wait for the leader as long as the leader might
// wait for a vote, at least - but also long enough that a large cluster has
// time to get its act together
String leaderUrl = getLeader(cloudDesc, leaderVoteWait + 600000);
String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName);
log.info("We are " + ourUrl + " and leader is " + leaderUrl);
boolean isLeader = leaderUrl.equals(ourUrl);
SolrCore core = null;
try {
core = cc.getCore(desc.getName());
// recover from local transaction log and wait for it to complete before
// going active
// TODO: should this be moved to another thread? To recoveryStrat?
// TODO: should this actually be done earlier, before (or as part of)
// leader election perhaps?
// TODO: if I'm the leader, ensure that a replica that is trying to recover waits until I'm
// active (or don't make me the
// leader until my local replay is done.
UpdateLog ulog = core.getUpdateHandler().getUpdateLog();
if (!core.isReloaded() && ulog != null) {
// disable recovery in case shard is in construction state (for shard splits)
Slice slice = getClusterState().getSlice(collection, shardId);
if (!Slice.CONSTRUCTION.equals(slice.getState()) || !isLeader) {
Future<UpdateLog.RecoveryInfo> recoveryFuture = core.getUpdateHandler()
.getUpdateLog().recoverFromLog();
if (recoveryFuture != null) {
recoveryFuture.get(); // NOTE: this could potentially block for
// minutes or more!
// TODO: public as recovering in the mean time?
// TODO: in the future we could do peersync in parallel with recoverFromLog
} else {
log.info("No LogReplay needed for core=" + core.getName() + " baseURL=" + baseUrl);
}
}
boolean didRecovery = checkRecovery(coreName, desc, recoverReloadedCores, isLeader, cloudDesc,
collection, coreZkNodeName, shardId, leaderProps, core, cc);
if (!didRecovery) {
publish(desc, ZkStateReader.ACTIVE);
}
}
} finally {
if (core != null) {
core.close();
}
}
// make sure we have an update cluster state right away
zkStateReader.updateClusterState(true);
return shardId;
}
// timeoutms is the timeout for the first call to get the leader - there is then
// a longer wait to make sure that leader matches our local state
private String getLeader(final CloudDescriptor cloudDesc, int timeoutms) {
String collection = cloudDesc.getCollectionName();
String shardId = cloudDesc.getShardId();
// rather than look in the cluster state file, we go straight to the zknodes
// here, because on cluster restart there could be stale leader info in the
// cluster state node that won't be updated for a moment
String leaderUrl;
try {
leaderUrl = getLeaderProps(collection, cloudDesc.getShardId(), timeoutms)
.getCoreUrl();
// now wait until our currently cloud state contains the latest leader
String clusterStateLeaderUrl = zkStateReader.getLeaderUrl(collection,
shardId, timeoutms * 2); // since we found it in zk, we are willing to
// wait a while to find it in state
int tries = 0;
while (!leaderUrl.equals(clusterStateLeaderUrl)) {
if (tries == 60) {
throw new SolrException(ErrorCode.SERVER_ERROR,
"There is conflicting information about the leader of shard: "
+ cloudDesc.getShardId() + " our state says:"
+ clusterStateLeaderUrl + " but zookeeper says:" + leaderUrl);
}
Thread.sleep(1000);
tries++;
clusterStateLeaderUrl = zkStateReader.getLeaderUrl(collection, shardId,
timeoutms);
leaderUrl = getLeaderProps(collection, cloudDesc.getShardId(), timeoutms)
.getCoreUrl();
}
} catch (Exception e) {
log.error("Error getting leader from zk", e);
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Error getting leader from zk for shard " + shardId, e);
}
return leaderUrl;
}
/**
* Get leader props directly from zk nodes.
*/
public ZkCoreNodeProps getLeaderProps(final String collection,
final String slice, int timeoutms) throws InterruptedException {
return getLeaderProps(collection, slice, timeoutms, false);
}
/**
* Get leader props directly from zk nodes.
*
* @return leader props
*/
public ZkCoreNodeProps getLeaderProps(final String collection,
final String slice, int timeoutms, boolean failImmediatelyOnExpiration) throws InterruptedException {
int iterCount = timeoutms / 1000;
Exception exp = null;
while (iterCount-- > 0) {
try {
byte[] data = zkClient.getData(
ZkStateReader.getShardLeadersPath(collection, slice), null, null,
true);
ZkCoreNodeProps leaderProps = new ZkCoreNodeProps(
ZkNodeProps.load(data));
return leaderProps;
} catch (InterruptedException e) {
throw e;
} catch (SessionExpiredException e) {
if (failImmediatelyOnExpiration) {
throw new RuntimeException("Session has expired - could not get leader props", exp);
}
exp = e;
Thread.sleep(1000);
} catch (Exception e) {
exp = e;
Thread.sleep(1000);
}
if (cc.isShutDown()) {
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "CoreContainer is shutdown");
}
}
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Could not get leader props", exp);
}
private void joinElection(CoreDescriptor cd, boolean afterExpiration) throws InterruptedException, KeeperException, IOException {
String shardId = cd.getCloudDescriptor().getShardId();
Map<String,Object> props = new HashMap<String,Object>();
// we only put a subset of props into the leader node
props.put(ZkStateReader.BASE_URL_PROP, getBaseUrl());
props.put(ZkStateReader.CORE_NAME_PROP, cd.getName());
props.put(ZkStateReader.NODE_NAME_PROP, getNodeName());
final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
ZkNodeProps ourProps = new ZkNodeProps(props);
String collection = cd.getCloudDescriptor()
.getCollectionName();
ElectionContext context = new ShardLeaderElectionContext(leaderElector, shardId,
collection, coreNodeName, ourProps, this, cc);
leaderElector.setup(context);
electionContexts.put(new ContextKey(collection, coreNodeName), context);
leaderElector.joinElection(context, false);
}
/**
* Returns whether or not a recovery was started
*/
private boolean checkRecovery(String coreName, final CoreDescriptor desc,
boolean recoverReloadedCores, final boolean isLeader,
final CloudDescriptor cloudDesc, final String collection,
final String shardZkNodeName, String shardId, ZkNodeProps leaderProps,
SolrCore core, CoreContainer cc) {
if (SKIP_AUTO_RECOVERY) {
log.warn("Skipping recovery according to sys prop solrcloud.skip.autorecovery");
return false;
}
boolean doRecovery = true;
if (!isLeader) {
if (core.isReloaded() && !recoverReloadedCores) {
doRecovery = false;
}
if (doRecovery) {
log.info("Core needs to recover:" + core.getName());
core.getUpdateHandler().getSolrCoreState().doRecovery(cc, core.getCoreDescriptor());
return true;
}
} else {
log.info("I am the leader, no recovery necessary");
}
return false;
}
public String getBaseUrl() {
return baseURL;
}
public void publish(final CoreDescriptor cd, final String state) throws KeeperException, InterruptedException {
publish(cd, state, true);
}
/**
* Publish core state to overseer.
*/
public void publish(final CoreDescriptor cd, final String state, boolean updateLastState) throws KeeperException, InterruptedException {
log.info("publishing core={} state={}", cd.getName(), state);
//System.out.println(Thread.currentThread().getStackTrace()[3]);
Integer numShards = cd.getCloudDescriptor().getNumShards();
if (numShards == null) { //XXX sys prop hack
log.info("numShards not found on descriptor - reading it from system property");
numShards = Integer.getInteger(ZkStateReader.NUM_SHARDS_PROP);
}
assert cd.getCloudDescriptor().getCollectionName() != null && cd.getCloudDescriptor()
.getCollectionName().length() > 0;
String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
//assert cd.getCloudDescriptor().getShardId() != null;
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",
ZkStateReader.STATE_PROP, state,
ZkStateReader.BASE_URL_PROP, getBaseUrl(),
ZkStateReader.CORE_NAME_PROP, cd.getName(),
ZkStateReader.ROLES_PROP, cd.getCloudDescriptor().getRoles(),
ZkStateReader.NODE_NAME_PROP, getNodeName(),
ZkStateReader.SHARD_ID_PROP, cd.getCloudDescriptor().getShardId(),
ZkStateReader.SHARD_RANGE_PROP, cd.getCloudDescriptor().getShardRange(),
ZkStateReader.SHARD_STATE_PROP, cd.getCloudDescriptor().getShardState(),
ZkStateReader.SHARD_PARENT_PROP, cd.getCloudDescriptor().getShardParent(),
ZkStateReader.COLLECTION_PROP, cd.getCloudDescriptor()
.getCollectionName(),
ZkStateReader.NUM_SHARDS_PROP, numShards != null ? numShards.toString()
: null,
ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName != null ? coreNodeName
: null);
if (updateLastState) {
cd.getCloudDescriptor().lastPublished = state;
}
overseerJobQueue.offer(ZkStateReader.toJSON(m));
}
private boolean needsToBeAssignedShardId(final CoreDescriptor desc,
final ClusterState state, final String coreNodeName) {
final CloudDescriptor cloudDesc = desc.getCloudDescriptor();
final String shardId = state.getShardId(getBaseUrl(), desc.getName());
if (shardId != null) {
cloudDesc.setShardId(shardId);
return false;
}
return true;
}
public void unregister(String coreName, CoreDescriptor cd)
throws InterruptedException, KeeperException {
final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
final String collection = cd.getCloudDescriptor().getCollectionName();
assert collection != null;
ElectionContext context = electionContexts.remove(new ContextKey(collection, coreNodeName));
if (context != null) {
context.cancelElection();
}
CloudDescriptor cloudDescriptor = cd.getCloudDescriptor();
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,
Overseer.DELETECORE, ZkStateReader.CORE_NAME_PROP, coreName,
ZkStateReader.NODE_NAME_PROP, getNodeName(),
ZkStateReader.COLLECTION_PROP, cloudDescriptor.getCollectionName(),
ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName);
overseerJobQueue.offer(ZkStateReader.toJSON(m));
}
public void createCollection(String collection) throws KeeperException,
InterruptedException {
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,
"createcollection", ZkStateReader.NODE_NAME_PROP, getNodeName(),
ZkStateReader.COLLECTION_PROP, collection);
overseerJobQueue.offer(ZkStateReader.toJSON(m));
}
public void uploadToZK(File dir, String zkPath) throws IOException, KeeperException, InterruptedException {
uploadToZK(zkClient, dir, zkPath);
}
public void uploadConfigDir(File dir, String configName) throws IOException, KeeperException, InterruptedException {
uploadToZK(zkClient, dir, ZkController.CONFIGS_ZKNODE + "/" + configName);
}
// convenience for testing
void printLayoutToStdOut() throws KeeperException, InterruptedException {
zkClient.printLayoutToStdOut();
}
public void createCollectionZkNode(CloudDescriptor cd) throws KeeperException, InterruptedException {
String collection = cd.getCollectionName();
log.info("Check for collection zkNode:" + collection);
String collectionPath = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection;
try {
if(!zkClient.exists(collectionPath, true)) {
log.info("Creating collection in ZooKeeper:" + collection);
SolrParams params = cd.getParams();
try {
Map<String,Object> collectionProps = new HashMap<String,Object>();
// TODO: if collection.configName isn't set, and there isn't already a conf in zk, just use that?
String defaultConfigName = System.getProperty(COLLECTION_PARAM_PREFIX+CONFIGNAME_PROP, collection);
// params passed in - currently only done via core admin (create core commmand).
if (params != null) {
Iterator<String> iter = params.getParameterNamesIterator();
while (iter.hasNext()) {
String paramName = iter.next();
if (paramName.startsWith(COLLECTION_PARAM_PREFIX)) {
collectionProps.put(paramName.substring(COLLECTION_PARAM_PREFIX.length()), params.get(paramName));
}
}
// if the config name wasn't passed in, use the default
if (!collectionProps.containsKey(CONFIGNAME_PROP)) {
// TODO: getting the configName from the collectionPath should fail since we already know it doesn't exist?
getConfName(collection, collectionPath, collectionProps);
}
} else if(System.getProperty("bootstrap_confdir") != null) {
// if we are bootstrapping a collection, default the config for
// a new collection to the collection we are bootstrapping
log.info("Setting config for collection:" + collection + " to " + defaultConfigName);
Properties sysProps = System.getProperties();
for (String sprop : System.getProperties().stringPropertyNames()) {
if (sprop.startsWith(COLLECTION_PARAM_PREFIX)) {
collectionProps.put(sprop.substring(COLLECTION_PARAM_PREFIX.length()), sysProps.getProperty(sprop));
}
}
// if the config name wasn't passed in, use the default
if (!collectionProps.containsKey(CONFIGNAME_PROP))
collectionProps.put(CONFIGNAME_PROP, defaultConfigName);
} else if (Boolean.getBoolean("bootstrap_conf")) {
// the conf name should should be the collection name of this core
collectionProps.put(CONFIGNAME_PROP, cd.getCollectionName());
} else {
getConfName(collection, collectionPath, collectionProps);
}
collectionProps.remove(ZkStateReader.NUM_SHARDS_PROP); // we don't put numShards in the collections properties
ZkNodeProps zkProps = new ZkNodeProps(collectionProps);
zkClient.makePath(collectionPath, ZkStateReader.toJSON(zkProps), CreateMode.PERSISTENT, null, true);
} catch (KeeperException e) {
// its okay if the node already exists
if (e.code() != KeeperException.Code.NODEEXISTS) {
throw e;
}
}
} else {
log.info("Collection zkNode exists");
}
} catch (KeeperException e) {
// its okay if another beats us creating the node
if (e.code() != KeeperException.Code.NODEEXISTS) {
throw e;
}
}
}
private void getConfName(String collection, String collectionPath,
Map<String,Object> collectionProps) throws KeeperException,
InterruptedException {
// check for configName
log.info("Looking for collection configName");
List<String> configNames = null;
int retry = 1;
int retryLimt = 6;
for (; retry < retryLimt; retry++) {
if (zkClient.exists(collectionPath, true)) {
ZkNodeProps cProps = ZkNodeProps.load(zkClient.getData(collectionPath, null, null, true));
if (cProps.containsKey(CONFIGNAME_PROP)) {
break;
}
}
// if there is only one conf, use that
try {
configNames = zkClient.getChildren(CONFIGS_ZKNODE, null,
true);
} catch (NoNodeException e) {
// just keep trying
}
if (configNames != null && configNames.size() == 1) {
// no config set named, but there is only 1 - use it
log.info("Only one config set found in zk - using it:" + configNames.get(0));
collectionProps.put(CONFIGNAME_PROP, configNames.get(0));
break;
}
if (configNames != null && configNames.contains(collection)) {
log.info("Could not find explicit collection configName, but found config name matching collection name - using that set.");
collectionProps.put(CONFIGNAME_PROP, collection);
break;
}
log.info("Could not find collection configName - pausing for 3 seconds and trying again - try: " + retry);
Thread.sleep(3000);
}
if (retry == retryLimt) {
log.error("Could not find configName for collection " + collection);
throw new ZooKeeperException(
SolrException.ErrorCode.SERVER_ERROR,
"Could not find configName for collection " + collection + " found:" + configNames);
}
}
public ZkStateReader getZkStateReader() {
return zkStateReader;
}
private void doGetShardIdAndNodeNameProcess(CoreDescriptor cd) {
final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
if (coreNodeName != null) {
waitForShardId(cd);
} else {
// if no explicit coreNodeName, we want to match by base url and core name
waitForCoreNodeName(cd);
waitForShardId(cd);
}
}
private void waitForCoreNodeName(CoreDescriptor descriptor) {
int retryCount = 320;
log.info("look for our core node name");
while (retryCount-- > 0) {
Map<String,Slice> slicesMap = zkStateReader.getClusterState()
.getSlicesMap(descriptor.getCloudDescriptor().getCollectionName());
if (slicesMap != null) {
for (Slice slice : slicesMap.values()) {
for (Replica replica : slice.getReplicas()) {
// TODO: for really large clusters, we could 'index' on this
String baseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);
String core = replica.getStr(ZkStateReader.CORE_NAME_PROP);
String msgBaseUrl = getBaseUrl();
String msgCore = descriptor.getName();
if (baseUrl.equals(msgBaseUrl) && core.equals(msgCore)) {
descriptor.getCloudDescriptor()
.setCoreNodeName(replica.getName());
return;
}
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private void waitForShardId(CoreDescriptor cd) {
log.info("waiting to find shard id in clusterstate for " + cd.getName());
int retryCount = 320;
while (retryCount-- > 0) {
final String shardId = zkStateReader.getClusterState().getShardId(getBaseUrl(), cd.getName());
if (shardId != null) {
cd.getCloudDescriptor().setShardId(shardId);
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
throw new SolrException(ErrorCode.SERVER_ERROR,
"Could not get shard id for core: " + cd.getName());
}
public static void uploadToZK(SolrZkClient zkClient, File dir, String zkPath) throws IOException, KeeperException, InterruptedException {
File[] files = dir.listFiles();
if (files == null) {
throw new IllegalArgumentException("Illegal directory: " + dir);
}
for(File file : files) {
if (!file.getName().startsWith(".")) {
if (!file.isDirectory()) {
zkClient.makePath(zkPath + "/" + file.getName(), file, false, true);
} else {
uploadToZK(zkClient, file, zkPath + "/" + file.getName());
}
}
}
}
public static void downloadFromZK(SolrZkClient zkClient, String zkPath,
File dir) throws IOException, KeeperException, InterruptedException {
List<String> files = zkClient.getChildren(zkPath, null, true);
for (String file : files) {
List<String> children = zkClient.getChildren(zkPath + "/" + file, null, true);
if (children.size() == 0) {
byte[] data = zkClient.getData(zkPath + "/" + file, null, null, true);
dir.mkdirs();
log.info("Write file " + new File(dir, file));
FileUtils.writeByteArrayToFile(new File(dir, file), data);
} else {
downloadFromZK(zkClient, zkPath + "/" + file, new File(dir, file));
}
}
}
public String getCoreNodeName(CoreDescriptor descriptor){
String coreNodeName = descriptor.getCloudDescriptor().getCoreNodeName();
if (coreNodeName == null && !genericCoreNodeNames) {
// it's the default
return getNodeName() + "_" + descriptor.getName();
}
return coreNodeName;
}
public static void uploadConfigDir(SolrZkClient zkClient, File dir, String configName) throws IOException, KeeperException, InterruptedException {
uploadToZK(zkClient, dir, ZkController.CONFIGS_ZKNODE + "/" + configName);
}
public static void downloadConfigDir(SolrZkClient zkClient, String configName, File dir) throws IOException, KeeperException, InterruptedException {
downloadFromZK(zkClient, ZkController.CONFIGS_ZKNODE + "/" + configName, dir);
}
public void preRegister(CoreDescriptor cd ) {
String coreNodeName = getCoreNodeName(cd);
// before becoming available, make sure we are not live and active
// this also gets us our assigned shard id if it was not specified
try {
CloudDescriptor cloudDesc = cd.getCloudDescriptor();
if(cd.getCloudDescriptor().getCollectionName() !=null && cloudDesc.getCoreNodeName() != null ) {
//we were already registered
if(zkStateReader.getClusterState().hasCollection(cloudDesc.getCollectionName())){
DocCollection coll = zkStateReader.getClusterState().getCollection(cloudDesc.getCollectionName());
if(!"true".equals(coll.getStr("autoCreated"))){
Slice slice = coll.getSlice(cloudDesc.getShardId());
if(slice != null){
if(slice.getReplica(cloudDesc.getCoreNodeName()) == null) {
log.info("core_removed This core is removed from ZK");
throw new SolrException(ErrorCode.NOT_FOUND,cloudDesc.getCoreNodeName() +" is removed");
}
}
}
}
}
// make sure the node name is set on the descriptor
if (cloudDesc.getCoreNodeName() == null) {
cloudDesc.setCoreNodeName(coreNodeName);
}
publish(cd, ZkStateReader.DOWN, false);
} catch (KeeperException e) {
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
}
if (cd.getCloudDescriptor().getShardId() == null && needsToBeAssignedShardId(cd, zkStateReader.getClusterState(), coreNodeName)) {
doGetShardIdAndNodeNameProcess(cd);
} else {
// still wait till we see us in local state
doGetShardIdAndNodeNameProcess(cd);
}
}
private ZkCoreNodeProps waitForLeaderToSeeDownState(
CoreDescriptor descriptor, final String coreZkNodeName) {
CloudDescriptor cloudDesc = descriptor.getCloudDescriptor();
String collection = cloudDesc.getCollectionName();
String shard = cloudDesc.getShardId();
ZkCoreNodeProps leaderProps = null;
int retries = 6;
for (int i = 0; i < retries; i++) {
try {
if (isClosed) {
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,
"We have been closed");
}
// go straight to zk, not the cloud state - we must have current info
leaderProps = getLeaderProps(collection, shard, 30000);
break;
} catch (Exception e) {
SolrException.log(log, "There was a problem finding the leader in zk", e);
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
if (i == retries - 1) {
throw new SolrException(ErrorCode.SERVER_ERROR, "There was a problem finding the leader in zk");
}
}
}
String leaderBaseUrl = leaderProps.getBaseUrl();
String leaderCoreName = leaderProps.getCoreName();
String ourUrl = ZkCoreNodeProps.getCoreUrl(getBaseUrl(),
descriptor.getName());
boolean isLeader = leaderProps.getCoreUrl().equals(ourUrl);
if (!isLeader && !SKIP_AUTO_RECOVERY) {
HttpSolrServer server = null;
server = new HttpSolrServer(leaderBaseUrl);
try {
server.setConnectionTimeout(15000);
server.setSoTimeout(120000);
WaitForState prepCmd = new WaitForState();
prepCmd.setCoreName(leaderCoreName);
prepCmd.setNodeName(getNodeName());
prepCmd.setCoreNodeName(coreZkNodeName);
prepCmd.setState(ZkStateReader.DOWN);
// let's retry a couple times - perhaps the leader just went down,
// or perhaps he is just not quite ready for us yet
retries = 6;
for (int i = 0; i < retries; i++) {
if (isClosed) {
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,
"We have been closed");
}
try {
server.request(prepCmd);
break;
} catch (Exception e) {
SolrException.log(log,
"There was a problem making a request to the leader", e);
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
if (i == retries - 1) {
throw new SolrException(ErrorCode.SERVER_ERROR,
"There was a problem making a request to the leader");
}
}
}
} finally {
server.shutdown();
}
}
return leaderProps;
}
public static void linkConfSet(SolrZkClient zkClient, String collection, String confSetName) throws KeeperException, InterruptedException {
String path = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection;
if (log.isInfoEnabled()) {
log.info("Load collection config from:" + path);
}
byte[] data;
try {
data = zkClient.getData(path, null, null, true);
} catch (NoNodeException e) {
// if there is no node, we will try and create it
// first try to make in case we are pre configuring
ZkNodeProps props = new ZkNodeProps(CONFIGNAME_PROP, confSetName);
try {
zkClient.makePath(path, ZkStateReader.toJSON(props),
CreateMode.PERSISTENT, null, true);
} catch (KeeperException e2) {
// its okay if the node already exists
if (e2.code() != KeeperException.Code.NODEEXISTS) {
throw e;
}
// if we fail creating, setdata
// TODO: we should consider using version
zkClient.setData(path, ZkStateReader.toJSON(props), true);
}
return;
}
// we found existing data, let's update it
ZkNodeProps props = null;
if(data != null) {
props = ZkNodeProps.load(data);
Map<String,Object> newProps = new HashMap<String,Object>();
newProps.putAll(props.getProperties());
newProps.put(CONFIGNAME_PROP, confSetName);
props = new ZkNodeProps(newProps);
} else {
props = new ZkNodeProps(CONFIGNAME_PROP, confSetName);
}
// TODO: we should consider using version
zkClient.setData(path, ZkStateReader.toJSON(props), true);
}
/**
* If in SolrCloud mode, upload config sets for each SolrCore in solr.xml.
*/
public static void bootstrapConf(SolrZkClient zkClient, CoreContainer cc, String solrHome) throws IOException,
KeeperException, InterruptedException {
//List<String> allCoreNames = cfg.getAllCoreNames();
List<CoreDescriptor> cds = cc.getCoresLocator().discover(cc);
log.info("bootstrapping config for " + cds.size() + " cores into ZooKeeper using solr.xml from " + solrHome);
for (CoreDescriptor cd : cds) {
String coreName = cd.getName();
String confName = cd.getCollectionName();
if (StringUtils.isEmpty(confName))
confName = coreName;
String instanceDir = cd.getInstanceDir();
File udir = new File(instanceDir, "conf");
log.info("Uploading directory " + udir + " with name " + confName + " for SolrCore " + coreName);
ZkController.uploadConfigDir(zkClient, udir, confName);
}
}
public DistributedQueue getOverseerJobQueue() {
return overseerJobQueue;
}
public DistributedQueue getOverseerCollectionQueue() {
return overseerCollectionQueue;
}
public int getClientTimeout() {
return clientTimeout;
}
public Overseer getOverseer() {
return overseer;
}
public LeaderElector getOverseerElector() {
return overseerElector;
}
/**
* Returns the nodeName that should be used based on the specified properties.
*
* @param hostName - must not be null or the empty string
* @param hostPort - must consist only of digits, must not be null or the empty string
* @param hostContext - should not begin or end with a slash (leading/trailin slashes will be ignored), must not be null, may be the empty string to denote the root context
* @lucene.experimental
* @see SolrZkClient#getBaseUrlForNodeName
*/
static String generateNodeName(final String hostName,
final String hostPort,
final String hostContext) {
try {
return hostName + ':' + hostPort + '_' +
URLEncoder.encode(trimLeadingAndTrailingSlashes(hostContext), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("JVM Does not seem to support UTF-8", e);
}
}
/**
* Utility method for trimming and leading and/or trailing slashes from
* it's input. May return the empty string. May return null if and only
* if the input is null.
*/
public static String trimLeadingAndTrailingSlashes(final String in) {
if (null == in) return in;
String out = in;
if (out.startsWith("/")) {
out = out.substring(1);
}
if (out.endsWith("/")) {
out = out.substring(0,out.length()-1);
}
return out;
}
}
|
solr/core/src/java/org/apache/solr/cloud/ZkController.java
|
package org.apache.solr.cloud;
/*
* 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.
*/
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.cloud.BeforeReconnect;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DefaultConnectionStrategy;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.OnReconnect;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.SolrZkClient;
import org.apache.solr.common.cloud.ZkCmdExecutor;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.cloud.ZooKeeperException;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.component.ShardHandler;
import org.apache.solr.update.UpdateLog;
import org.apache.solr.update.UpdateShardHandler;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.SessionExpiredException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Handle ZooKeeper interactions.
*
* notes: loads everything on init, creates what's not there - further updates
* are prompted with Watches.
*
* TODO: exceptions during shutdown on attempts to update cloud state
*
*/
public final class ZkController {
private static Logger log = LoggerFactory.getLogger(ZkController.class);
static final String NEWL = System.getProperty("line.separator");
private final static Pattern URL_POST = Pattern.compile("https?://(.*)");
private final static Pattern URL_PREFIX = Pattern.compile("(https?://).*");
private final boolean SKIP_AUTO_RECOVERY = Boolean.getBoolean("solrcloud.skip.autorecovery");
private final DistributedQueue overseerJobQueue;
private final DistributedQueue overseerCollectionQueue;
public static final String CONFIGS_ZKNODE = "/configs";
public final static String COLLECTION_PARAM_PREFIX="collection.";
public final static String CONFIGNAME_PROP="configName";
static class ContextKey {
private String collection;
private String coreNodeName;
public ContextKey(String collection, String coreNodeName) {
this.collection = collection;
this.coreNodeName = coreNodeName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((collection == null) ? 0 : collection.hashCode());
result = prime * result
+ ((coreNodeName == null) ? 0 : coreNodeName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ContextKey other = (ContextKey) obj;
if (collection == null) {
if (other.collection != null) return false;
} else if (!collection.equals(other.collection)) return false;
if (coreNodeName == null) {
if (other.coreNodeName != null) return false;
} else if (!coreNodeName.equals(other.coreNodeName)) return false;
return true;
}
}
private final Map<ContextKey, ElectionContext> electionContexts = Collections.synchronizedMap(new HashMap<ContextKey, ElectionContext>());
private SolrZkClient zkClient;
private ZkCmdExecutor cmdExecutor;
private ZkStateReader zkStateReader;
private LeaderElector leaderElector;
private String zkServerAddress; // example: 127.0.0.1:54062/solr
private final String localHostPort; // example: 54065
private final String localHostContext; // example: solr
private final String localHost; // example: http://127.0.0.1
private final String hostName; // example: 127.0.0.1
private final String nodeName; // example: 127.0.0.1:54065_solr
private final String baseURL; // example: http://127.0.0.1:54065/solr
private LeaderElector overseerElector;
// for now, this can be null in tests, in which case recovery will be inactive, and other features
// may accept defaults or use mocks rather than pulling things from a CoreContainer
private CoreContainer cc;
protected volatile Overseer overseer;
private int leaderVoteWait;
private boolean genericCoreNodeNames;
private int clientTimeout;
private volatile boolean isClosed;
public ZkController(final CoreContainer cc, String zkServerAddress, int zkClientTimeout, int zkClientConnectTimeout, String localHost, String locaHostPort,
String localHostContext, int leaderVoteWait, boolean genericCoreNodeNames, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException,
TimeoutException, IOException {
if (cc == null) throw new IllegalArgumentException("CoreContainer cannot be null.");
this.cc = cc;
this.genericCoreNodeNames = genericCoreNodeNames;
// be forgiving and strip this off leading/trailing slashes
// this allows us to support users specifying hostContext="/" in
// solr.xml to indicate the root context, instead of hostContext=""
// which means the default of "solr"
localHostContext = trimLeadingAndTrailingSlashes(localHostContext);
this.zkServerAddress = zkServerAddress;
this.localHostPort = locaHostPort;
this.localHostContext = localHostContext;
this.localHost = getHostAddress(localHost);
this.baseURL = this.localHost + ":" + this.localHostPort +
(this.localHostContext.isEmpty() ? "" : ("/" + this.localHostContext));
this.hostName = getHostNameFromAddress(this.localHost);
this.nodeName = generateNodeName(this.hostName,
this.localHostPort,
this.localHostContext);
this.leaderVoteWait = leaderVoteWait;
this.clientTimeout = zkClientTimeout;
zkClient = new SolrZkClient(zkServerAddress, zkClientTimeout,
zkClientConnectTimeout, new DefaultConnectionStrategy(),
// on reconnect, reload cloud info
new OnReconnect() {
@Override
public void command() {
try {
markAllAsNotLeader(registerOnReconnect);
// this is troublesome - we dont want to kill anything the old
// leader accepted
// though I guess sync will likely get those updates back? But
// only if
// he is involved in the sync, and he certainly may not be
// ExecutorUtil.shutdownAndAwaitTermination(cc.getCmdDistribExecutor());
// we need to create all of our lost watches
// seems we dont need to do this again...
// Overseer.createClientNodes(zkClient, getNodeName());
ShardHandler shardHandler;
String adminPath;
shardHandler = cc.getShardHandlerFactory().getShardHandler();
adminPath = cc.getAdminPath();
cc.cancelCoreRecoveries();
registerAllCoresAsDown(registerOnReconnect, false);
ElectionContext context = new OverseerElectionContext(zkClient,
overseer, getNodeName());
overseerElector.joinElection(context, true);
zkStateReader.createClusterStateWatchersAndUpdate();
// we have to register as live first to pick up docs in the buffer
createEphemeralLiveNode();
List<CoreDescriptor> descriptors = registerOnReconnect
.getCurrentDescriptors();
// re register all descriptors
if (descriptors != null) {
for (CoreDescriptor descriptor : descriptors) {
// TODO: we need to think carefully about what happens when it
// was
// a leader that was expired - as well as what to do about
// leaders/overseers
// with connection loss
try {
register(descriptor.getName(), descriptor, true, true);
} catch (Throwable t) {
SolrException.log(log, "Error registering SolrCore", t);
}
}
}
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
throw new ZooKeeperException(
SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (Exception e) {
SolrException.log(log, "", e);
throw new ZooKeeperException(
SolrException.ErrorCode.SERVER_ERROR, "", e);
}
}
}, new BeforeReconnect() {
@Override
public void command() {
try {
ZkController.this.overseer.close();
} catch (Exception e) {
log.error("Error trying to stop any Overseer threads", e);
}
}
});
this.overseerJobQueue = Overseer.getInQueue(zkClient);
this.overseerCollectionQueue = Overseer.getCollectionQueue(zkClient);
cmdExecutor = new ZkCmdExecutor(zkClientTimeout);
leaderElector = new LeaderElector(zkClient);
zkStateReader = new ZkStateReader(zkClient);
init(registerOnReconnect);
}
public int getLeaderVoteWait() {
return leaderVoteWait;
}
private void registerAllCoresAsDown(
final CurrentCoreDescriptorProvider registerOnReconnect, boolean updateLastPublished) {
List<CoreDescriptor> descriptors = registerOnReconnect
.getCurrentDescriptors();
if (isClosed) return;
if (descriptors != null) {
// before registering as live, make sure everyone is in a
// down state
for (CoreDescriptor descriptor : descriptors) {
final String coreZkNodeName = descriptor.getCloudDescriptor().getCoreNodeName();
try {
descriptor.getCloudDescriptor().setLeader(false);
publish(descriptor, ZkStateReader.DOWN, updateLastPublished);
} catch (Exception e) {
if (isClosed) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
try {
publish(descriptor, ZkStateReader.DOWN);
} catch (Exception e2) {
SolrException.log(log, "", e2);
continue;
}
}
// if it looks like we are going to be the leader, we don't
// want to wait for the following stuff
CloudDescriptor cloudDesc = descriptor.getCloudDescriptor();
String collection = cloudDesc.getCollectionName();
String slice = cloudDesc.getShardId();
try {
int children = zkStateReader
.getZkClient()
.getChildren(
ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection
+ "/leader_elect/" + slice + "/election", null, true).size();
if (children == 0) {
return;
}
} catch (NoNodeException e) {
return;
} catch (InterruptedException e2) {
Thread.currentThread().interrupt();
} catch (KeeperException e) {
log.warn("", e);
Thread.currentThread().interrupt();
}
try {
waitForLeaderToSeeDownState(descriptor, coreZkNodeName);
} catch (Exception e) {
SolrException.log(log, "", e);
if (isClosed) {
return;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
}
}
}
private void markAllAsNotLeader(
final CurrentCoreDescriptorProvider registerOnReconnect) {
List<CoreDescriptor> descriptors = registerOnReconnect
.getCurrentDescriptors();
if (descriptors != null) {
for (CoreDescriptor descriptor : descriptors) {
descriptor.getCloudDescriptor().setLeader(false);
}
}
}
/**
* Closes the underlying ZooKeeper client.
*/
public void close() {
this.isClosed = true;
for (ElectionContext context : electionContexts.values()) {
try {
context.close();
} catch (Throwable t) {
log.error("Error closing overseer", t);
}
}
try {
overseer.close();
} catch(Throwable t) {
log.error("Error closing overseer", t);
}
try {
zkStateReader.close();
} catch(Throwable t) {
log.error("Error closing zkStateReader", t);
}
try {
zkClient.close();;
} catch(Throwable t) {
log.error("Error closing zkClient", t);
}
}
/**
* Returns true if config file exists
*/
public boolean configFileExists(String collection, String fileName)
throws KeeperException, InterruptedException {
Stat stat = zkClient.exists(CONFIGS_ZKNODE + "/" + collection + "/" + fileName, null, true);
return stat != null;
}
/**
* @return information about the cluster from ZooKeeper
*/
public ClusterState getClusterState() {
return zkStateReader.getClusterState();
}
/**
* Returns config file data (in bytes)
*/
public byte[] getConfigFileData(String zkConfigName, String fileName)
throws KeeperException, InterruptedException {
String zkPath = CONFIGS_ZKNODE + "/" + zkConfigName + "/" + fileName;
byte[] bytes = zkClient.getData(zkPath, null, null, true);
if (bytes == null) {
log.error("Config file contains no data:" + zkPath);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
"Config file contains no data:" + zkPath);
}
return bytes;
}
// normalize host to url_prefix://host
// input can be null, host, or url_prefix://host
private String getHostAddress(String host) throws IOException {
if (host == null || host.length() == 0) {
String hostaddress;
try {
hostaddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
hostaddress = "127.0.0.1"; // cannot resolve system hostname, fall through
}
// Re-get the IP again for "127.0.0.1", the other case we trust the hosts
// file is right.
if ("127.0.0.1".equals(hostaddress)) {
Enumeration<NetworkInterface> netInterfaces = null;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress ip = ips.nextElement();
if (ip.isSiteLocalAddress()) {
hostaddress = ip.getHostAddress();
}
}
}
} catch (Throwable e) {
SolrException.log(log,
"Error while looking for a better host name than 127.0.0.1", e);
}
}
host = "http://" + hostaddress;
} else {
Matcher m = URL_PREFIX.matcher(host);
if (m.matches()) {
String prefix = m.group(1);
host = prefix + host;
} else {
host = "http://" + host;
}
}
return host;
}
// extract host from url_prefix://host
private String getHostNameFromAddress(String addr) {
Matcher m = URL_POST.matcher(addr);
if (m.matches()) {
return m.group(1);
} else {
log.error("Unrecognized host:" + addr);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
"Unrecognized host:" + addr);
}
}
public String getHostName() {
return hostName;
}
public String getHostPort() {
return localHostPort;
}
public SolrZkClient getZkClient() {
return zkClient;
}
/**
* @return zookeeper server address
*/
public String getZkServerAddress() {
return zkServerAddress;
}
private void init(CurrentCoreDescriptorProvider registerOnReconnect) {
try {
boolean createdWatchesAndUpdated = false;
if (zkClient.exists(ZkStateReader.LIVE_NODES_ZKNODE, true)) {
zkStateReader.createClusterStateWatchersAndUpdate();
createdWatchesAndUpdated = true;
publishAndWaitForDownStates();
}
// makes nodes zkNode
cmdExecutor.ensureExists(ZkStateReader.LIVE_NODES_ZKNODE, zkClient);
createEphemeralLiveNode();
cmdExecutor.ensureExists(ZkStateReader.COLLECTIONS_ZKNODE, zkClient);
ShardHandler shardHandler;
String adminPath;
shardHandler = cc.getShardHandlerFactory().getShardHandler();
adminPath = cc.getAdminPath();
overseerElector = new LeaderElector(zkClient);
this.overseer = new Overseer(shardHandler, adminPath, zkStateReader);
ElectionContext context = new OverseerElectionContext(zkClient, overseer, getNodeName());
overseerElector.setup(context);
overseerElector.joinElection(context, false);
if (!createdWatchesAndUpdated) {
zkStateReader.createClusterStateWatchersAndUpdate();
}
} catch (IOException e) {
log.error("", e);
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Can't create ZooKeeperController", e);
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
"", e);
} catch (KeeperException e) {
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR,
"", e);
}
}
public void publishAndWaitForDownStates() throws KeeperException,
InterruptedException {
ClusterState clusterState = zkStateReader.getClusterState();
Set<String> collections = clusterState.getCollections();
List<String> updatedNodes = new ArrayList<String>();
for (String collectionName : collections) {
DocCollection collection = clusterState.getCollection(collectionName);
Collection<Slice> slices = collection.getSlices();
for (Slice slice : slices) {
Collection<Replica> replicas = slice.getReplicas();
for (Replica replica : replicas) {
if (replica.getNodeName().equals(getNodeName())
&& !(replica.getStr(ZkStateReader.STATE_PROP)
.equals(ZkStateReader.DOWN))) {
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",
ZkStateReader.STATE_PROP, ZkStateReader.DOWN,
ZkStateReader.BASE_URL_PROP, getBaseUrl(),
ZkStateReader.CORE_NAME_PROP,
replica.getStr(ZkStateReader.CORE_NAME_PROP),
ZkStateReader.ROLES_PROP,
replica.getStr(ZkStateReader.ROLES_PROP),
ZkStateReader.NODE_NAME_PROP, getNodeName(),
ZkStateReader.SHARD_ID_PROP,
replica.getStr(ZkStateReader.SHARD_ID_PROP),
ZkStateReader.COLLECTION_PROP, collectionName,
ZkStateReader.CORE_NODE_NAME_PROP, replica.getName());
updatedNodes.add(replica.getStr(ZkStateReader.CORE_NAME_PROP));
overseerJobQueue.offer(ZkStateReader.toJSON(m));
}
}
}
}
// now wait till the updates are in our state
long now = System.currentTimeMillis();
long timeout = now + 1000 * 30;
boolean foundStates = false;
while (System.currentTimeMillis() < timeout) {
clusterState = zkStateReader.getClusterState();
collections = clusterState.getCollections();
for (String collectionName : collections) {
DocCollection collection = clusterState.getCollection(collectionName);
Collection<Slice> slices = collection.getSlices();
for (Slice slice : slices) {
Collection<Replica> replicas = slice.getReplicas();
for (Replica replica : replicas) {
if (replica.getStr(ZkStateReader.STATE_PROP).equals(
ZkStateReader.DOWN)) {
updatedNodes.remove(replica.getStr(ZkStateReader.CORE_NAME_PROP));
}
}
}
}
if (updatedNodes.size() == 0) {
foundStates = true;
Thread.sleep(1000);
break;
}
Thread.sleep(1000);
}
if (!foundStates) {
log.warn("Timed out waiting to see all nodes published as DOWN in our cluster state.");
}
}
/**
* Validates if the chroot exists in zk (or if it is successfully created).
* Optionally, if create is set to true this method will create the path in
* case it doesn't exist
*
* @return true if the path exists or is created false if the path doesn't
* exist and 'create' = false
*/
public static boolean checkChrootPath(String zkHost, boolean create)
throws KeeperException, InterruptedException {
if (!containsChroot(zkHost)) {
return true;
}
log.info("zkHost includes chroot");
String chrootPath = zkHost.substring(zkHost.indexOf("/"), zkHost.length());
SolrZkClient tmpClient = new SolrZkClient(zkHost.substring(0,
zkHost.indexOf("/")), 60 * 1000);
boolean exists = tmpClient.exists(chrootPath, true);
if (!exists && create) {
tmpClient.makePath(chrootPath, false, true);
exists = true;
}
tmpClient.close();
return exists;
}
/**
* Validates if zkHost contains a chroot. See http://zookeeper.apache.org/doc/r3.2.2/zookeeperProgrammers.html#ch_zkSessions
*/
private static boolean containsChroot(String zkHost) {
return zkHost.contains("/");
}
public boolean isConnected() {
return zkClient.isConnected();
}
private void createEphemeralLiveNode() throws KeeperException,
InterruptedException {
String nodeName = getNodeName();
String nodePath = ZkStateReader.LIVE_NODES_ZKNODE + "/" + nodeName;
log.info("Register node as live in ZooKeeper:" + nodePath);
try {
boolean nodeDeleted = true;
try {
// we attempt a delete in the case of a quick server bounce -
// if there was not a graceful shutdown, the node may exist
// until expiration timeout - so a node won't be created here because
// it exists, but eventually the node will be removed. So delete
// in case it exists and create a new node.
zkClient.delete(nodePath, -1, true);
} catch (KeeperException.NoNodeException e) {
// fine if there is nothing to delete
// TODO: annoying that ZK logs a warning on us
nodeDeleted = false;
}
if (nodeDeleted) {
log
.info("Found a previous node that still exists while trying to register a new live node "
+ nodePath + " - removing existing node to create another.");
}
zkClient.makePath(nodePath, CreateMode.EPHEMERAL, true);
} catch (KeeperException e) {
// its okay if the node already exists
if (e.code() != KeeperException.Code.NODEEXISTS) {
throw e;
}
}
}
public String getNodeName() {
return nodeName;
}
/**
* Returns true if the path exists
*/
public boolean pathExists(String path) throws KeeperException,
InterruptedException {
return zkClient.exists(path, true);
}
/**
* Register shard with ZooKeeper.
*
* @return the shardId for the SolrCore
*/
public String register(String coreName, final CoreDescriptor desc) throws Exception {
return register(coreName, desc, false, false);
}
/**
* Register shard with ZooKeeper.
*
* @return the shardId for the SolrCore
*/
public String register(String coreName, final CoreDescriptor desc, boolean recoverReloadedCores, boolean afterExpiration) throws Exception {
final String baseUrl = getBaseUrl();
final CloudDescriptor cloudDesc = desc.getCloudDescriptor();
final String collection = cloudDesc.getCollectionName();
final String coreZkNodeName = desc.getCloudDescriptor().getCoreNodeName();
assert coreZkNodeName != null : "we should have a coreNodeName by now";
String shardId = cloudDesc.getShardId();
Map<String,Object> props = new HashMap<String,Object>();
// we only put a subset of props into the leader node
props.put(ZkStateReader.BASE_URL_PROP, baseUrl);
props.put(ZkStateReader.CORE_NAME_PROP, coreName);
props.put(ZkStateReader.NODE_NAME_PROP, getNodeName());
if (log.isInfoEnabled()) {
log.info("Register replica - core:" + coreName + " address:"
+ baseUrl + " collection:" + cloudDesc.getCollectionName() + " shard:" + shardId);
}
ZkNodeProps leaderProps = new ZkNodeProps(props);
try {
joinElection(desc, afterExpiration);
} catch (InterruptedException e) {
// Restore the interrupted status
Thread.currentThread().interrupt();
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (KeeperException e) {
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (IOException e) {
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
}
// in this case, we want to wait for the leader as long as the leader might
// wait for a vote, at least - but also long enough that a large cluster has
// time to get its act together
String leaderUrl = getLeader(cloudDesc, leaderVoteWait + 600000);
String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName);
log.info("We are " + ourUrl + " and leader is " + leaderUrl);
boolean isLeader = leaderUrl.equals(ourUrl);
SolrCore core = null;
try {
core = cc.getCore(desc.getName());
// recover from local transaction log and wait for it to complete before
// going active
// TODO: should this be moved to another thread? To recoveryStrat?
// TODO: should this actually be done earlier, before (or as part of)
// leader election perhaps?
// TODO: if I'm the leader, ensure that a replica that is trying to recover waits until I'm
// active (or don't make me the
// leader until my local replay is done.
UpdateLog ulog = core.getUpdateHandler().getUpdateLog();
if (!core.isReloaded() && ulog != null) {
// disable recovery in case shard is in construction state (for shard splits)
Slice slice = getClusterState().getSlice(collection, shardId);
if (!Slice.CONSTRUCTION.equals(slice.getState()) || !isLeader) {
Future<UpdateLog.RecoveryInfo> recoveryFuture = core.getUpdateHandler()
.getUpdateLog().recoverFromLog();
if (recoveryFuture != null) {
recoveryFuture.get(); // NOTE: this could potentially block for
// minutes or more!
// TODO: public as recovering in the mean time?
// TODO: in the future we could do peersync in parallel with recoverFromLog
} else {
log.info("No LogReplay needed for core=" + core.getName() + " baseURL=" + baseUrl);
}
}
boolean didRecovery = checkRecovery(coreName, desc, recoverReloadedCores, isLeader, cloudDesc,
collection, coreZkNodeName, shardId, leaderProps, core, cc);
if (!didRecovery) {
publish(desc, ZkStateReader.ACTIVE);
}
}
} finally {
if (core != null) {
core.close();
}
}
// make sure we have an update cluster state right away
zkStateReader.updateClusterState(true);
return shardId;
}
// timeoutms is the timeout for the first call to get the leader - there is then
// a longer wait to make sure that leader matches our local state
private String getLeader(final CloudDescriptor cloudDesc, int timeoutms) {
String collection = cloudDesc.getCollectionName();
String shardId = cloudDesc.getShardId();
// rather than look in the cluster state file, we go straight to the zknodes
// here, because on cluster restart there could be stale leader info in the
// cluster state node that won't be updated for a moment
String leaderUrl;
try {
leaderUrl = getLeaderProps(collection, cloudDesc.getShardId(), timeoutms)
.getCoreUrl();
// now wait until our currently cloud state contains the latest leader
String clusterStateLeaderUrl = zkStateReader.getLeaderUrl(collection,
shardId, timeoutms * 2); // since we found it in zk, we are willing to
// wait a while to find it in state
int tries = 0;
while (!leaderUrl.equals(clusterStateLeaderUrl)) {
if (tries == 60) {
throw new SolrException(ErrorCode.SERVER_ERROR,
"There is conflicting information about the leader of shard: "
+ cloudDesc.getShardId() + " our state says:"
+ clusterStateLeaderUrl + " but zookeeper says:" + leaderUrl);
}
Thread.sleep(1000);
tries++;
clusterStateLeaderUrl = zkStateReader.getLeaderUrl(collection, shardId,
timeoutms);
leaderUrl = getLeaderProps(collection, cloudDesc.getShardId(), timeoutms)
.getCoreUrl();
}
} catch (Exception e) {
log.error("Error getting leader from zk", e);
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Error getting leader from zk for shard " + shardId, e);
}
return leaderUrl;
}
/**
* Get leader props directly from zk nodes.
*/
public ZkCoreNodeProps getLeaderProps(final String collection,
final String slice, int timeoutms) throws InterruptedException {
return getLeaderProps(collection, slice, timeoutms, false);
}
/**
* Get leader props directly from zk nodes.
*
* @return leader props
*/
public ZkCoreNodeProps getLeaderProps(final String collection,
final String slice, int timeoutms, boolean failImmediatelyOnExpiration) throws InterruptedException {
int iterCount = timeoutms / 1000;
Exception exp = null;
while (iterCount-- > 0) {
try {
byte[] data = zkClient.getData(
ZkStateReader.getShardLeadersPath(collection, slice), null, null,
true);
ZkCoreNodeProps leaderProps = new ZkCoreNodeProps(
ZkNodeProps.load(data));
return leaderProps;
} catch (InterruptedException e) {
throw e;
} catch (SessionExpiredException e) {
if (failImmediatelyOnExpiration) {
throw new RuntimeException("Session has expired - could not get leader props", exp);
}
exp = e;
Thread.sleep(1000);
} catch (Exception e) {
exp = e;
Thread.sleep(1000);
}
if (cc.isShutDown()) {
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "CoreContainer is shutdown");
}
}
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Could not get leader props", exp);
}
private void joinElection(CoreDescriptor cd, boolean afterExpiration) throws InterruptedException, KeeperException, IOException {
String shardId = cd.getCloudDescriptor().getShardId();
Map<String,Object> props = new HashMap<String,Object>();
// we only put a subset of props into the leader node
props.put(ZkStateReader.BASE_URL_PROP, getBaseUrl());
props.put(ZkStateReader.CORE_NAME_PROP, cd.getName());
props.put(ZkStateReader.NODE_NAME_PROP, getNodeName());
final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
ZkNodeProps ourProps = new ZkNodeProps(props);
String collection = cd.getCloudDescriptor()
.getCollectionName();
ElectionContext context = new ShardLeaderElectionContext(leaderElector, shardId,
collection, coreNodeName, ourProps, this, cc);
leaderElector.setup(context);
electionContexts.put(new ContextKey(collection, coreNodeName), context);
leaderElector.joinElection(context, false);
}
/**
* Returns whether or not a recovery was started
*/
private boolean checkRecovery(String coreName, final CoreDescriptor desc,
boolean recoverReloadedCores, final boolean isLeader,
final CloudDescriptor cloudDesc, final String collection,
final String shardZkNodeName, String shardId, ZkNodeProps leaderProps,
SolrCore core, CoreContainer cc) {
if (SKIP_AUTO_RECOVERY) {
log.warn("Skipping recovery according to sys prop solrcloud.skip.autorecovery");
return false;
}
boolean doRecovery = true;
if (!isLeader) {
if (core.isReloaded() && !recoverReloadedCores) {
doRecovery = false;
}
if (doRecovery) {
log.info("Core needs to recover:" + core.getName());
core.getUpdateHandler().getSolrCoreState().doRecovery(cc, core.getCoreDescriptor());
return true;
}
} else {
log.info("I am the leader, no recovery necessary");
}
return false;
}
public String getBaseUrl() {
return baseURL;
}
public void publish(final CoreDescriptor cd, final String state) throws KeeperException, InterruptedException {
publish(cd, state, true);
}
/**
* Publish core state to overseer.
*/
public void publish(final CoreDescriptor cd, final String state, boolean updateLastState) throws KeeperException, InterruptedException {
log.info("publishing core={} state={}", cd.getName(), state);
//System.out.println(Thread.currentThread().getStackTrace()[3]);
Integer numShards = cd.getCloudDescriptor().getNumShards();
if (numShards == null) { //XXX sys prop hack
log.info("numShards not found on descriptor - reading it from system property");
numShards = Integer.getInteger(ZkStateReader.NUM_SHARDS_PROP);
}
assert cd.getCloudDescriptor().getCollectionName() != null && cd.getCloudDescriptor()
.getCollectionName().length() > 0;
String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
//assert cd.getCloudDescriptor().getShardId() != null;
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",
ZkStateReader.STATE_PROP, state,
ZkStateReader.BASE_URL_PROP, getBaseUrl(),
ZkStateReader.CORE_NAME_PROP, cd.getName(),
ZkStateReader.ROLES_PROP, cd.getCloudDescriptor().getRoles(),
ZkStateReader.NODE_NAME_PROP, getNodeName(),
ZkStateReader.SHARD_ID_PROP, cd.getCloudDescriptor().getShardId(),
ZkStateReader.SHARD_RANGE_PROP, cd.getCloudDescriptor().getShardRange(),
ZkStateReader.SHARD_STATE_PROP, cd.getCloudDescriptor().getShardState(),
ZkStateReader.SHARD_PARENT_PROP, cd.getCloudDescriptor().getShardParent(),
ZkStateReader.COLLECTION_PROP, cd.getCloudDescriptor()
.getCollectionName(),
ZkStateReader.NUM_SHARDS_PROP, numShards != null ? numShards.toString()
: null,
ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName != null ? coreNodeName
: null);
if (updateLastState) {
cd.getCloudDescriptor().lastPublished = state;
}
overseerJobQueue.offer(ZkStateReader.toJSON(m));
}
private boolean needsToBeAssignedShardId(final CoreDescriptor desc,
final ClusterState state, final String coreNodeName) {
final CloudDescriptor cloudDesc = desc.getCloudDescriptor();
final String shardId = state.getShardId(getBaseUrl(), desc.getName());
if (shardId != null) {
cloudDesc.setShardId(shardId);
return false;
}
return true;
}
public void unregister(String coreName, CoreDescriptor cd)
throws InterruptedException, KeeperException {
final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
final String collection = cd.getCloudDescriptor().getCollectionName();
assert collection != null;
ElectionContext context = electionContexts.remove(new ContextKey(collection, coreNodeName));
if (context != null) {
context.cancelElection();
}
CloudDescriptor cloudDescriptor = cd.getCloudDescriptor();
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,
Overseer.DELETECORE, ZkStateReader.CORE_NAME_PROP, coreName,
ZkStateReader.NODE_NAME_PROP, getNodeName(),
ZkStateReader.COLLECTION_PROP, cloudDescriptor.getCollectionName(),
ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName);
overseerJobQueue.offer(ZkStateReader.toJSON(m));
}
public void createCollection(String collection) throws KeeperException,
InterruptedException {
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,
"createcollection", ZkStateReader.NODE_NAME_PROP, getNodeName(),
ZkStateReader.COLLECTION_PROP, collection);
overseerJobQueue.offer(ZkStateReader.toJSON(m));
}
public void uploadToZK(File dir, String zkPath) throws IOException, KeeperException, InterruptedException {
uploadToZK(zkClient, dir, zkPath);
}
public void uploadConfigDir(File dir, String configName) throws IOException, KeeperException, InterruptedException {
uploadToZK(zkClient, dir, ZkController.CONFIGS_ZKNODE + "/" + configName);
}
// convenience for testing
void printLayoutToStdOut() throws KeeperException, InterruptedException {
zkClient.printLayoutToStdOut();
}
public void createCollectionZkNode(CloudDescriptor cd) throws KeeperException, InterruptedException {
String collection = cd.getCollectionName();
log.info("Check for collection zkNode:" + collection);
String collectionPath = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection;
try {
if(!zkClient.exists(collectionPath, true)) {
log.info("Creating collection in ZooKeeper:" + collection);
SolrParams params = cd.getParams();
try {
Map<String,Object> collectionProps = new HashMap<String,Object>();
// TODO: if collection.configName isn't set, and there isn't already a conf in zk, just use that?
String defaultConfigName = System.getProperty(COLLECTION_PARAM_PREFIX+CONFIGNAME_PROP, collection);
// params passed in - currently only done via core admin (create core commmand).
if (params != null) {
Iterator<String> iter = params.getParameterNamesIterator();
while (iter.hasNext()) {
String paramName = iter.next();
if (paramName.startsWith(COLLECTION_PARAM_PREFIX)) {
collectionProps.put(paramName.substring(COLLECTION_PARAM_PREFIX.length()), params.get(paramName));
}
}
// if the config name wasn't passed in, use the default
if (!collectionProps.containsKey(CONFIGNAME_PROP)) {
// TODO: getting the configName from the collectionPath should fail since we already know it doesn't exist?
getConfName(collection, collectionPath, collectionProps);
}
} else if(System.getProperty("bootstrap_confdir") != null) {
// if we are bootstrapping a collection, default the config for
// a new collection to the collection we are bootstrapping
log.info("Setting config for collection:" + collection + " to " + defaultConfigName);
Properties sysProps = System.getProperties();
for (String sprop : System.getProperties().stringPropertyNames()) {
if (sprop.startsWith(COLLECTION_PARAM_PREFIX)) {
collectionProps.put(sprop.substring(COLLECTION_PARAM_PREFIX.length()), sysProps.getProperty(sprop));
}
}
// if the config name wasn't passed in, use the default
if (!collectionProps.containsKey(CONFIGNAME_PROP))
collectionProps.put(CONFIGNAME_PROP, defaultConfigName);
} else if (Boolean.getBoolean("bootstrap_conf")) {
// the conf name should should be the collection name of this core
collectionProps.put(CONFIGNAME_PROP, cd.getCollectionName());
} else {
getConfName(collection, collectionPath, collectionProps);
}
collectionProps.remove(ZkStateReader.NUM_SHARDS_PROP); // we don't put numShards in the collections properties
ZkNodeProps zkProps = new ZkNodeProps(collectionProps);
zkClient.makePath(collectionPath, ZkStateReader.toJSON(zkProps), CreateMode.PERSISTENT, null, true);
} catch (KeeperException e) {
// its okay if the node already exists
if (e.code() != KeeperException.Code.NODEEXISTS) {
throw e;
}
}
} else {
log.info("Collection zkNode exists");
}
} catch (KeeperException e) {
// its okay if another beats us creating the node
if (e.code() != KeeperException.Code.NODEEXISTS) {
throw e;
}
}
}
private void getConfName(String collection, String collectionPath,
Map<String,Object> collectionProps) throws KeeperException,
InterruptedException {
// check for configName
log.info("Looking for collection configName");
List<String> configNames = null;
int retry = 1;
int retryLimt = 6;
for (; retry < retryLimt; retry++) {
if (zkClient.exists(collectionPath, true)) {
ZkNodeProps cProps = ZkNodeProps.load(zkClient.getData(collectionPath, null, null, true));
if (cProps.containsKey(CONFIGNAME_PROP)) {
break;
}
}
// if there is only one conf, use that
try {
configNames = zkClient.getChildren(CONFIGS_ZKNODE, null,
true);
} catch (NoNodeException e) {
// just keep trying
}
if (configNames != null && configNames.size() == 1) {
// no config set named, but there is only 1 - use it
log.info("Only one config set found in zk - using it:" + configNames.get(0));
collectionProps.put(CONFIGNAME_PROP, configNames.get(0));
break;
}
if (configNames != null && configNames.contains(collection)) {
log.info("Could not find explicit collection configName, but found config name matching collection name - using that set.");
collectionProps.put(CONFIGNAME_PROP, collection);
break;
}
log.info("Could not find collection configName - pausing for 3 seconds and trying again - try: " + retry);
Thread.sleep(3000);
}
if (retry == retryLimt) {
log.error("Could not find configName for collection " + collection);
throw new ZooKeeperException(
SolrException.ErrorCode.SERVER_ERROR,
"Could not find configName for collection " + collection + " found:" + configNames);
}
}
public ZkStateReader getZkStateReader() {
return zkStateReader;
}
private void doGetShardIdAndNodeNameProcess(CoreDescriptor cd) {
final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();
if (coreNodeName != null) {
waitForShardId(cd);
} else {
// if no explicit coreNodeName, we want to match by base url and core name
waitForCoreNodeName(cd);
waitForShardId(cd);
}
}
private void waitForCoreNodeName(CoreDescriptor descriptor) {
int retryCount = 320;
log.info("look for our core node name");
while (retryCount-- > 0) {
Map<String,Slice> slicesMap = zkStateReader.getClusterState()
.getSlicesMap(descriptor.getCloudDescriptor().getCollectionName());
if (slicesMap != null) {
for (Slice slice : slicesMap.values()) {
for (Replica replica : slice.getReplicas()) {
// TODO: for really large clusters, we could 'index' on this
String baseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);
String core = replica.getStr(ZkStateReader.CORE_NAME_PROP);
String msgBaseUrl = getBaseUrl();
String msgCore = descriptor.getName();
if (baseUrl.equals(msgBaseUrl) && core.equals(msgCore)) {
descriptor.getCloudDescriptor()
.setCoreNodeName(replica.getName());
return;
}
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
private void waitForShardId(CoreDescriptor cd) {
log.info("waiting to find shard id in clusterstate for " + cd.getName());
int retryCount = 320;
while (retryCount-- > 0) {
final String shardId = zkStateReader.getClusterState().getShardId(getBaseUrl(), cd.getName());
if (shardId != null) {
cd.getCloudDescriptor().setShardId(shardId);
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
throw new SolrException(ErrorCode.SERVER_ERROR,
"Could not get shard id for core: " + cd.getName());
}
public static void uploadToZK(SolrZkClient zkClient, File dir, String zkPath) throws IOException, KeeperException, InterruptedException {
File[] files = dir.listFiles();
if (files == null) {
throw new IllegalArgumentException("Illegal directory: " + dir);
}
for(File file : files) {
if (!file.getName().startsWith(".")) {
if (!file.isDirectory()) {
zkClient.makePath(zkPath + "/" + file.getName(), file, false, true);
} else {
uploadToZK(zkClient, file, zkPath + "/" + file.getName());
}
}
}
}
public static void downloadFromZK(SolrZkClient zkClient, String zkPath,
File dir) throws IOException, KeeperException, InterruptedException {
List<String> files = zkClient.getChildren(zkPath, null, true);
for (String file : files) {
List<String> children = zkClient.getChildren(zkPath + "/" + file, null, true);
if (children.size() == 0) {
byte[] data = zkClient.getData(zkPath + "/" + file, null, null, true);
dir.mkdirs();
log.info("Write file " + new File(dir, file));
FileUtils.writeByteArrayToFile(new File(dir, file), data);
} else {
downloadFromZK(zkClient, zkPath + "/" + file, new File(dir, file));
}
}
}
public String getCoreNodeName(CoreDescriptor descriptor){
String coreNodeName = descriptor.getCloudDescriptor().getCoreNodeName();
if (coreNodeName == null && !genericCoreNodeNames) {
// it's the default
return getNodeName() + "_" + descriptor.getName();
}
return coreNodeName;
}
public static void uploadConfigDir(SolrZkClient zkClient, File dir, String configName) throws IOException, KeeperException, InterruptedException {
uploadToZK(zkClient, dir, ZkController.CONFIGS_ZKNODE + "/" + configName);
}
public static void downloadConfigDir(SolrZkClient zkClient, String configName, File dir) throws IOException, KeeperException, InterruptedException {
downloadFromZK(zkClient, ZkController.CONFIGS_ZKNODE + "/" + configName, dir);
}
public void preRegister(CoreDescriptor cd ) {
String coreNodeName = getCoreNodeName(cd);
// make sure the node name is set on the descriptor
if (cd.getCloudDescriptor().getCoreNodeName() == null) {
cd.getCloudDescriptor().setCoreNodeName(coreNodeName);
}
// before becoming available, make sure we are not live and active
// this also gets us our assigned shard id if it was not specified
try {
if(cd.getCloudDescriptor().getCollectionName() !=null && cd.getCloudDescriptor().getCoreNodeName() != null ) {
//we were already registered
if(zkStateReader.getClusterState().hasCollection(cd.getCloudDescriptor().getCollectionName())){
DocCollection coll = zkStateReader.getClusterState().getCollection(cd.getCloudDescriptor().getCollectionName());
if(!"true".equals(coll.getStr("autoCreated"))){
Slice slice = coll.getSlice(cd.getCloudDescriptor().getShardId());
if(slice != null){
if(slice.getReplica(cd.getCloudDescriptor().getCoreNodeName()) == null) {
log.info("core_removed This core is removed from ZK");
throw new SolrException(ErrorCode.NOT_FOUND,coreNodeName +" is removed");
}
}
}
}
}
publish(cd, ZkStateReader.DOWN, false);
} catch (KeeperException e) {
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("", e);
throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);
}
if (cd.getCloudDescriptor().getShardId() == null && needsToBeAssignedShardId(cd, zkStateReader.getClusterState(), coreNodeName)) {
doGetShardIdAndNodeNameProcess(cd);
} else {
// still wait till we see us in local state
doGetShardIdAndNodeNameProcess(cd);
}
}
private ZkCoreNodeProps waitForLeaderToSeeDownState(
CoreDescriptor descriptor, final String coreZkNodeName) {
CloudDescriptor cloudDesc = descriptor.getCloudDescriptor();
String collection = cloudDesc.getCollectionName();
String shard = cloudDesc.getShardId();
ZkCoreNodeProps leaderProps = null;
int retries = 6;
for (int i = 0; i < retries; i++) {
try {
if (isClosed) {
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,
"We have been closed");
}
// go straight to zk, not the cloud state - we must have current info
leaderProps = getLeaderProps(collection, shard, 30000);
break;
} catch (Exception e) {
SolrException.log(log, "There was a problem finding the leader in zk", e);
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
if (i == retries - 1) {
throw new SolrException(ErrorCode.SERVER_ERROR, "There was a problem finding the leader in zk");
}
}
}
String leaderBaseUrl = leaderProps.getBaseUrl();
String leaderCoreName = leaderProps.getCoreName();
String ourUrl = ZkCoreNodeProps.getCoreUrl(getBaseUrl(),
descriptor.getName());
boolean isLeader = leaderProps.getCoreUrl().equals(ourUrl);
if (!isLeader && !SKIP_AUTO_RECOVERY) {
HttpSolrServer server = null;
server = new HttpSolrServer(leaderBaseUrl);
try {
server.setConnectionTimeout(15000);
server.setSoTimeout(120000);
WaitForState prepCmd = new WaitForState();
prepCmd.setCoreName(leaderCoreName);
prepCmd.setNodeName(getNodeName());
prepCmd.setCoreNodeName(coreZkNodeName);
prepCmd.setState(ZkStateReader.DOWN);
// let's retry a couple times - perhaps the leader just went down,
// or perhaps he is just not quite ready for us yet
retries = 6;
for (int i = 0; i < retries; i++) {
if (isClosed) {
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,
"We have been closed");
}
try {
server.request(prepCmd);
break;
} catch (Exception e) {
SolrException.log(log,
"There was a problem making a request to the leader", e);
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
if (i == retries - 1) {
throw new SolrException(ErrorCode.SERVER_ERROR,
"There was a problem making a request to the leader");
}
}
}
} finally {
server.shutdown();
}
}
return leaderProps;
}
public static void linkConfSet(SolrZkClient zkClient, String collection, String confSetName) throws KeeperException, InterruptedException {
String path = ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection;
if (log.isInfoEnabled()) {
log.info("Load collection config from:" + path);
}
byte[] data;
try {
data = zkClient.getData(path, null, null, true);
} catch (NoNodeException e) {
// if there is no node, we will try and create it
// first try to make in case we are pre configuring
ZkNodeProps props = new ZkNodeProps(CONFIGNAME_PROP, confSetName);
try {
zkClient.makePath(path, ZkStateReader.toJSON(props),
CreateMode.PERSISTENT, null, true);
} catch (KeeperException e2) {
// its okay if the node already exists
if (e2.code() != KeeperException.Code.NODEEXISTS) {
throw e;
}
// if we fail creating, setdata
// TODO: we should consider using version
zkClient.setData(path, ZkStateReader.toJSON(props), true);
}
return;
}
// we found existing data, let's update it
ZkNodeProps props = null;
if(data != null) {
props = ZkNodeProps.load(data);
Map<String,Object> newProps = new HashMap<String,Object>();
newProps.putAll(props.getProperties());
newProps.put(CONFIGNAME_PROP, confSetName);
props = new ZkNodeProps(newProps);
} else {
props = new ZkNodeProps(CONFIGNAME_PROP, confSetName);
}
// TODO: we should consider using version
zkClient.setData(path, ZkStateReader.toJSON(props), true);
}
/**
* If in SolrCloud mode, upload config sets for each SolrCore in solr.xml.
*/
public static void bootstrapConf(SolrZkClient zkClient, CoreContainer cc, String solrHome) throws IOException,
KeeperException, InterruptedException {
//List<String> allCoreNames = cfg.getAllCoreNames();
List<CoreDescriptor> cds = cc.getCoresLocator().discover(cc);
log.info("bootstrapping config for " + cds.size() + " cores into ZooKeeper using solr.xml from " + solrHome);
for (CoreDescriptor cd : cds) {
String coreName = cd.getName();
String confName = cd.getCollectionName();
if (StringUtils.isEmpty(confName))
confName = coreName;
String instanceDir = cd.getInstanceDir();
File udir = new File(instanceDir, "conf");
log.info("Uploading directory " + udir + " with name " + confName + " for SolrCore " + coreName);
ZkController.uploadConfigDir(zkClient, udir, confName);
}
}
public DistributedQueue getOverseerJobQueue() {
return overseerJobQueue;
}
public DistributedQueue getOverseerCollectionQueue() {
return overseerCollectionQueue;
}
public int getClientTimeout() {
return clientTimeout;
}
public Overseer getOverseer() {
return overseer;
}
public LeaderElector getOverseerElector() {
return overseerElector;
}
/**
* Returns the nodeName that should be used based on the specified properties.
*
* @param hostName - must not be null or the empty string
* @param hostPort - must consist only of digits, must not be null or the empty string
* @param hostContext - should not begin or end with a slash (leading/trailin slashes will be ignored), must not be null, may be the empty string to denote the root context
* @lucene.experimental
* @see SolrZkClient#getBaseUrlForNodeName
*/
static String generateNodeName(final String hostName,
final String hostPort,
final String hostContext) {
try {
return hostName + ':' + hostPort + '_' +
URLEncoder.encode(trimLeadingAndTrailingSlashes(hostContext), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("JVM Does not seem to support UTF-8", e);
}
}
/**
* Utility method for trimming and leading and/or trailing slashes from
* it's input. May return the empty string. May return null if and only
* if the input is null.
*/
public static String trimLeadingAndTrailingSlashes(final String in) {
if (null == in) return in;
String out = in;
if (out.startsWith("/")) {
out = out.substring(1);
}
if (out.endsWith("/")) {
out = out.substring(0,out.length()-1);
}
return out;
}
}
|
SOLR-5510
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1546922 13f79535-47bb-0310-9956-ffa450edef68
|
solr/core/src/java/org/apache/solr/cloud/ZkController.java
|
SOLR-5510
|
<ide><path>olr/core/src/java/org/apache/solr/cloud/ZkController.java
<ide> public void preRegister(CoreDescriptor cd ) {
<ide>
<ide> String coreNodeName = getCoreNodeName(cd);
<del>
<del> // make sure the node name is set on the descriptor
<del> if (cd.getCloudDescriptor().getCoreNodeName() == null) {
<del> cd.getCloudDescriptor().setCoreNodeName(coreNodeName);
<del> }
<del>
<ide> // before becoming available, make sure we are not live and active
<ide> // this also gets us our assigned shard id if it was not specified
<ide> try {
<del> if(cd.getCloudDescriptor().getCollectionName() !=null && cd.getCloudDescriptor().getCoreNodeName() != null ) {
<add> CloudDescriptor cloudDesc = cd.getCloudDescriptor();
<add> if(cd.getCloudDescriptor().getCollectionName() !=null && cloudDesc.getCoreNodeName() != null ) {
<ide> //we were already registered
<del> if(zkStateReader.getClusterState().hasCollection(cd.getCloudDescriptor().getCollectionName())){
<del> DocCollection coll = zkStateReader.getClusterState().getCollection(cd.getCloudDescriptor().getCollectionName());
<add> if(zkStateReader.getClusterState().hasCollection(cloudDesc.getCollectionName())){
<add> DocCollection coll = zkStateReader.getClusterState().getCollection(cloudDesc.getCollectionName());
<ide> if(!"true".equals(coll.getStr("autoCreated"))){
<del> Slice slice = coll.getSlice(cd.getCloudDescriptor().getShardId());
<add> Slice slice = coll.getSlice(cloudDesc.getShardId());
<ide> if(slice != null){
<del> if(slice.getReplica(cd.getCloudDescriptor().getCoreNodeName()) == null) {
<add> if(slice.getReplica(cloudDesc.getCoreNodeName()) == null) {
<ide> log.info("core_removed This core is removed from ZK");
<del> throw new SolrException(ErrorCode.NOT_FOUND,coreNodeName +" is removed");
<add> throw new SolrException(ErrorCode.NOT_FOUND,cloudDesc.getCoreNodeName() +" is removed");
<ide> }
<ide> }
<ide> }
<ide> }
<ide> }
<add>
<add> // make sure the node name is set on the descriptor
<add> if (cloudDesc.getCoreNodeName() == null) {
<add> cloudDesc.setCoreNodeName(coreNodeName);
<add> }
<add>
<ide> publish(cd, ZkStateReader.DOWN, false);
<ide> } catch (KeeperException e) {
<ide> log.error("", e);
|
|
Java
|
apache-2.0
|
1fc2ddb5bb2cf1ad5a1f5be2c4ea23d5651d379f
| 0 |
FHannes/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,da1z/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,allotria/intellij-community,da1z/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,signed/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,signed/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,allotria/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ibinti/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,xfournet/intellij-community,semonte/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,fitermay/intellij-community,xfournet/intellij-community,signed/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,semonte/intellij-community,da1z/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,fitermay/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,fitermay/intellij-community,signed/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,signed/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,semonte/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,vvv1559/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,apixandru/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,signed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ibinti/intellij-community,allotria/intellij-community,signed/intellij-community,FHannes/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,allotria/intellij-community,semonte/intellij-community,da1z/intellij-community,signed/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,fitermay/intellij-community,asedunov/intellij-community,semonte/intellij-community,apixandru/intellij-community,hurricup/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,semonte/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,xfournet/intellij-community,semonte/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ibinti/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,FHannes/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,semonte/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community
|
/*
* Copyright 2000-2016 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.openapi.progress.impl;
import com.google.common.collect.ConcurrentHashMultiset;
import com.intellij.concurrency.JobScheduler;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.progress.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.ex.ProgressIndicatorEx;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.containers.ConcurrentLongObjectMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.SmartHashSet;
import com.intellij.util.io.storage.HeavyProcessLatch;
import gnu.trove.THashMap;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class CoreProgressManager extends ProgressManager implements Disposable {
static final int CHECK_CANCELED_DELAY_MILLIS = 10;
final AtomicInteger myCurrentUnsafeProgressCount = new AtomicInteger(0);
private final AtomicInteger myCurrentModalProgressCount = new AtomicInteger(0);
private static final boolean ENABLED = !"disabled".equals(System.getProperty("idea.ProcessCanceledException"));
private static boolean ourMaySleepInCheckCanceled;
private ScheduledFuture<?> myCheckCancelledFuture; // guarded by threadsUnderIndicator
// indicator -> threads which are running under this indicator. guarded by threadsUnderIndicator.
private static final Map<ProgressIndicator, Set<Thread>> threadsUnderIndicator = new THashMap<ProgressIndicator, Set<Thread>>();
// the active indicator for the thread id
private static final ConcurrentLongObjectMap<ProgressIndicator> currentIndicators = ContainerUtil.createConcurrentLongObjectMap();
// threads which are running under canceled indicator
static final Set<Thread> threadsUnderCanceledIndicator = ContainerUtil.newConcurrentSet();
private static volatile boolean shouldCheckCanceled;
/** active (i.e. which have {@link #executeProcessUnderProgress(Runnable, ProgressIndicator)} method running) indicators
* which are not inherited from {@link StandardProgressIndicator}.
* for them an extra processing thread (see {@link #myCheckCancelledFuture}) has to be run
* to call their non-standard {@link ProgressIndicator#checkCanceled()} method periodically.
*/
// multiset here (instead of a set) is for simplifying add/remove indicators on process-with-progress start/end with possibly identical indicators.
private static final Collection<ProgressIndicator> nonStandardIndicators = ConcurrentHashMultiset.create();
public CoreProgressManager() {
HeavyProcessLatch.INSTANCE.addUIActivityListener(new HeavyProcessLatch.HeavyProcessListener() {
@Override
public void processStarted() {
updateShouldCheckCanceled();
}
@Override
public void processFinished() {
updateShouldCheckCanceled();
}
}, this);
}
// must be under threadsUnderIndicator lock
private void startBackgroundNonStandardIndicatorsPing() {
if (myCheckCancelledFuture == null) {
myCheckCancelledFuture = JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
for (ProgressIndicator indicator : nonStandardIndicators) {
try {
indicator.checkCanceled();
}
catch (ProcessCanceledException e) {
indicatorCanceled(indicator);
}
}
}
}, 0, CHECK_CANCELED_DELAY_MILLIS, TimeUnit.MILLISECONDS);
}
}
// must be under threadsUnderIndicator lock
private void stopBackgroundNonStandardIndicatorsPing() {
if (myCheckCancelledFuture != null) {
myCheckCancelledFuture.cancel(true);
myCheckCancelledFuture = null;
}
}
@Override
public void dispose() {
synchronized (threadsUnderIndicator) {
stopBackgroundNonStandardIndicatorsPing();
}
}
public static boolean sleepIfNeeded() {
if (ourMaySleepInCheckCanceled && HeavyProcessLatch.INSTANCE.isInsideLowPriorityThread()) {
TimeoutUtil.sleep(1);
return true;
}
return false;
}
@Override
protected void doCheckCanceled() throws ProcessCanceledException {
if (!shouldCheckCanceled) return;
final ProgressIndicator progress = getProgressIndicator();
if (progress != null && ENABLED) {
progress.checkCanceled();
}
else {
sleepIfNeeded();
}
}
@Override
public boolean hasProgressIndicator() {
return getProgressIndicator() != null;
}
@Override
public boolean hasUnsafeProgressIndicator() {
return myCurrentUnsafeProgressCount.get() > 0;
}
@Override
public boolean hasModalProgressIndicator() {
return myCurrentModalProgressCount.get() > 0;
}
@Override
public void runProcess(@NotNull final Runnable process, final ProgressIndicator progress) {
executeProcessUnderProgress(new Runnable(){
@Override
public void run() {
try {
try {
if (progress != null && !progress.isRunning()) {
progress.start();
}
}
catch (RuntimeException e) {
throw e;
}
catch (Throwable e) {
throw new RuntimeException(e);
}
process.run();
}
finally {
if (progress != null && progress.isRunning()) {
progress.stop();
if (progress instanceof ProgressIndicatorEx) {
((ProgressIndicatorEx)progress).processFinish();
}
}
}
}
},progress);
}
@Override
public <T> T runProcess(@NotNull final Computable<T> process, ProgressIndicator progress) throws ProcessCanceledException {
final Ref<T> ref = new Ref<T>();
runProcess(new Runnable() {
@Override
public void run() {
ref.set(process.compute());
}
}, progress);
return ref.get();
}
@Override
public void executeNonCancelableSection(@NotNull Runnable runnable) {
executeProcessUnderProgress(runnable, NonCancelableIndicator.INSTANCE);
}
@Override
public void setCancelButtonText(String cancelButtonText) {
}
@Override
public boolean runProcessWithProgressSynchronously(@NotNull Runnable process,
@NotNull @Nls String progressTitle,
boolean canBeCanceled,
@Nullable Project project) {
return runProcessWithProgressSynchronously(process, progressTitle, canBeCanceled, project, null);
}
@Override
public <T, E extends Exception> T runProcessWithProgressSynchronously(@NotNull final ThrowableComputable<T, E> process,
@NotNull @Nls String progressTitle,
boolean canBeCanceled,
@Nullable Project project) throws E {
final AtomicReference<T> result = new AtomicReference<T>();
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
runProcessWithProgressSynchronously(new Task.Modal(project, progressTitle, canBeCanceled) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
try {
T compute = process.compute();
result.set(compute);
}
catch (Throwable t) {
exception.set(t);
}
}
}, null);
//noinspection ThrowableResultOfMethodCallIgnored
Throwable t = exception.get();
if (t != null) {
if (t instanceof Error) throw (Error)t;
if (t instanceof RuntimeException) throw (RuntimeException)t;
@SuppressWarnings("unchecked") E e = (E)t;
throw e;
}
return result.get();
}
@Override
public boolean runProcessWithProgressSynchronously(@NotNull final Runnable process,
@NotNull @Nls String progressTitle,
boolean canBeCanceled,
@Nullable Project project,
@Nullable JComponent parentComponent) {
Task.Modal task = new Task.Modal(project, progressTitle, canBeCanceled) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
process.run();
}
};
return runProcessWithProgressSynchronously(task, parentComponent);
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull Project project,
@NotNull @Nls String progressTitle,
@NotNull Runnable process,
@Nullable Runnable successRunnable,
@Nullable Runnable canceledRunnable) {
runProcessWithProgressAsynchronously(project, progressTitle, process, successRunnable, canceledRunnable, PerformInBackgroundOption.DEAF);
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull Project project,
@NotNull @Nls String progressTitle,
@NotNull final Runnable process,
@Nullable final Runnable successRunnable,
@Nullable final Runnable canceledRunnable,
@NotNull PerformInBackgroundOption option) {
runProcessWithProgressAsynchronously(new Task.Backgroundable(project, progressTitle, true, option) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
process.run();
}
@Override
public void onCancel() {
if (canceledRunnable != null) {
canceledRunnable.run();
}
}
@Override
public void onSuccess() {
if (successRunnable != null) {
successRunnable.run();
}
}
});
}
@Override
public void run(@NotNull final Task task) {
if (task.isHeadless()) {
if (ApplicationManager.getApplication().isDispatchThread()) {
runProcessWithProgressSynchronously(task, null);
}
else {
runProcessWithProgressInCurrentThread(task, new EmptyProgressIndicator(), ModalityState.defaultModalityState());
}
}
else if (task.isModal()) {
runSynchronously(task.asModal());
}
else {
final Task.Backgroundable backgroundable = task.asBackgroundable();
if (backgroundable.isConditionalModal() && !backgroundable.shouldStartInBackground()) {
runSynchronously(task);
}
else {
runAsynchronously(backgroundable);
}
}
}
private void runSynchronously(@NotNull final Task task) {
Runnable runnable = new Runnable() {
@Override
public void run() {
runProcessWithProgressSynchronously(task, null);
}
};
if (ApplicationManager.getApplication().isDispatchThread()) {
runnable.run();
}
else {
ApplicationManager.getApplication().invokeAndWait(runnable, ModalityState.defaultModalityState());
}
}
private void runAsynchronously(@NotNull final Task.Backgroundable task) {
Runnable runnable = new Runnable() {
@Override
public void run() {
runProcessWithProgressAsynchronously(task);
}
};
if (ApplicationManager.getApplication().isDispatchThread()) {
runnable.run();
}
else {
ApplicationManager.getApplication().invokeLater(runnable, ModalityState.defaultModalityState());
}
}
@NotNull
public Future<?> runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task) {
return runProcessWithProgressAsynchronously(task, new EmptyProgressIndicator(), null);
}
@NotNull
public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task,
@NotNull final ProgressIndicator progressIndicator,
@Nullable final Runnable continuation) {
return runProcessWithProgressAsynchronously(task, progressIndicator, continuation, ModalityState.defaultModalityState());
}
@NotNull
public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task,
@NotNull final ProgressIndicator progressIndicator,
@Nullable final Runnable continuation,
@NotNull final ModalityState modalityState) {
if (progressIndicator instanceof Disposable) {
Disposer.register(ApplicationManager.getApplication(), (Disposable)progressIndicator);
}
final Runnable process = new TaskRunnable(task, progressIndicator, continuation);
Runnable action = new TaskContainer(task) {
@Override
public void run() {
boolean processCanceled = false;
Exception exception = null;
try {
runProcess(process, progressIndicator);
}
catch (ProcessCanceledException e) {
processCanceled = true;
}
catch (Exception e) {
exception = e;
}
final boolean finalCanceled = processCanceled || progressIndicator.isCanceled();
final Exception finalException = exception;
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
finishTask(task, finalCanceled, finalException);
}
}, modalityState);
}
};
return ApplicationManager.getApplication().executeOnPooledThread(action);
}
public boolean runProcessWithProgressSynchronously(@NotNull final Task task, @Nullable final JComponent parentComponent) {
final Ref<Exception> exceptionRef = new Ref<Exception>();
TaskContainer taskContainer = new TaskContainer(task) {
@Override
public void run() {
try {
new TaskRunnable(task, getProgressIndicator()).run();
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception e) {
exceptionRef.set(e);
}
}
};
ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication();
boolean result = application.runProcessWithProgressSynchronously(taskContainer, task.getTitle(), task.isCancellable(),
task.getProject(), parentComponent, task.getCancelText());
finishTask(task, !result, exceptionRef.get());
return result;
}
public void runProcessWithProgressInCurrentThread(@NotNull final Task task,
@NotNull final ProgressIndicator progressIndicator,
@NotNull final ModalityState modalityState) {
if (progressIndicator instanceof Disposable) {
Disposer.register(ApplicationManager.getApplication(), (Disposable)progressIndicator);
}
final Runnable process = new TaskRunnable(task, progressIndicator);
boolean processCanceled = false;
Exception exception = null;
try {
runProcess(process, progressIndicator);
}
catch (ProcessCanceledException e) {
processCanceled = true;
}
catch (Exception e) {
exception = e;
}
final boolean finalCanceled = processCanceled || progressIndicator.isCanceled();
final Exception finalException = exception;
if (ApplicationManager.getApplication().isDispatchThread()) {
finishTask(task, finalCanceled, finalException);
}
else {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
finishTask(task, finalCanceled, finalException);
}
}, modalityState);
}
}
static void finishTask(@NotNull Task task, boolean canceled, @Nullable Exception exception) {
try {
if (exception != null) {
task.onError(exception);
}
else if (canceled) {
task.onCancel();
}
else {
task.onSuccess();
}
}
finally {
task.onFinished();
}
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task, @NotNull ProgressIndicator progressIndicator) {
runProcessWithProgressAsynchronously(task, progressIndicator, null);
}
@Override
public ProgressIndicator getProgressIndicator() {
return getCurrentIndicator(Thread.currentThread());
}
@Override
public void executeProcessUnderProgress(@NotNull Runnable process, ProgressIndicator progress) throws ProcessCanceledException {
boolean modal = progress != null && progress.isModal();
if (modal) myCurrentModalProgressCount.incrementAndGet();
if (progress == null) myCurrentUnsafeProgressCount.incrementAndGet();
try {
ProgressIndicator oldIndicator = null;
boolean set = progress != null && progress != (oldIndicator = getProgressIndicator());
if (set) {
Thread currentThread = Thread.currentThread();
setCurrentIndicator(currentThread, progress);
try {
registerIndicatorAndRun(progress, currentThread, oldIndicator, process);
}
finally {
setCurrentIndicator(currentThread, oldIndicator);
}
}
else {
process.run();
}
}
finally {
if (progress == null) myCurrentUnsafeProgressCount.decrementAndGet();
if (modal) myCurrentModalProgressCount.decrementAndGet();
}
}
private void registerIndicatorAndRun(@NotNull ProgressIndicator indicator,
@NotNull Thread currentThread,
ProgressIndicator oldIndicator,
@NotNull Runnable process) {
List<Set<Thread>> threadsUnderThisIndicator = new ArrayList<Set<Thread>>();
synchronized (threadsUnderIndicator) {
for (ProgressIndicator thisIndicator = indicator; thisIndicator != null; thisIndicator = thisIndicator instanceof WrappedProgressIndicator ? ((WrappedProgressIndicator)thisIndicator).getOriginalProgressIndicator() : null) {
Set<Thread> underIndicator = threadsUnderIndicator.get(thisIndicator);
if (underIndicator == null) {
underIndicator = new SmartHashSet<Thread>();
threadsUnderIndicator.put(thisIndicator, underIndicator);
}
boolean alreadyUnder = !underIndicator.add(currentThread);
threadsUnderThisIndicator.add(alreadyUnder ? null : underIndicator);
boolean isStandard = thisIndicator instanceof StandardProgressIndicator;
if (!isStandard) {
nonStandardIndicators.add(thisIndicator);
startBackgroundNonStandardIndicatorsPing();
}
if (thisIndicator.isCanceled()) {
threadsUnderCanceledIndicator.add(currentThread);
}
else {
threadsUnderCanceledIndicator.remove(currentThread);
}
}
updateShouldCheckCanceled();
}
try {
process.run();
}
finally {
synchronized (threadsUnderIndicator) {
ProgressIndicator thisIndicator = null;
// order doesn't matter
for (int i = 0; i < threadsUnderThisIndicator.size(); i++) {
thisIndicator = i == 0 ? indicator : ((WrappedProgressIndicator)thisIndicator).getOriginalProgressIndicator();
Set<Thread> underIndicator = threadsUnderThisIndicator.get(i);
boolean removed = underIndicator != null && underIndicator.remove(currentThread);
if (removed && underIndicator.isEmpty()) {
threadsUnderIndicator.remove(thisIndicator);
}
boolean isStandard = thisIndicator instanceof StandardProgressIndicator;
if (!isStandard) {
nonStandardIndicators.remove(thisIndicator);
if (nonStandardIndicators.isEmpty()) {
stopBackgroundNonStandardIndicatorsPing();
}
}
// by this time oldIndicator may have been canceled
if (oldIndicator != null && oldIndicator.isCanceled()) {
threadsUnderCanceledIndicator.add(currentThread);
}
else {
threadsUnderCanceledIndicator.remove(currentThread);
}
}
updateShouldCheckCanceled();
}
}
}
private static void updateShouldCheckCanceled() {
ourMaySleepInCheckCanceled = Registry.is("ide.prioritize.ui.thread", false);
if (ourMaySleepInCheckCanceled && HeavyProcessLatch.INSTANCE.hasPrioritizedThread()) {
shouldCheckCanceled = true;
return;
}
synchronized (threadsUnderIndicator) {
shouldCheckCanceled = !threadsUnderCanceledIndicator.isEmpty();
}
}
@Override
protected void indicatorCanceled(@NotNull ProgressIndicator indicator) {
// mark threads running under this indicator as canceled
synchronized (threadsUnderIndicator) {
Set<Thread> threads = threadsUnderIndicator.get(indicator);
if (threads != null) {
for (Thread thread : threads) {
boolean underCancelledIndicator = false;
for (ProgressIndicator currentIndicator = getCurrentIndicator(thread);
currentIndicator != null;
currentIndicator = currentIndicator instanceof WrappedProgressIndicator ?
((WrappedProgressIndicator)currentIndicator).getOriginalProgressIndicator() : null) {
if (currentIndicator == indicator) {
underCancelledIndicator = true;
break;
}
}
if (underCancelledIndicator) {
threadsUnderCanceledIndicator.add(thread);
//noinspection AssignmentToStaticFieldFromInstanceMethod
shouldCheckCanceled = true;
}
}
}
}
}
@TestOnly
public static boolean isCanceledThread(@NotNull Thread thread) {
return threadsUnderCanceledIndicator.contains(thread);
}
@NotNull
@Override
public final NonCancelableSection startNonCancelableSection() {
final ProgressIndicator myOld = getProgressIndicator();
final Thread currentThread = Thread.currentThread();
NonCancelableIndicator nonCancelor = new NonCancelableIndicator() {
@Override
public void done() {
setCurrentIndicator(currentThread, myOld);
}
};
setCurrentIndicator(currentThread, nonCancelor);
return nonCancelor;
}
private static void setCurrentIndicator(@NotNull Thread currentThread, ProgressIndicator indicator) {
if (indicator == null) {
currentIndicators.remove(currentThread.getId());
}
else {
currentIndicators.put(currentThread.getId(), indicator);
}
}
private static ProgressIndicator getCurrentIndicator(@NotNull Thread thread) {
return currentIndicators.get(thread.getId());
}
protected abstract static class TaskContainer implements Runnable {
private final Task myTask;
protected TaskContainer(@NotNull Task task) {
myTask = task;
}
@NotNull
public Task getTask() {
return myTask;
}
@Override
public String toString() {
return myTask.toString();
}
}
protected static class TaskRunnable extends TaskContainer {
private final ProgressIndicator myIndicator;
private final Runnable myContinuation;
public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator) {
this(task, indicator, null);
}
public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) {
super(task);
myIndicator = indicator;
myContinuation = continuation;
}
@Override
public void run() {
try {
getTask().run(myIndicator);
}
finally {
try {
if (myIndicator instanceof ProgressIndicatorEx) {
((ProgressIndicatorEx)myIndicator).finish(getTask());
}
}
finally {
if (myContinuation != null) {
myContinuation.run();
}
}
}
}
}
}
|
platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java
|
/*
* Copyright 2000-2016 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.openapi.progress.impl;
import com.google.common.collect.ConcurrentHashMultiset;
import com.intellij.concurrency.JobScheduler;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.progress.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.ex.ProgressIndicatorEx;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.containers.ConcurrentLongObjectMap;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.SmartHashSet;
import com.intellij.util.io.storage.HeavyProcessLatch;
import gnu.trove.THashMap;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class CoreProgressManager extends ProgressManager implements Disposable {
static final int CHECK_CANCELED_DELAY_MILLIS = 10;
final AtomicInteger myCurrentUnsafeProgressCount = new AtomicInteger(0);
private final AtomicInteger myCurrentModalProgressCount = new AtomicInteger(0);
private static final boolean ENABLED = !"disabled".equals(System.getProperty("idea.ProcessCanceledException"));
private static boolean ourMaySleepInCheckCanceled;
private ScheduledFuture<?> myCheckCancelledFuture; // guarded by threadsUnderIndicator
// indicator -> threads which are running under this indicator. guarded by threadsUnderIndicator.
private static final Map<ProgressIndicator, Set<Thread>> threadsUnderIndicator = new THashMap<ProgressIndicator, Set<Thread>>();
// the active indicator for the thread id
private static final ConcurrentLongObjectMap<ProgressIndicator> currentIndicators = ContainerUtil.createConcurrentLongObjectMap();
// threads which are running under canceled indicator
static final Set<Thread> threadsUnderCanceledIndicator = ContainerUtil.newConcurrentSet();
private static volatile boolean shouldCheckCanceled;
/** active (i.e. which have {@link #executeProcessUnderProgress(Runnable, ProgressIndicator)} method running) indicators
* which are not inherited from {@link StandardProgressIndicator}.
* for them an extra processing thread (see {@link #myCheckCancelledFuture}) has to be run
* to call their non-standard {@link ProgressIndicator#checkCanceled()} method periodically.
*/
// multiset here (instead of a set) is for simplifying add/remove indicators on process-with-progress start/end with possibly identical indicators.
private static final Collection<ProgressIndicator> nonStandardIndicators = ConcurrentHashMultiset.create();
public CoreProgressManager() {
HeavyProcessLatch.INSTANCE.addUIActivityListener(new HeavyProcessLatch.HeavyProcessListener() {
@Override
public void processStarted() {
updateShouldCheckCanceled();
}
@Override
public void processFinished() {
updateShouldCheckCanceled();
}
}, this);
}
// must be under threadsUnderIndicator lock
private void startBackgroundNonStandardIndicatorsPing() {
if (myCheckCancelledFuture == null) {
myCheckCancelledFuture = JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
for (ProgressIndicator indicator : nonStandardIndicators) {
try {
indicator.checkCanceled();
}
catch (ProcessCanceledException e) {
indicatorCanceled(indicator);
}
}
}
}, 0, CHECK_CANCELED_DELAY_MILLIS, TimeUnit.MILLISECONDS);
}
}
// must be under threadsUnderIndicator lock
private void stopBackgroundNonStandardIndicatorsPing() {
if (myCheckCancelledFuture != null) {
myCheckCancelledFuture.cancel(true);
myCheckCancelledFuture = null;
}
}
@Override
public void dispose() {
synchronized (threadsUnderIndicator) {
stopBackgroundNonStandardIndicatorsPing();
}
}
public static boolean sleepIfNeeded() {
if (ourMaySleepInCheckCanceled && HeavyProcessLatch.INSTANCE.isInsideLowPriorityThread()) {
TimeoutUtil.sleep(1);
return true;
}
return false;
}
@Override
protected void doCheckCanceled() throws ProcessCanceledException {
if (!shouldCheckCanceled) return;
final ProgressIndicator progress = getProgressIndicator();
if (progress != null && ENABLED) {
progress.checkCanceled();
}
else {
sleepIfNeeded();
}
}
@Override
public boolean hasProgressIndicator() {
return getProgressIndicator() != null;
}
@Override
public boolean hasUnsafeProgressIndicator() {
return myCurrentUnsafeProgressCount.get() > 0;
}
@Override
public boolean hasModalProgressIndicator() {
return myCurrentModalProgressCount.get() > 0;
}
@Override
public void runProcess(@NotNull final Runnable process, final ProgressIndicator progress) {
executeProcessUnderProgress(new Runnable(){
@Override
public void run() {
try {
try {
if (progress != null && !progress.isRunning()) {
progress.start();
}
}
catch (RuntimeException e) {
throw e;
}
catch (Throwable e) {
throw new RuntimeException(e);
}
process.run();
}
finally {
if (progress != null && progress.isRunning()) {
progress.stop();
if (progress instanceof ProgressIndicatorEx) {
((ProgressIndicatorEx)progress).processFinish();
}
}
}
}
},progress);
}
@Override
public <T> T runProcess(@NotNull final Computable<T> process, ProgressIndicator progress) throws ProcessCanceledException {
final Ref<T> ref = new Ref<T>();
runProcess(new Runnable() {
@Override
public void run() {
ref.set(process.compute());
}
}, progress);
return ref.get();
}
@Override
public void executeNonCancelableSection(@NotNull Runnable runnable) {
executeProcessUnderProgress(runnable, NonCancelableIndicator.INSTANCE);
}
@Override
public void setCancelButtonText(String cancelButtonText) {
}
@Override
public boolean runProcessWithProgressSynchronously(@NotNull Runnable process,
@NotNull @Nls String progressTitle,
boolean canBeCanceled,
@Nullable Project project) {
return runProcessWithProgressSynchronously(process, progressTitle, canBeCanceled, project, null);
}
@Override
public <T, E extends Exception> T runProcessWithProgressSynchronously(@NotNull final ThrowableComputable<T, E> process,
@NotNull @Nls String progressTitle,
boolean canBeCanceled,
@Nullable Project project) throws E {
final AtomicReference<T> result = new AtomicReference<T>();
final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
runProcessWithProgressSynchronously(new Task.Modal(project, progressTitle, canBeCanceled) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
try {
T compute = process.compute();
result.set(compute);
}
catch (Throwable t) {
exception.set(t);
}
}
}, null);
//noinspection ThrowableResultOfMethodCallIgnored
Throwable t = exception.get();
if (t != null) {
if (t instanceof Error) throw (Error)t;
if (t instanceof RuntimeException) throw (RuntimeException)t;
@SuppressWarnings("unchecked") E e = (E)t;
throw e;
}
return result.get();
}
@Override
public boolean runProcessWithProgressSynchronously(@NotNull final Runnable process,
@NotNull @Nls String progressTitle,
boolean canBeCanceled,
@Nullable Project project,
@Nullable JComponent parentComponent) {
Task.Modal task = new Task.Modal(project, progressTitle, canBeCanceled) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
process.run();
}
};
return runProcessWithProgressSynchronously(task, parentComponent);
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull Project project,
@NotNull @Nls String progressTitle,
@NotNull Runnable process,
@Nullable Runnable successRunnable,
@Nullable Runnable canceledRunnable) {
runProcessWithProgressAsynchronously(project, progressTitle, process, successRunnable, canceledRunnable, PerformInBackgroundOption.DEAF);
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull Project project,
@NotNull @Nls String progressTitle,
@NotNull final Runnable process,
@Nullable final Runnable successRunnable,
@Nullable final Runnable canceledRunnable,
@NotNull PerformInBackgroundOption option) {
runProcessWithProgressAsynchronously(new Task.Backgroundable(project, progressTitle, true, option) {
@Override
public void run(@NotNull final ProgressIndicator indicator) {
process.run();
}
@Override
public void onCancel() {
if (canceledRunnable != null) {
canceledRunnable.run();
}
}
@Override
public void onSuccess() {
if (successRunnable != null) {
successRunnable.run();
}
}
});
}
@Override
public void run(@NotNull final Task task) {
if (task.isHeadless()) {
if (ApplicationManager.getApplication().isDispatchThread()) {
runProcessWithProgressSynchronously(task, null);
}
else {
runProcessWithProgressInCurrentThread(task, new EmptyProgressIndicator(), ModalityState.NON_MODAL);
}
}
else if (task.isModal()) {
runSynchronously(task.asModal());
}
else {
final Task.Backgroundable backgroundable = task.asBackgroundable();
if (backgroundable.isConditionalModal() && !backgroundable.shouldStartInBackground()) {
runSynchronously(task);
}
else {
runAsynchronously(backgroundable);
}
}
}
private void runSynchronously(@NotNull final Task task) {
Runnable runnable = new Runnable() {
@Override
public void run() {
runProcessWithProgressSynchronously(task, null);
}
};
if (ApplicationManager.getApplication().isDispatchThread()) {
runnable.run();
}
else {
ApplicationManager.getApplication().invokeAndWait(runnable, ModalityState.NON_MODAL);
}
}
private void runAsynchronously(@NotNull final Task.Backgroundable task) {
Runnable runnable = new Runnable() {
@Override
public void run() {
runProcessWithProgressAsynchronously(task);
}
};
if (ApplicationManager.getApplication().isDispatchThread()) {
runnable.run();
}
else {
ApplicationManager.getApplication().invokeLater(runnable, ModalityState.NON_MODAL);
}
}
@NotNull
public Future<?> runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task) {
return runProcessWithProgressAsynchronously(task, new EmptyProgressIndicator(), null);
}
@NotNull
public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task,
@NotNull final ProgressIndicator progressIndicator,
@Nullable final Runnable continuation) {
return runProcessWithProgressAsynchronously(task, progressIndicator, continuation, ModalityState.NON_MODAL);
}
@NotNull
public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task,
@NotNull final ProgressIndicator progressIndicator,
@Nullable final Runnable continuation,
@NotNull final ModalityState modalityState) {
if (progressIndicator instanceof Disposable) {
Disposer.register(ApplicationManager.getApplication(), (Disposable)progressIndicator);
}
final Runnable process = new TaskRunnable(task, progressIndicator, continuation);
Runnable action = new TaskContainer(task) {
@Override
public void run() {
boolean processCanceled = false;
Exception exception = null;
try {
runProcess(process, progressIndicator);
}
catch (ProcessCanceledException e) {
processCanceled = true;
}
catch (Exception e) {
exception = e;
}
final boolean finalCanceled = processCanceled || progressIndicator.isCanceled();
final Exception finalException = exception;
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
finishTask(task, finalCanceled, finalException);
}
}, modalityState);
}
};
return ApplicationManager.getApplication().executeOnPooledThread(action);
}
public boolean runProcessWithProgressSynchronously(@NotNull final Task task, @Nullable final JComponent parentComponent) {
final Ref<Exception> exceptionRef = new Ref<Exception>();
TaskContainer taskContainer = new TaskContainer(task) {
@Override
public void run() {
try {
new TaskRunnable(task, getProgressIndicator()).run();
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception e) {
exceptionRef.set(e);
}
}
};
ApplicationEx application = (ApplicationEx)ApplicationManager.getApplication();
boolean result = application.runProcessWithProgressSynchronously(taskContainer, task.getTitle(), task.isCancellable(),
task.getProject(), parentComponent, task.getCancelText());
finishTask(task, !result, exceptionRef.get());
return result;
}
public void runProcessWithProgressInCurrentThread(@NotNull final Task task,
@NotNull final ProgressIndicator progressIndicator,
@NotNull final ModalityState modalityState) {
if (progressIndicator instanceof Disposable) {
Disposer.register(ApplicationManager.getApplication(), (Disposable)progressIndicator);
}
final Runnable process = new TaskRunnable(task, progressIndicator);
boolean processCanceled = false;
Exception exception = null;
try {
runProcess(process, progressIndicator);
}
catch (ProcessCanceledException e) {
processCanceled = true;
}
catch (Exception e) {
exception = e;
}
final boolean finalCanceled = processCanceled || progressIndicator.isCanceled();
final Exception finalException = exception;
if (ApplicationManager.getApplication().isDispatchThread()) {
finishTask(task, finalCanceled, finalException);
}
else {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
finishTask(task, finalCanceled, finalException);
}
}, modalityState);
}
}
static void finishTask(@NotNull Task task, boolean canceled, @Nullable Exception exception) {
try {
if (exception != null) {
task.onError(exception);
}
else if (canceled) {
task.onCancel();
}
else {
task.onSuccess();
}
}
finally {
task.onFinished();
}
}
@Override
public void runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task, @NotNull ProgressIndicator progressIndicator) {
runProcessWithProgressAsynchronously(task, progressIndicator, null);
}
@Override
public ProgressIndicator getProgressIndicator() {
return getCurrentIndicator(Thread.currentThread());
}
@Override
public void executeProcessUnderProgress(@NotNull Runnable process, ProgressIndicator progress) throws ProcessCanceledException {
boolean modal = progress != null && progress.isModal();
if (modal) myCurrentModalProgressCount.incrementAndGet();
if (progress == null) myCurrentUnsafeProgressCount.incrementAndGet();
try {
ProgressIndicator oldIndicator = null;
boolean set = progress != null && progress != (oldIndicator = getProgressIndicator());
if (set) {
Thread currentThread = Thread.currentThread();
setCurrentIndicator(currentThread, progress);
try {
registerIndicatorAndRun(progress, currentThread, oldIndicator, process);
}
finally {
setCurrentIndicator(currentThread, oldIndicator);
}
}
else {
process.run();
}
}
finally {
if (progress == null) myCurrentUnsafeProgressCount.decrementAndGet();
if (modal) myCurrentModalProgressCount.decrementAndGet();
}
}
private void registerIndicatorAndRun(@NotNull ProgressIndicator indicator,
@NotNull Thread currentThread,
ProgressIndicator oldIndicator,
@NotNull Runnable process) {
List<Set<Thread>> threadsUnderThisIndicator = new ArrayList<Set<Thread>>();
synchronized (threadsUnderIndicator) {
for (ProgressIndicator thisIndicator = indicator; thisIndicator != null; thisIndicator = thisIndicator instanceof WrappedProgressIndicator ? ((WrappedProgressIndicator)thisIndicator).getOriginalProgressIndicator() : null) {
Set<Thread> underIndicator = threadsUnderIndicator.get(thisIndicator);
if (underIndicator == null) {
underIndicator = new SmartHashSet<Thread>();
threadsUnderIndicator.put(thisIndicator, underIndicator);
}
boolean alreadyUnder = !underIndicator.add(currentThread);
threadsUnderThisIndicator.add(alreadyUnder ? null : underIndicator);
boolean isStandard = thisIndicator instanceof StandardProgressIndicator;
if (!isStandard) {
nonStandardIndicators.add(thisIndicator);
startBackgroundNonStandardIndicatorsPing();
}
if (thisIndicator.isCanceled()) {
threadsUnderCanceledIndicator.add(currentThread);
}
else {
threadsUnderCanceledIndicator.remove(currentThread);
}
}
updateShouldCheckCanceled();
}
try {
process.run();
}
finally {
synchronized (threadsUnderIndicator) {
ProgressIndicator thisIndicator = null;
// order doesn't matter
for (int i = 0; i < threadsUnderThisIndicator.size(); i++) {
thisIndicator = i == 0 ? indicator : ((WrappedProgressIndicator)thisIndicator).getOriginalProgressIndicator();
Set<Thread> underIndicator = threadsUnderThisIndicator.get(i);
boolean removed = underIndicator != null && underIndicator.remove(currentThread);
if (removed && underIndicator.isEmpty()) {
threadsUnderIndicator.remove(thisIndicator);
}
boolean isStandard = thisIndicator instanceof StandardProgressIndicator;
if (!isStandard) {
nonStandardIndicators.remove(thisIndicator);
if (nonStandardIndicators.isEmpty()) {
stopBackgroundNonStandardIndicatorsPing();
}
}
// by this time oldIndicator may have been canceled
if (oldIndicator != null && oldIndicator.isCanceled()) {
threadsUnderCanceledIndicator.add(currentThread);
}
else {
threadsUnderCanceledIndicator.remove(currentThread);
}
}
updateShouldCheckCanceled();
}
}
}
private static void updateShouldCheckCanceled() {
ourMaySleepInCheckCanceled = Registry.is("ide.prioritize.ui.thread", false);
if (ourMaySleepInCheckCanceled && HeavyProcessLatch.INSTANCE.hasPrioritizedThread()) {
shouldCheckCanceled = true;
return;
}
synchronized (threadsUnderIndicator) {
shouldCheckCanceled = !threadsUnderCanceledIndicator.isEmpty();
}
}
@Override
protected void indicatorCanceled(@NotNull ProgressIndicator indicator) {
// mark threads running under this indicator as canceled
synchronized (threadsUnderIndicator) {
Set<Thread> threads = threadsUnderIndicator.get(indicator);
if (threads != null) {
for (Thread thread : threads) {
boolean underCancelledIndicator = false;
for (ProgressIndicator currentIndicator = getCurrentIndicator(thread);
currentIndicator != null;
currentIndicator = currentIndicator instanceof WrappedProgressIndicator ?
((WrappedProgressIndicator)currentIndicator).getOriginalProgressIndicator() : null) {
if (currentIndicator == indicator) {
underCancelledIndicator = true;
break;
}
}
if (underCancelledIndicator) {
threadsUnderCanceledIndicator.add(thread);
//noinspection AssignmentToStaticFieldFromInstanceMethod
shouldCheckCanceled = true;
}
}
}
}
}
@TestOnly
public static boolean isCanceledThread(@NotNull Thread thread) {
return threadsUnderCanceledIndicator.contains(thread);
}
@NotNull
@Override
public final NonCancelableSection startNonCancelableSection() {
final ProgressIndicator myOld = getProgressIndicator();
final Thread currentThread = Thread.currentThread();
NonCancelableIndicator nonCancelor = new NonCancelableIndicator() {
@Override
public void done() {
setCurrentIndicator(currentThread, myOld);
}
};
setCurrentIndicator(currentThread, nonCancelor);
return nonCancelor;
}
private static void setCurrentIndicator(@NotNull Thread currentThread, ProgressIndicator indicator) {
if (indicator == null) {
currentIndicators.remove(currentThread.getId());
}
else {
currentIndicators.put(currentThread.getId(), indicator);
}
}
private static ProgressIndicator getCurrentIndicator(@NotNull Thread thread) {
return currentIndicators.get(thread.getId());
}
protected abstract static class TaskContainer implements Runnable {
private final Task myTask;
protected TaskContainer(@NotNull Task task) {
myTask = task;
}
@NotNull
public Task getTask() {
return myTask;
}
@Override
public String toString() {
return myTask.toString();
}
}
protected static class TaskRunnable extends TaskContainer {
private final ProgressIndicator myIndicator;
private final Runnable myContinuation;
public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator) {
this(task, indicator, null);
}
public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) {
super(task);
myIndicator = indicator;
myContinuation = continuation;
}
@Override
public void run() {
try {
getTask().run(myIndicator);
}
finally {
try {
if (myIndicator instanceof ProgressIndicatorEx) {
((ProgressIndicatorEx)myIndicator).finish(getTask());
}
}
finally {
if (myContinuation != null) {
myContinuation.run();
}
}
}
}
}
}
|
ProgressManager: use defaultModalityState for callbacks
|
platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java
|
ProgressManager: use defaultModalityState for callbacks
|
<ide><path>latform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java
<ide> runProcessWithProgressSynchronously(task, null);
<ide> }
<ide> else {
<del> runProcessWithProgressInCurrentThread(task, new EmptyProgressIndicator(), ModalityState.NON_MODAL);
<add> runProcessWithProgressInCurrentThread(task, new EmptyProgressIndicator(), ModalityState.defaultModalityState());
<ide> }
<ide> }
<ide> else if (task.isModal()) {
<ide> runnable.run();
<ide> }
<ide> else {
<del> ApplicationManager.getApplication().invokeAndWait(runnable, ModalityState.NON_MODAL);
<add> ApplicationManager.getApplication().invokeAndWait(runnable, ModalityState.defaultModalityState());
<ide> }
<ide> }
<ide>
<ide> runnable.run();
<ide> }
<ide> else {
<del> ApplicationManager.getApplication().invokeLater(runnable, ModalityState.NON_MODAL);
<add> ApplicationManager.getApplication().invokeLater(runnable, ModalityState.defaultModalityState());
<ide> }
<ide> }
<ide>
<ide> public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task,
<ide> @NotNull final ProgressIndicator progressIndicator,
<ide> @Nullable final Runnable continuation) {
<del> return runProcessWithProgressAsynchronously(task, progressIndicator, continuation, ModalityState.NON_MODAL);
<add> return runProcessWithProgressAsynchronously(task, progressIndicator, continuation, ModalityState.defaultModalityState());
<ide> }
<ide>
<ide> @NotNull
|
|
Java
|
lgpl-2.1
|
7500bcd2b938baaa766405fd023c1bda25a57d7b
| 0 |
kluver/lenskit,kluver/lenskit,vaibhav345/lenskit,vaibhav345/lenskit,kluver/lenskit,vaibhav345/lenskit,kluver/lenskit,kluver/lenskit,vaibhav345/lenskit
|
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2016 LensKit Contributors. See CONTRIBUTORS.md.
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.lenskit.knn.user;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import it.unimi.dsi.fastutil.longs.*;
import org.grouplens.lenskit.transform.threshold.Threshold;
import org.lenskit.api.Result;
import org.lenskit.api.ResultMap;
import org.lenskit.basic.AbstractItemScorer;
import org.lenskit.data.ratings.RatingVectorPDAO;
import org.lenskit.knn.MinNeighbors;
import org.lenskit.knn.NeighborhoodSize;
import org.lenskit.results.Results;
import org.lenskit.transform.normalize.UserVectorNormalizer;
import org.lenskit.util.InvertibleFunction;
import org.lenskit.util.collections.LongUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.PriorityQueue;
import static java.lang.Math.abs;
/**
* Score items with user-user collaborative filtering.
*
* The detailed results returned by this scorer are of type {@link UserUserResult}.
*/
public class UserUserItemScorer extends AbstractItemScorer {
private static final Logger logger = LoggerFactory.getLogger(UserUserItemScorer.class);
private final RatingVectorPDAO dao;
protected final NeighborFinder neighborFinder;
protected final UserVectorNormalizer normalizer;
private final int neighborhoodSize;
private final int minNeighborCount;
private final Threshold userThreshold;
@Inject
public UserUserItemScorer(RatingVectorPDAO rvd, NeighborFinder nf,
UserVectorNormalizer norm,
@NeighborhoodSize int nnbrs,
@MinNeighbors int minNbrs,
@UserSimilarityThreshold Threshold thresh) {
this.dao = rvd;
neighborFinder = nf;
normalizer = norm;
neighborhoodSize = nnbrs;
minNeighborCount = minNbrs;
userThreshold = thresh;
}
/**
* Normalize all neighbor rating vectors, taking care to normalize each one
* only once.
*
* FIXME: MDE does not like this method.
*
* @param neighborhoods The neighborhoods to search.
*/
protected Long2ObjectMap<Long2DoubleMap> normalizeNeighborRatings(Collection<? extends Collection<Neighbor>> neighborhoods) {
Long2ObjectMap<Long2DoubleMap> normedVectors =
new Long2ObjectOpenHashMap<>();
for (Neighbor n : Iterables.<Neighbor>concat(neighborhoods)) {
if (!normedVectors.containsKey(n.user)) {
normedVectors.put(n.user, normalizer.makeTransformation(n.user, n.vector).apply(n.vector));
}
}
return normedVectors;
}
@Nonnull
@Override
public ResultMap scoreWithDetails(long user, @Nonnull Collection<Long> items) {
Long2DoubleMap history = dao.userRatingVector(user);
logger.debug("Predicting for {} items for user {} with {} events",
items.size(), user, history.size());
LongSortedSet itemSet = LongUtils.packedSet(items);
Long2ObjectMap<? extends Collection<Neighbor>> neighborhoods =
findNeighbors(user, itemSet);
Long2ObjectMap<Long2DoubleMap> normedUsers =
normalizeNeighborRatings(neighborhoods.values());
// Make the normalizing transform to reverse
InvertibleFunction<Long2DoubleMap, Long2DoubleMap> xform = normalizer.makeTransformation(user, history);
// And prepare results
List<ResultBuilder> resultBuilders = new ArrayList<>();
LongIterator iter = itemSet.iterator();
while (iter.hasNext()) {
final long item = iter.nextLong();
double sum = 0;
double weight = 0;
int count = 0;
Collection<Neighbor> nbrs = neighborhoods.get(item);
if (nbrs != null) {
for (Neighbor n : nbrs) {
weight += abs(n.similarity);
sum += n.similarity * normedUsers.get(n.user).get(item);
count += 1;
}
}
if (count >= minNeighborCount && weight > 0) {
if (logger.isTraceEnabled()) {
logger.trace("Total neighbor weight for item {} is {} from {} neighbors",
item, weight, count);
}
resultBuilders.add(UserUserResult.newBuilder()
.setItemId(item)
.setRawScore(sum / weight)
.setNeighborhoodSize(count)
.setTotalWeight(weight));
}
}
// de-normalize the results
Long2DoubleMap itemScores = new Long2DoubleOpenHashMap(resultBuilders.size());
for (ResultBuilder rb: resultBuilders) {
itemScores.put(rb.getItemId(), rb.getRawScore());
}
itemScores = xform.unapply(itemScores);
// and finish up
List<Result> results = new ArrayList<>(resultBuilders.size());
for (ResultBuilder rb: resultBuilders) {
results.add(rb.setScore(itemScores.get(rb.getItemId()))
.build());
}
return Results.newResultMap(results);
}
/**
* Find the neighbors for a user with respect to a collection of items.
* For each item, the <var>neighborhoodSize</var> users closest to the
* provided user are returned.
*
* @param user The user's rating vector.
* @param items The items for which neighborhoods are requested.
* @return A mapping of item IDs to neighborhoods.
*/
protected Long2ObjectMap<? extends Collection<Neighbor>>
findNeighbors(long user, @Nonnull LongSet items) {
Preconditions.checkNotNull(user, "user profile");
Preconditions.checkNotNull(user, "item set");
Long2ObjectMap<PriorityQueue<Neighbor>> heaps = new Long2ObjectOpenHashMap<>(items.size());
for (LongIterator iter = items.iterator(); iter.hasNext();) {
long item = iter.nextLong();
heaps.put(item, new PriorityQueue<>(neighborhoodSize + 1,
Neighbor.SIMILARITY_COMPARATOR));
}
int neighborsUsed = 0;
for (Neighbor nbr: neighborFinder.getCandidateNeighbors(user, items)) {
// TODO consider optimizing
for (Long2DoubleMap.Entry e: nbr.vector.long2DoubleEntrySet()) {
final long item = e.getLongKey();
PriorityQueue<Neighbor> heap = heaps.get(item);
if (heap != null) {
heap.add(nbr);
if (heap.size() > neighborhoodSize) {
assert heap.size() == neighborhoodSize + 1;
heap.remove();
} else {
neighborsUsed += 1;
}
}
}
}
logger.debug("using {} neighbors across {} items",
neighborsUsed, items.size());
return heaps;
}
}
|
lenskit-knn/src/main/java/org/lenskit/knn/user/UserUserItemScorer.java
|
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2016 LensKit Contributors. See CONTRIBUTORS.md.
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* 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 General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.lenskit.knn.user;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import it.unimi.dsi.fastutil.longs.*;
import org.grouplens.lenskit.transform.threshold.Threshold;
import org.lenskit.api.Result;
import org.lenskit.api.ResultMap;
import org.lenskit.basic.AbstractItemScorer;
import org.lenskit.data.ratings.RatingVectorPDAO;
import org.lenskit.knn.MinNeighbors;
import org.lenskit.knn.NeighborhoodSize;
import org.lenskit.results.Results;
import org.lenskit.transform.normalize.UserVectorNormalizer;
import org.lenskit.util.InvertibleFunction;
import org.lenskit.util.collections.LongUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.PriorityQueue;
import static java.lang.Math.abs;
/**
* Score items with user-user collaborative filtering.
*
* The detailed results returned by this scorer are of type {@link UserUserResult}.
*/
public class UserUserItemScorer extends AbstractItemScorer {
private static final Logger logger = LoggerFactory.getLogger(UserUserItemScorer.class);
private final RatingVectorPDAO dao;
protected final NeighborFinder neighborFinder;
protected final UserVectorNormalizer normalizer;
private final int neighborhoodSize;
private final int minNeighborCount;
private final Threshold userThreshold;
@Inject
public UserUserItemScorer(RatingVectorPDAO rvd, NeighborFinder nf,
UserVectorNormalizer norm,
@NeighborhoodSize int nnbrs,
@MinNeighbors int minNbrs,
@UserSimilarityThreshold Threshold thresh) {
this.dao = rvd;
neighborFinder = nf;
normalizer = norm;
neighborhoodSize = nnbrs;
minNeighborCount = minNbrs;
userThreshold = thresh;
}
/**
* Normalize all neighbor rating vectors, taking care to normalize each one
* only once.
*
* FIXME: MDE does not like this method.
*
* @param neighborhoods The neighborhoods to search.
*/
protected Long2ObjectMap<Long2DoubleMap> normalizeNeighborRatings(Collection<? extends Collection<Neighbor>> neighborhoods) {
Long2ObjectMap<Long2DoubleMap> normedVectors =
new Long2ObjectOpenHashMap<>();
for (Neighbor n : Iterables.concat(neighborhoods)) {
if (!normedVectors.containsKey(n.user)) {
normedVectors.put(n.user, normalizer.makeTransformation(n.user, n.vector).apply(n.vector));
}
}
return normedVectors;
}
@Nonnull
@Override
public ResultMap scoreWithDetails(long user, @Nonnull Collection<Long> items) {
Long2DoubleMap history = dao.userRatingVector(user);
logger.debug("Predicting for {} items for user {} with {} events",
items.size(), user, history.size());
LongSortedSet itemSet = LongUtils.packedSet(items);
Long2ObjectMap<? extends Collection<Neighbor>> neighborhoods =
findNeighbors(user, itemSet);
Long2ObjectMap<Long2DoubleMap> normedUsers =
normalizeNeighborRatings(neighborhoods.values());
// Make the normalizing transform to reverse
InvertibleFunction<Long2DoubleMap, Long2DoubleMap> xform = normalizer.makeTransformation(user, history);
// And prepare results
List<ResultBuilder> resultBuilders = new ArrayList<>();
LongIterator iter = itemSet.iterator();
while (iter.hasNext()) {
final long item = iter.nextLong();
double sum = 0;
double weight = 0;
int count = 0;
Collection<Neighbor> nbrs = neighborhoods.get(item);
if (nbrs != null) {
for (Neighbor n : nbrs) {
weight += abs(n.similarity);
sum += n.similarity * normedUsers.get(n.user).get(item);
count += 1;
}
}
if (count >= minNeighborCount && weight > 0) {
if (logger.isTraceEnabled()) {
logger.trace("Total neighbor weight for item {} is {} from {} neighbors",
item, weight, count);
}
resultBuilders.add(UserUserResult.newBuilder()
.setItemId(item)
.setRawScore(sum / weight)
.setNeighborhoodSize(count)
.setTotalWeight(weight));
}
}
// de-normalize the results
Long2DoubleMap itemScores = new Long2DoubleOpenHashMap(resultBuilders.size());
for (ResultBuilder rb: resultBuilders) {
itemScores.put(rb.getItemId(), rb.getRawScore());
}
itemScores = xform.unapply(itemScores);
// and finish up
List<Result> results = new ArrayList<>(resultBuilders.size());
for (ResultBuilder rb: resultBuilders) {
results.add(rb.setScore(itemScores.get(rb.getItemId()))
.build());
}
return Results.newResultMap(results);
}
/**
* Find the neighbors for a user with respect to a collection of items.
* For each item, the <var>neighborhoodSize</var> users closest to the
* provided user are returned.
*
* @param user The user's rating vector.
* @param items The items for which neighborhoods are requested.
* @return A mapping of item IDs to neighborhoods.
*/
protected Long2ObjectMap<? extends Collection<Neighbor>>
findNeighbors(long user, @Nonnull LongSet items) {
Preconditions.checkNotNull(user, "user profile");
Preconditions.checkNotNull(user, "item set");
Long2ObjectMap<PriorityQueue<Neighbor>> heaps = new Long2ObjectOpenHashMap<>(items.size());
for (LongIterator iter = items.iterator(); iter.hasNext();) {
long item = iter.nextLong();
heaps.put(item, new PriorityQueue<>(neighborhoodSize + 1,
Neighbor.SIMILARITY_COMPARATOR));
}
int neighborsUsed = 0;
for (Neighbor nbr: neighborFinder.getCandidateNeighbors(user, items)) {
// TODO consider optimizing
for (Long2DoubleMap.Entry e: nbr.vector.long2DoubleEntrySet()) {
final long item = e.getLongKey();
PriorityQueue<Neighbor> heap = heaps.get(item);
if (heap != null) {
heap.add(nbr);
if (heap.size() > neighborhoodSize) {
assert heap.size() == neighborhoodSize + 1;
heap.remove();
} else {
neighborsUsed += 1;
}
}
}
}
logger.debug("using {} neighbors across {} items",
neighborsUsed, items.size());
return heaps;
}
}
|
Fix IntelliJ error in user-user item scorer
|
lenskit-knn/src/main/java/org/lenskit/knn/user/UserUserItemScorer.java
|
Fix IntelliJ error in user-user item scorer
|
<ide><path>enskit-knn/src/main/java/org/lenskit/knn/user/UserUserItemScorer.java
<ide> protected Long2ObjectMap<Long2DoubleMap> normalizeNeighborRatings(Collection<? extends Collection<Neighbor>> neighborhoods) {
<ide> Long2ObjectMap<Long2DoubleMap> normedVectors =
<ide> new Long2ObjectOpenHashMap<>();
<del> for (Neighbor n : Iterables.concat(neighborhoods)) {
<add> for (Neighbor n : Iterables.<Neighbor>concat(neighborhoods)) {
<ide> if (!normedVectors.containsKey(n.user)) {
<ide> normedVectors.put(n.user, normalizer.makeTransformation(n.user, n.vector).apply(n.vector));
<ide> }
|
|
Java
|
apache-2.0
|
1a424362d47f1cd1c4240f11bf411c8e8115e9fc
| 0 |
phax/ph-commons
|
/**
* Copyright (C) 2014-2016 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.commons.ws;
import java.net.URL;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.OverridingMethodsMustInvokeSuper;
import javax.annotation.concurrent.NotThreadSafe;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.OverrideOnDemand;
import com.helger.commons.lang.ClassLoaderHelper;
/**
* Abstract base class for a webservice client caller.
*
* @author Philip Helger
*/
@NotThreadSafe
public abstract class AbstractWSClientCaller
{
public static final int DEFAULT_CONNECTION_TIMEOUT_MS = 5000;
public static final int DEFAULT_REQUEST_TIMEOUT_MS = 5000;
private static final Logger s_aLogger = LoggerFactory.getLogger (AbstractWSClientCaller.class);
private final URL m_aEndpointAddress;
private SSLSocketFactory m_aSSLSocketFactory;
private HostnameVerifier m_aHostnameVerifier;
private int m_nConnectionTimeoutMS = DEFAULT_CONNECTION_TIMEOUT_MS;
private int m_nRequestTimeoutMS = DEFAULT_REQUEST_TIMEOUT_MS;
private boolean m_bWorkAroundMASM0003 = true;
/**
* Creates a service caller for the service meta data interface
*
* @param aEndpointAddress
* The address of the SML management interface. May not be
* <code>null</code>.
*/
public AbstractWSClientCaller (@Nonnull final URL aEndpointAddress)
{
ValueEnforcer.notNull (aEndpointAddress, "EndpointAddress");
m_aEndpointAddress = aEndpointAddress;
if (s_aLogger.isDebugEnabled ())
s_aLogger.debug ("Using SML endpoint address '" + m_aEndpointAddress.toExternalForm () + "'");
}
/**
* @return The endpoint address as specified in the constructor. Never
* <code>null</code>.
*/
@Nonnull
public URL getEndpointAddress ()
{
return m_aEndpointAddress;
}
/**
* @return The {@link SSLSocketFactory} to be used by this client. Is
* <code>null</code> by default.
*/
@Nullable
public SSLSocketFactory getSSLSocketFactory ()
{
return m_aSSLSocketFactory;
}
/**
* Change the {@link SSLSocketFactory} to be used by this client.
*
* @param aSSLSocketFactory
* The factory to use. Maybe <code>null</code> to indicate, that the
* default {@link SSLSocketFactory} is to be used.
*/
public void setSSLSocketFactory (@Nullable final SSLSocketFactory aSSLSocketFactory)
{
m_aSSLSocketFactory = aSSLSocketFactory;
}
/**
* @return The {@link HostnameVerifier} to be used by this client. Is
* <code>null</code> by default.
*/
@Nullable
public HostnameVerifier getHostnameVerifier ()
{
return m_aHostnameVerifier;
}
/**
* Change the {@link HostnameVerifier} to be used by this client.
*
* @param aHostnameVerifier
* The factory to use. Maybe <code>null</code> to indicate, that the
* default {@link HostnameVerifier} is to be used.
*/
public void setHostnameVerifier (@Nullable final HostnameVerifier aHostnameVerifier)
{
m_aHostnameVerifier = aHostnameVerifier;
}
/**
* @return The connection timeout in milliseconds.
*/
public int getConnectionTimeoutMS ()
{
return m_nConnectionTimeoutMS;
}
/**
* Set the connection timeout in milliseconds.
*
* @param nConnectionTimeoutMS
* Milliseconds. Only values ≥ 0 are considered.
*/
public void setConnectionTimeoutMS (final int nConnectionTimeoutMS)
{
m_nConnectionTimeoutMS = nConnectionTimeoutMS;
}
/**
* @return The request timeout in milliseconds.
*/
public int getRequestTimeoutMS ()
{
return m_nRequestTimeoutMS;
}
/**
* Set the request timeout in milliseconds.
*
* @param nRequestTimeoutMS
* Milliseconds. Only values ≥ 0 are considered.
*/
public void setRequestTimeoutMS (final int nRequestTimeoutMS)
{
m_nRequestTimeoutMS = nRequestTimeoutMS;
}
/**
* Implement this method in your derived class to add custom handlers.
*
* @param aHandlerList
* The handler list to be filled. Never <code>null</code>.
*/
@OverrideOnDemand
@SuppressWarnings ("rawtypes")
protected void addHandlers (@Nonnull final List <Handler> aHandlerList)
{}
protected final boolean isWorkAroundMASM0003 ()
{
return m_bWorkAroundMASM0003;
}
protected final void setWorkAroundMASM0003 (final boolean bWorkAroundMASM0003)
{
m_bWorkAroundMASM0003 = bWorkAroundMASM0003;
}
@OverrideOnDemand
@OverridingMethodsMustInvokeSuper
protected void applyWSSettingsToBindingProvider (@Nonnull final BindingProvider aBP)
{
aBP.getRequestContext ().put (BindingProvider.ENDPOINT_ADDRESS_PROPERTY, m_aEndpointAddress.toString ());
if (m_aSSLSocketFactory != null)
{
aBP.getRequestContext ().put ("com.sun.xml.ws.transport.https.client.SSLSocketFactory", m_aSSLSocketFactory);
aBP.getRequestContext ().put ("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
m_aSSLSocketFactory);
}
if (m_aHostnameVerifier != null)
{
aBP.getRequestContext ().put ("com.sun.xml.ws.transport.https.client.hostname.verifier", m_aHostnameVerifier);
aBP.getRequestContext ().put ("com.sun.xml.internal.ws.transport.https.client.hostname.verifier",
m_aHostnameVerifier);
}
if (m_nConnectionTimeoutMS >= 0)
{
aBP.getRequestContext ().put ("com.sun.xml.ws.connect.timeout", Integer.valueOf (m_nConnectionTimeoutMS));
aBP.getRequestContext ().put ("com.sun.xml.internal.ws.connect.timeout",
Integer.valueOf (m_nConnectionTimeoutMS));
}
if (m_nRequestTimeoutMS >= 0)
{
aBP.getRequestContext ().put ("com.sun.xml.ws.request.timeout", Integer.valueOf (m_nRequestTimeoutMS));
aBP.getRequestContext ().put ("com.sun.xml.internal.ws.request.timeout", Integer.valueOf (m_nRequestTimeoutMS));
}
@SuppressWarnings ("rawtypes")
final List <Handler> aHandlers = aBP.getBinding ().getHandlerChain ();
// Fill handlers
addHandlers (aHandlers);
aBP.getBinding ().setHandlerChain (aHandlers);
if (m_bWorkAroundMASM0003)
{
// Introduced with Java 1.8.0_31??
// MASM0003: Default [ jaxws-tubes-default.xml ] configuration file was
// not loaded
final ClassLoader aContextClassLoader = ClassLoaderHelper.getContextClassLoader ();
final ClassLoader aThisClassLoader = getClass ().getClassLoader ();
if (aContextClassLoader == null)
{
s_aLogger.info ("Manually setting thread context class loader to work around MASM0003 bug");
ClassLoaderHelper.setContextClassLoader (aThisClassLoader);
}
else
{
if (aContextClassLoader != aThisClassLoader)
{
s_aLogger.warn ("Manually overriding thread context class loader to work around MASM0003 bug");
ClassLoaderHelper.setContextClassLoader (aThisClassLoader);
}
}
}
}
}
|
ph-commons/src/main/java/com/helger/commons/ws/AbstractWSClientCaller.java
|
/**
* Copyright (C) 2014-2016 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.commons.ws;
import java.net.URL;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.OverridingMethodsMustInvokeSuper;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.OverrideOnDemand;
/**
* Abstract base class for a webservice client caller.
*
* @author Philip Helger
*/
public abstract class AbstractWSClientCaller
{
public static final int DEFAULT_CONNECTION_TIMEOUT_MS = 5000;
public static final int DEFAULT_REQUEST_TIMEOUT_MS = 5000;
private static final Logger s_aLogger = LoggerFactory.getLogger (AbstractWSClientCaller.class);
private final URL m_aEndpointAddress;
private SSLSocketFactory m_aSSLSocketFactory;
private HostnameVerifier m_aHostnameVerifier;
private int m_nConnectionTimeoutMS = DEFAULT_CONNECTION_TIMEOUT_MS;
private int m_nRequestTimeoutMS = DEFAULT_REQUEST_TIMEOUT_MS;
/**
* Creates a service caller for the service meta data interface
*
* @param aEndpointAddress
* The address of the SML management interface. May not be
* <code>null</code>.
*/
public AbstractWSClientCaller (@Nonnull final URL aEndpointAddress)
{
ValueEnforcer.notNull (aEndpointAddress, "EndpointAddress");
m_aEndpointAddress = aEndpointAddress;
if (s_aLogger.isDebugEnabled ())
s_aLogger.debug ("Using SML endpoint address '" + m_aEndpointAddress.toExternalForm () + "'");
}
/**
* @return The endpoint address as specified in the constructor. Never
* <code>null</code>.
*/
@Nonnull
public URL getEndpointAddress ()
{
return m_aEndpointAddress;
}
/**
* @return The {@link SSLSocketFactory} to be used by this client. Is
* <code>null</code> by default.
*/
@Nullable
public SSLSocketFactory getSSLSocketFactory ()
{
return m_aSSLSocketFactory;
}
/**
* Change the {@link SSLSocketFactory} to be used by this client.
*
* @param aSSLSocketFactory
* The factory to use. Maybe <code>null</code> to indicate, that the
* default {@link SSLSocketFactory} is to be used.
*/
public void setSSLSocketFactory (@Nullable final SSLSocketFactory aSSLSocketFactory)
{
m_aSSLSocketFactory = aSSLSocketFactory;
}
/**
* @return The {@link HostnameVerifier} to be used by this client. Is
* <code>null</code> by default.
*/
@Nullable
public HostnameVerifier getHostnameVerifier ()
{
return m_aHostnameVerifier;
}
/**
* Change the {@link HostnameVerifier} to be used by this client.
*
* @param aHostnameVerifier
* The factory to use. Maybe <code>null</code> to indicate, that the
* default {@link HostnameVerifier} is to be used.
*/
public void setHostnameVerifier (@Nullable final HostnameVerifier aHostnameVerifier)
{
m_aHostnameVerifier = aHostnameVerifier;
}
/**
* @return The connection timeout in milliseconds.
*/
public int getConnectionTimeoutMS ()
{
return m_nConnectionTimeoutMS;
}
/**
* Set the connection timeout in milliseconds.
*
* @param nConnectionTimeoutMS
* Milliseconds. Only values ≥ 0 are considered.
*/
public void setConnectionTimeoutMS (final int nConnectionTimeoutMS)
{
m_nConnectionTimeoutMS = nConnectionTimeoutMS;
}
/**
* @return The request timeout in milliseconds.
*/
public int getRequestTimeoutMS ()
{
return m_nRequestTimeoutMS;
}
/**
* Set the request timeout in milliseconds.
*
* @param nRequestTimeoutMS
* Milliseconds. Only values ≥ 0 are considered.
*/
public void setRequestTimeoutMS (final int nRequestTimeoutMS)
{
m_nRequestTimeoutMS = nRequestTimeoutMS;
}
/**
* Implement this method in your derived class to add custom handlers.
*
* @param aHandlerList
* The handler list to be filled. Never <code>null</code>.
*/
@OverrideOnDemand
@SuppressWarnings ("rawtypes")
protected void addHandlers (@Nonnull final List <Handler> aHandlerList)
{}
@OverrideOnDemand
@OverridingMethodsMustInvokeSuper
protected void applyWSSettingsToBindingProvider (@Nonnull final BindingProvider aBP)
{
aBP.getRequestContext ().put (BindingProvider.ENDPOINT_ADDRESS_PROPERTY, m_aEndpointAddress.toString ());
if (m_aSSLSocketFactory != null)
{
aBP.getRequestContext ().put ("com.sun.xml.ws.transport.https.client.SSLSocketFactory", m_aSSLSocketFactory);
aBP.getRequestContext ().put ("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
m_aSSLSocketFactory);
}
if (m_aHostnameVerifier != null)
{
aBP.getRequestContext ().put ("com.sun.xml.ws.transport.https.client.hostname.verifier", m_aHostnameVerifier);
aBP.getRequestContext ().put ("com.sun.xml.internal.ws.transport.https.client.hostname.verifier",
m_aHostnameVerifier);
}
if (m_nConnectionTimeoutMS >= 0)
{
aBP.getRequestContext ().put ("com.sun.xml.ws.connect.timeout", Integer.valueOf (m_nConnectionTimeoutMS));
aBP.getRequestContext ().put ("com.sun.xml.internal.ws.connect.timeout",
Integer.valueOf (m_nConnectionTimeoutMS));
}
if (m_nRequestTimeoutMS >= 0)
{
aBP.getRequestContext ().put ("com.sun.xml.ws.request.timeout", Integer.valueOf (m_nRequestTimeoutMS));
aBP.getRequestContext ().put ("com.sun.xml.internal.ws.request.timeout", Integer.valueOf (m_nRequestTimeoutMS));
}
@SuppressWarnings ("rawtypes")
final List <Handler> aHandlers = aBP.getBinding ().getHandlerChain ();
// Fill handlers
addHandlers (aHandlers);
aBP.getBinding ().setHandlerChain (aHandlers);
if (Thread.currentThread ().getContextClassLoader () == null)
{
// Introduced with Java 1.8.0_31??
// MASM0003: Default [ jaxws-tubes-default.xml ] configuration file was
// not loaded
s_aLogger.info ("Manually setting thread context class loader to work around MASM0003 bug");
Thread.currentThread ().setContextClassLoader (getClass ().getClassLoader ());
}
}
}
|
Made MASM0003 work around configurable
|
ph-commons/src/main/java/com/helger/commons/ws/AbstractWSClientCaller.java
|
Made MASM0003 work around configurable
|
<ide><path>h-commons/src/main/java/com/helger/commons/ws/AbstractWSClientCaller.java
<ide> import javax.annotation.Nonnull;
<ide> import javax.annotation.Nullable;
<ide> import javax.annotation.OverridingMethodsMustInvokeSuper;
<add>import javax.annotation.concurrent.NotThreadSafe;
<ide> import javax.net.ssl.HostnameVerifier;
<ide> import javax.net.ssl.SSLSocketFactory;
<ide> import javax.xml.ws.BindingProvider;
<ide>
<ide> import com.helger.commons.ValueEnforcer;
<ide> import com.helger.commons.annotation.OverrideOnDemand;
<add>import com.helger.commons.lang.ClassLoaderHelper;
<ide>
<ide> /**
<ide> * Abstract base class for a webservice client caller.
<ide> *
<ide> * @author Philip Helger
<ide> */
<add>@NotThreadSafe
<ide> public abstract class AbstractWSClientCaller
<ide> {
<ide> public static final int DEFAULT_CONNECTION_TIMEOUT_MS = 5000;
<ide> private int m_nConnectionTimeoutMS = DEFAULT_CONNECTION_TIMEOUT_MS;
<ide> private int m_nRequestTimeoutMS = DEFAULT_REQUEST_TIMEOUT_MS;
<ide>
<add> private boolean m_bWorkAroundMASM0003 = true;
<add>
<ide> /**
<ide> * Creates a service caller for the service meta data interface
<ide> *
<ide> @SuppressWarnings ("rawtypes")
<ide> protected void addHandlers (@Nonnull final List <Handler> aHandlerList)
<ide> {}
<add>
<add> protected final boolean isWorkAroundMASM0003 ()
<add> {
<add> return m_bWorkAroundMASM0003;
<add> }
<add>
<add> protected final void setWorkAroundMASM0003 (final boolean bWorkAroundMASM0003)
<add> {
<add> m_bWorkAroundMASM0003 = bWorkAroundMASM0003;
<add> }
<ide>
<ide> @OverrideOnDemand
<ide> @OverridingMethodsMustInvokeSuper
<ide> addHandlers (aHandlers);
<ide> aBP.getBinding ().setHandlerChain (aHandlers);
<ide>
<del> if (Thread.currentThread ().getContextClassLoader () == null)
<add> if (m_bWorkAroundMASM0003)
<ide> {
<ide> // Introduced with Java 1.8.0_31??
<ide> // MASM0003: Default [ jaxws-tubes-default.xml ] configuration file was
<ide> // not loaded
<del> s_aLogger.info ("Manually setting thread context class loader to work around MASM0003 bug");
<del> Thread.currentThread ().setContextClassLoader (getClass ().getClassLoader ());
<add> final ClassLoader aContextClassLoader = ClassLoaderHelper.getContextClassLoader ();
<add> final ClassLoader aThisClassLoader = getClass ().getClassLoader ();
<add> if (aContextClassLoader == null)
<add> {
<add> s_aLogger.info ("Manually setting thread context class loader to work around MASM0003 bug");
<add> ClassLoaderHelper.setContextClassLoader (aThisClassLoader);
<add> }
<add> else
<add> {
<add> if (aContextClassLoader != aThisClassLoader)
<add> {
<add> s_aLogger.warn ("Manually overriding thread context class loader to work around MASM0003 bug");
<add> ClassLoaderHelper.setContextClassLoader (aThisClassLoader);
<add> }
<add> }
<ide> }
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
c4732fb2ba4d43c45e953f91be0ea5fe7d2770b5
| 0 |
cltl/kaflib,antske/kaflib,ixa-ehu/kaflib,antske/kaflib,ixa-ehu/kaflib,cltl/kaflib
|
package ixa.kaflib;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Comment;
import org.jdom2.Namespace;
import org.jdom2.CDATA;
import org.jdom2.output.XMLOutputter;
import org.jdom2.output.Format;
import org.jdom2.input.SAXBuilder;
import org.jdom2.JDOMException;
import org.jdom2.xpath.XPathExpression;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
import java.io.File;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.*;
/** Reads XML files in KAF format and loads the content in a KAFDocument object, and writes the content into XML files. */
class ReadWriteManager {
/** Loads the content of a KAF file into the given KAFDocument object */
static KAFDocument load(File file) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
}
/** Loads the content of a String in KAF format into the given KAFDocument object */
static KAFDocument load(Reader stream) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(stream);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
}
/** Writes the content of a given KAFDocument to a file. */
static void save(KAFDocument kaf, String filename) {
try {
File file = new File(filename);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println("Error writing to file");
}
}
/** Writes the content of a KAFDocument object to standard output. */
static void print(KAFDocument kaf) {
try {
Writer out = new BufferedWriter(new OutputStreamWriter(System.out, "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println(e);
}
}
/** Returns a string containing the XML content of a KAFDocument object. */
static String kafToStr(KAFDocument kaf) {
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
Document jdom = KAFToDOM(kaf);
return out.outputString(jdom);
}
/** Loads a KAFDocument object from XML content in DOM format */
private static KAFDocument DOMToKAF(Document dom) throws KAFNotValidException {
HashMap<String, WF> wfIndex = new HashMap<String, WF>();
HashMap<String, Term> termIndex = new HashMap<String, Term>();
HashMap<String, Relational> relationalIndex = new HashMap<String, Relational>();
Element rootElem = dom.getRootElement();
String lang = getAttribute("lang", rootElem, Namespace.XML_NAMESPACE);
String kafVersion = getAttribute("version", rootElem);
KAFDocument kaf = new KAFDocument(lang, kafVersion);
List<Element> rootChildrenElems = rootElem.getChildren();
for (Element elem : rootChildrenElems) {
if (elem.getName().equals("kafHeader")) {
List<Element> lpsElems = elem.getChildren("linguisticProcessors");
for (Element lpsElem : lpsElems) {
String layer = getAttribute("layer", lpsElem);
List<Element> lpElems = lpsElem.getChildren();
for (Element lpElem : lpElems) {
String name = getAttribute("name", lpElem);
String timestamp = getOptAttribute("timestamp", lpElem);
String version = getOptAttribute("version", lpElem);
kaf.addLinguisticProcessor(layer, name, timestamp, version);
}
}
Element fileDescElem = elem.getChild("fileDesc");
if (fileDescElem != null) {
KAFDocument.FileDesc fd = kaf.createFileDesc();
String author = getOptAttribute("author", fileDescElem);
if (author != null) {
fd.author = author;
}
String title = getOptAttribute("title", fileDescElem);
if (title != null) {
fd.title = title;
}
String creationtime = getOptAttribute("creationtime", fileDescElem);
if (creationtime != null) {
fd.creationtime = creationtime;
}
String filename = getOptAttribute("filename", fileDescElem);
if (filename != null) {
fd.filename = filename;
}
String filetype = getOptAttribute("filetype", fileDescElem);
if (filetype != null) {
fd.filetype = filetype;
}
String pages = getOptAttribute("pages", fileDescElem);
if (pages != null) {
fd.pages = Integer.parseInt(pages);
}
}
Element publicElem = elem.getChild("public");
if (publicElem != null) {
String publicId = getAttribute("publicId", publicElem);
KAFDocument.Public pub = kaf.createPublic(publicId);
String uri = getOptAttribute("uri", publicElem);
if (uri != null) {
pub.uri = uri;
}
}
}
if (elem.getName().equals("raw")) {
kaf.setRawText(elem.getText());
}
if (elem.getName().equals("text")) {
List<Element> wfElems = elem.getChildren();
for (Element wfElem : wfElems) {
String wid = getAttribute("wid", wfElem);
String wForm = wfElem.getText();
String wSent = getOptAttribute("sent", wfElem);
WF newWf = kaf.newWF(wid, wForm, Integer.valueOf(wSent));
String wPara = getOptAttribute("para", wfElem);
if (wPara != null) {
newWf.setPara(Integer.valueOf(wPara));
}
String wPage = getOptAttribute("page", wfElem);
if (wPage != null) {
newWf.setPage(Integer.valueOf(wPage));
}
String wOffset = getOptAttribute("offset", wfElem);
if (wOffset != null) {
newWf.setOffset(Integer.valueOf(wOffset));
}
String wLength = getOptAttribute("length", wfElem);
if (wLength != null) {
newWf.setLength(Integer.valueOf(wLength));
}
String wXpath = getOptAttribute("xpath", wfElem);
if (wXpath != null) {
newWf.setXpath(wXpath);
}
wfIndex.put(newWf.getId(), newWf);
}
}
if (elem.getName().equals("terms")) {
List<Element> termElems = elem.getChildren();
for (Element termElem : termElems) {
String tid = getAttribute("tid", termElem);
String type = getAttribute("type", termElem);
String lemma = getAttribute("lemma", termElem);
String pos = getAttribute("pos", termElem);
Element spanElem = termElem.getChild("span");
if (spanElem == null) {
throw new IllegalStateException("Every term must contain a span element");
}
List<Element> termsWfElems = spanElem.getChildren("target");
Span<WF> span = kaf.newWFSpan();
for (Element termsWfElem : termsWfElems) {
String wfId = getAttribute("id", termsWfElem);
boolean isHead = isHead(termsWfElem);
WF wf = wfIndex.get(wfId);
if (wf == null) {
throw new KAFNotValidException("Wf " + wfId + " not found when loading term " + tid);
}
span.addTarget(wf, isHead);
}
Term newTerm = kaf.newTerm(tid, type, lemma, pos, span);
String tMorphofeat = getOptAttribute("morphofeat", termElem);
if (tMorphofeat != null) {
newTerm.setMorphofeat(tMorphofeat);
}
String tHead = getOptAttribute("head", termElem);
String termcase = getOptAttribute("case", termElem);
if (termcase != null) {
newTerm.setCase(termcase);
}
List<Element> sentimentElems = termElem.getChildren("sentiment");
if (sentimentElems.size() > 0) {
Element sentimentElem = sentimentElems.get(0);
Term.Sentiment newSentiment = kaf.newSentiment();
String sentResource = getOptAttribute("resource", sentimentElem);
if (sentResource != null) {
newSentiment.setResource(sentResource);
}
String sentPolarity = getOptAttribute("polarity", sentimentElem);
if (sentPolarity != null) {
newSentiment.setPolarity(sentPolarity);
}
String sentStrength = getOptAttribute("strength", sentimentElem);
if (sentStrength != null) {
newSentiment.setStrength(sentStrength);
}
String sentSubjectivity = getOptAttribute("subjectivity", sentimentElem);
if (sentSubjectivity != null) {
newSentiment.setSubjectivity(sentSubjectivity);
}
String sentSentimentSemanticType = getOptAttribute("sentiment_semantic_type", sentimentElem);
if (sentSentimentSemanticType != null) {
newSentiment.setSentimentSemanticType(sentSentimentSemanticType);
}
String sentSentimentModifier = getOptAttribute("sentiment_modifier", sentimentElem);
if (sentSentimentModifier != null) {
newSentiment.setSentimentModifier(sentSentimentModifier);
}
String sentSentimentMarker = getOptAttribute("sentiment_marker", sentimentElem);
if (sentSentimentMarker != null) {
newSentiment.setSentimentMarker(sentSentimentMarker);
}
String sentSentimentProductFeature = getOptAttribute("sentiment_product_feature", sentimentElem);
if (sentSentimentProductFeature != null) {
newSentiment.setSentimentProductFeature(sentSentimentProductFeature);
}
newTerm.setSentiment(newSentiment);
}
List<Element> termsComponentElems = termElem.getChildren("component");
for (Element termsComponentElem : termsComponentElems) {
String compId = getAttribute("id", termsComponentElem);
boolean isHead = ((tHead != null) && tHead.equals(compId));
String compLemma = getAttribute("lemma", termsComponentElem);
String compPos = getAttribute("pos", termsComponentElem);
Term.Component newComponent = kaf.newComponent(compId, newTerm, compLemma, compPos);
List<Element> externalReferencesElems = termsComponentElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newComponent.addExternalRefs(externalRefs);
}
newTerm.addComponent(newComponent, isHead);
}
List<Element> externalReferencesElems = termElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newTerm.addExternalRefs(externalRefs);
}
termIndex.put(newTerm.getId(), newTerm);
}
}
if (elem.getName().equals("deps")) {
List<Element> depElems = elem.getChildren();
for (Element depElem : depElems) {
String fromId = getAttribute("from", depElem);
String toId = getAttribute("to", depElem);
Term from = termIndex.get(fromId);
if (from == null) {
throw new KAFNotValidException("Term " + fromId + " not found when loading Dep (" + fromId + ", " + toId + ")");
}
Term to = termIndex.get(toId);
if (to == null) {
throw new KAFNotValidException("Term " + toId + " not found when loading Dep (" + fromId + ", " + toId + ")");
}
String rfunc = getAttribute("rfunc", depElem);
Dep newDep = kaf.newDep(from, to, rfunc);
String depcase = getOptAttribute("case", depElem);
if (depcase != null) {
newDep.setCase(depcase);
}
}
}
if (elem.getName().equals("chunks")) {
List<Element> chunkElems = elem.getChildren();
for (Element chunkElem : chunkElems) {
String chunkId = getAttribute("cid", chunkElem);
String headId = getAttribute("head", chunkElem);
Term chunkHead = termIndex.get(headId);
if (chunkHead == null) {
throw new KAFNotValidException("Term " + headId + " not found when loading chunk " + chunkId);
}
String chunkPhrase = getAttribute("phrase", chunkElem);
Element spanElem = chunkElem.getChild("span");
if (spanElem == null) {
throw new IllegalStateException("Every chunk must contain a span element");
}
List<Element> chunksTermElems = spanElem.getChildren("target");
Span<Term> span = kaf.newTermSpan();
for (Element chunksTermElem : chunksTermElems) {
String termId = getAttribute("id", chunksTermElem);
boolean isHead = isHead(chunksTermElem);
Term targetTerm = termIndex.get(termId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + termId + " not found when loading chunk " + chunkId);
}
span.addTarget(targetTerm, ((targetTerm == chunkHead) || isHead));
}
if (!span.hasTarget(chunkHead)) {
throw new KAFNotValidException("The head of the chunk is not in it's span.");
}
Chunk newChunk = kaf.newChunk(chunkId, chunkPhrase, span);
String chunkCase = getOptAttribute("case", chunkElem);
if (chunkCase != null) {
newChunk.setCase(chunkCase);
}
}
}
if (elem.getName().equals("entities")) {
List<Element> entityElems = elem.getChildren();
for (Element entityElem : entityElems) {
String entId = getAttribute("eid", entityElem);
String entType = getOptAttribute("type", entityElem);
List<Element> referencesElem = entityElem.getChildren("references");
if (referencesElem.size() < 1) {
throw new IllegalStateException("Every entity must contain a 'references' element");
}
List<Element> spanElems = referencesElem.get(0).getChildren();
if (spanElems.size() < 1) {
throw new IllegalStateException("Every entity must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in an entity must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading entity " + entId);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Entity newEntity = kaf.newEntity(entId, references);
if (entType != null) {
newEntity.setType(entType);
}
List<Element> externalReferencesElems = entityElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newEntity.addExternalRefs(externalRefs);
}
relationalIndex.put(newEntity.getId(), newEntity);
}
}
if (elem.getName().equals("coreferences")) {
List<Element> corefElems = elem.getChildren();
for (Element corefElem : corefElems) {
String coId = getAttribute("coid", corefElem);
List<Element> spanElems = corefElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every coref must contain a 'span' element inside 'references'");
}
List<Span<Term>> mentions = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in an entity must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading coref " + coId);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
mentions.add(span);
}
Coref newCoref = kaf.newCoref(coId, mentions);
}
}
if (elem.getName().equals("features")) {
Element propertiesElem = elem.getChild("properties");
Element categoriesElem = elem.getChild("categories");
if (propertiesElem != null) {
List<Element> propertyElems = propertiesElem.getChildren("property");
for (Element propertyElem : propertyElems) {
String pid = getAttribute("pid", propertyElem);
String lemma = getAttribute("lemma", propertyElem);
Element referencesElem = propertyElem.getChild("references");
if (referencesElem == null) {
throw new IllegalStateException("Every property must contain a 'references' element");
}
List<Element> spanElems = referencesElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every property must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in a property must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading property " + pid);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Feature newProperty = kaf.newProperty(pid, lemma, references);
List<Element> externalReferencesElems = propertyElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newProperty.addExternalRefs(externalRefs);
}
relationalIndex.put(newProperty.getId(), newProperty);
}
}
if (categoriesElem != null) {
List<Element> categoryElems = categoriesElem.getChildren("category");
for (Element categoryElem : categoryElems) {
String cid = getAttribute("cid", categoryElem);
String lemma = getAttribute("lemma", categoryElem);
Element referencesElem = categoryElem.getChild("references");
if (referencesElem == null) {
throw new IllegalStateException("Every category must contain a 'references' element");
}
List<Element> spanElems = referencesElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every category must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in a property must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading category " + cid);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Feature newCategory = kaf.newCategory(cid, lemma, references);
List<Element> externalReferencesElems = categoryElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newCategory.addExternalRefs(externalRefs);
}
relationalIndex.put(newCategory.getId(), newCategory);
}
}
}
if (elem.getName().equals("opinions")) {
List<Element> opinionElems = elem.getChildren("opinion");
for (Element opinionElem : opinionElems) {
String opinionId = getAttribute("oid", opinionElem);
Opinion opinion = kaf.newOpinion(opinionId);
Element opinionHolderElem = opinionElem.getChild("opinion_holder");
if (opinionHolderElem != null) {
Span<Term> span = kaf.newTermSpan();
Opinion.OpinionHolder opinionHolder = opinion.createOpinionHolder(span);
Element spanElem = opinionHolderElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
Element opinionTargetElem = opinionElem.getChild("opinion_target");
if (opinionTargetElem != null) {
Span<Term> span = kaf.newTermSpan();
Opinion.OpinionTarget opinionTarget = opinion.createOpinionTarget(span);
Element spanElem = opinionTargetElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
Element opinionExpressionElem = opinionElem.getChild("opinion_expression");
if (opinionExpressionElem != null) {
Span<Term> span = kaf.newTermSpan();
String polarity = getOptAttribute("polarity", opinionExpressionElem);
String strength = getOptAttribute("strength", opinionExpressionElem);
String subjectivity = getOptAttribute("subjectivity", opinionExpressionElem);
String sentimentSemanticType = getOptAttribute("sentiment_semantic_type", opinionExpressionElem);
String sentimentProductFeature = getOptAttribute("sentiment_product_feature", opinionExpressionElem);
Opinion.OpinionExpression opinionExpression = opinion.createOpinionExpression(span);
if (polarity != null) {
opinionExpression.setPolarity(polarity);
}
if (strength != null) {
opinionExpression.setStrength(strength);
}
if (subjectivity != null) {
opinionExpression.setSubjectivity(subjectivity);
}
if (sentimentSemanticType != null) {
opinionExpression.setSentimentSemanticType(sentimentSemanticType);
}
if (sentimentProductFeature != null) {
opinionExpression.setSentimentProductFeature(sentimentProductFeature);
}
Element spanElem = opinionExpressionElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
}
}
if (elem.getName().equals("relations")) {
List<Element> relationElems = elem.getChildren("relation");
for (Element relationElem : relationElems) {
String id = getAttribute("rid", relationElem);
String fromId = getAttribute("from", relationElem);
String toId = getAttribute("to", relationElem);
String confidenceStr = getOptAttribute("confidence", relationElem);
float confidence = -1.0f;
if (confidenceStr != null) {
confidence = Float.parseFloat(confidenceStr);
}
Relational from = relationalIndex.get(fromId);
if (from == null) {
throw new KAFNotValidException("Entity/feature object " + fromId + " not found when loading relation " + id);
}
Relational to = relationalIndex.get(toId);
if (to == null) {
throw new KAFNotValidException("Entity/feature object " + toId + " not found when loading relation " + id);
}
Relation newRelation = kaf.newRelation(id, from, to);
if (confidence >= 0) {
newRelation.setConfidence(confidence);
}
}
}
if (elem.getName().equals("srl")) {
List<Element> predicateElems = elem.getChildren("predicate");
for (Element predicateElem : predicateElems) {
String id = getAttribute("prid", predicateElem);
String uri = getOptAttribute("uri", predicateElem);
Span<Term> span = kaf.newTermSpan();
Element spanElem = predicateElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading predicate " + id);
}
span.addTarget(targetTerm, isHead);
}
}
Predicate newPredicate = kaf.newPredicate(id, span);
if (uri != null) {
newPredicate.setUri(uri);
}
List<Element> roleElems = predicateElem.getChildren("role");
for (Element roleElem : roleElems) {
String rid = getAttribute("rid", roleElem);
String semRole = getAttribute("semRole", roleElem);
Span<Term> roleSpan = kaf.newTermSpan();
Element roleSpanElem = roleElem.getChild("span");
if (roleSpanElem != null) {
List<Element> targetElems = roleSpanElem.getChildren("target");
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading role " + rid);
}
roleSpan.addTarget(targetTerm, isHead);
}
}
Predicate.Role newRole = kaf.newRole(rid, newPredicate, semRole, roleSpan);
newPredicate.addRole(newRole);
}
Span<Term> spana = kaf.newTermSpan();
Predicate.Role rolea = kaf.newRole(newPredicate, "kaka", spana);
newPredicate.addRole(rolea);
}
}
if (elem.getName().equals("constituents")) {
List<Element> treeElems = elem.getChildren("tree");
for (Element treeElem : treeElems) {
HashMap<String, TreeNode> treeNodes = new HashMap<String, TreeNode>();
HashMap<String, Boolean> rootNodes = new HashMap<String, Boolean>();
// Terminals
List<Element> terminalElems = treeElem.getChildren("t");
for (Element terminalElem : terminalElems) {
String id = getAttribute("id", terminalElem);
Element spanElem = terminalElem.getChild("span");
if (spanElem == null) {
throw new KAFNotValidException("Constituent non terminal nodes need a span");
}
Span<Term> span = loadTermSpan(spanElem, termIndex, id);
treeNodes.put(id, kaf.newTerminal(id, span));
rootNodes.put(id, true);
}
// NonTerminals
List<Element> nonTerminalElems = treeElem.getChildren("nt");
for (Element nonTerminalElem : nonTerminalElems) {
String id = getAttribute("id", nonTerminalElem);
String label = getAttribute("label", nonTerminalElem);
treeNodes.put(id, kaf.newNonTerminal(id, label));
rootNodes.put(id, true);
}
// Edges
List<Element> edgeElems = treeElem.getChildren("edge");
for (Element edgeElem : edgeElems) {
String fromId = getAttribute("from", edgeElem);
String toId = getAttribute("to", edgeElem);
String edgeId = getAttribute("id", edgeElem);
TreeNode parentNode = treeNodes.get(toId);
TreeNode childNode = treeNodes.get(fromId);
if ((parentNode == null) || (childNode == null)) {
throw new KAFNotValidException("There is a problem with the edge(" + fromId + ", " + toId + "). One of its targets doesn't exist.");
}
((NonTerminal) parentNode).addChild(childNode);
rootNodes.put(fromId, false);
childNode.setEdgeId(edgeId);
}
// Constituent objects
for (Map.Entry<String, Boolean> areRoot : rootNodes.entrySet()) {
if (areRoot.getValue()) {
TreeNode rootNode = treeNodes.get(areRoot.getKey());
kaf.newConstituent(rootNode);
}
}
}
}
}
return kaf;
}
private static Span<Term> loadTermSpan(Element spanElem, HashMap<String, Term> terms, String objId) throws KAFNotValidException {
List<Element> targetElems = spanElem.getChildren("target");
if (targetElems.size() < 1) {
throw new KAFNotValidException("A span element can not be empty");
}
Span<Term> span = KAFDocument.newTermSpan();
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = terms.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading object " + objId);
}
span.addTarget(targetTerm, isHead);
}
return span;
}
private static Element createTermSpanElem(Span<Term> span) {
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
String targetId = term.getId();
targetElem.setAttribute("id", targetId);
if (span.isHead(term)) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
return spanElem;
}
private static List<ExternalRef> getExternalReferences(Element externalReferencesElem, KAFDocument kaf) {
List<ExternalRef> externalRefs = new ArrayList<ExternalRef>();
List<Element> externalRefElems = externalReferencesElem.getChildren();
for (Element externalRefElem : externalRefElems) {
ExternalRef externalRef = getExternalRef(externalRefElem, kaf);
externalRefs.add(externalRef);
}
return externalRefs;
}
private static ExternalRef getExternalRef(Element externalRefElem, KAFDocument kaf) {
String resource = getAttribute("resource", externalRefElem);
String references = getAttribute("reference", externalRefElem);
ExternalRef newExternalRef = kaf.newExternalRef(resource, references);
String confidence = getOptAttribute("confidence", externalRefElem);
if (confidence != null) {
newExternalRef.setConfidence(Float.valueOf(confidence));
}
List<Element> subRefElems = externalRefElem.getChildren("externalRef");
if (subRefElems.size() > 0) {
Element subRefElem = subRefElems.get(0);
ExternalRef subRef = getExternalRef(subRefElem, kaf);
newExternalRef.setExternalRef(subRef);
}
return newExternalRef;
}
private static String getAttribute(String attName, Element elem) {
String value = elem.getAttributeValue(attName);
if (value==null) {
throw new IllegalStateException(attName+" attribute must be defined for element "+elem.getName());
}
return value;
}
private static String getAttribute(String attName, Element elem, Namespace nmspace) {
String value = elem.getAttributeValue(attName, nmspace);
if (value==null) {
throw new IllegalStateException(attName+" attribute must be defined for element "+elem.getName());
}
return value;
}
private static String getOptAttribute(String attName, Element elem) {
String value = elem.getAttributeValue(attName);
if (value==null) {
return null;
}
return value;
}
private static boolean isHead(Element elem) {
String value = elem.getAttributeValue("head");
if (value == null) {
return false;
}
if (value.equals("yes")) {
return true;
}
return false;
}
private static class Edge {
String id;
String from;
String to;
boolean head;
Edge(TreeNode from, TreeNode to) {
this.id = from.getEdgeId();
this.from = from.getId();
this.to = to.getId();
this.head = from.getHead();
}
}
/** Returns the content of the given KAFDocument in a DOM document. */
private static Document KAFToDOM(KAFDocument kaf) {
AnnotationContainer annotationContainer = kaf.getAnnotationContainer();
Element root = new Element("KAF");
root.setAttribute("lang", kaf.getLang(), Namespace.XML_NAMESPACE);
root.setAttribute("version", kaf.getVersion());
Document doc = new Document(root);
Element kafHeaderElem = new Element("kafHeader");
root.addContent(kafHeaderElem);
KAFDocument.FileDesc fd = kaf.getFileDesc();
if (fd != null) {
Element fdElem = new Element("fileDesc");
if (fd.author != null) {
fdElem.setAttribute("author", fd.author);
}
if (fd.author != null) {
fdElem.setAttribute("title", fd.title);
}
if (fd.creationtime != null) {
fdElem.setAttribute("creationtime", fd.creationtime);
}
if (fd.author != null) {
fdElem.setAttribute("filename", fd.filename);
}
if (fd.author != null) {
fdElem.setAttribute("filetype", fd.filetype);
}
if (fd.author != null) {
fdElem.setAttribute("pages", Integer.toString(fd.pages));
}
kafHeaderElem.addContent(fdElem);
}
KAFDocument.Public pub = kaf.getPublic();
if (pub != null) {
Element pubElem = new Element("public");
pubElem.setAttribute("publicId", pub.publicId);
if (pub.uri != null) {
pubElem.setAttribute("uri", pub.uri);
}
kafHeaderElem.addContent(pubElem);
}
Map<String, List<KAFDocument.LinguisticProcessor>> lps = kaf.getLinguisticProcessors();
for (Map.Entry entry : lps.entrySet()) {
Element lpsElem = new Element("linguisticProcessors");
lpsElem.setAttribute("layer", (String) entry.getKey());
for (KAFDocument.LinguisticProcessor lp : (List<KAFDocument.LinguisticProcessor>) entry.getValue()) {
Element lpElem = new Element("lp");
lpElem.setAttribute("name", lp.name);
lpElem.setAttribute("timestamp", lp.timestamp);
lpElem.setAttribute("version", lp.version);
lpsElem.addContent(lpElem);
}
kafHeaderElem.addContent(lpsElem);
}
String rawText = annotationContainer.getRawText();
if (rawText.length() > 0) {
Element rawElem = new Element("raw");
CDATA cdataElem = new CDATA(rawText);
rawElem.addContent(cdataElem);
root.addContent(rawElem);
}
List<WF> text = annotationContainer.getText();
if (text.size() > 0) {
Element textElem = new Element("text");
for (WF wf : text) {
Element wfElem = new Element("wf");
wfElem.setAttribute("wid", wf.getId());
if (wf.hasSent()) {
wfElem.setAttribute("sent", Integer.toString(wf.getSent()));
}
if (wf.hasPara()) {
wfElem.setAttribute("para", Integer.toString(wf.getPara()));
}
if (wf.hasPage()) {
wfElem.setAttribute("page", Integer.toString(wf.getPage()));
}
if (wf.hasOffset()) {
wfElem.setAttribute("offset", Integer.toString(wf.getOffset()));
}
if (wf.hasLength()) {
wfElem.setAttribute("length", Integer.toString(wf.getLength()));
}
if (wf.hasXpath()) {
wfElem.setAttribute("xpath", wf.getXpath());
}
wfElem.setText(wf.getForm());
textElem.addContent(wfElem);
}
root.addContent(textElem);
}
List<Term> terms = annotationContainer.getTerms();
if (terms.size() > 0) {
Element termsElem = new Element("terms");
for (Term term : terms) {
String morphofeat;
Term.Component head;
String termcase;
Comment termComment = new Comment(term.getStr());
termsElem.addContent(termComment);
Element termElem = new Element("term");
termElem.setAttribute("tid", term.getId());
termElem.setAttribute("type", term.getType());
termElem.setAttribute("lemma", term.getLemma());
termElem.setAttribute("pos", term.getPos());
if (term.hasMorphofeat()) {
termElem.setAttribute("morphofeat", term.getMorphofeat());
}
if (term.hasHead()) {
termElem.setAttribute("head", term.getHead().getId());
}
if (term.hasCase()) {
termElem.setAttribute("case", term.getCase());
}
if (term.hasSentiment()) {
Term.Sentiment sentiment = term.getSentiment();
Element sentimentElem = new Element("sentiment");
if (sentiment.hasResource()) {
sentimentElem.setAttribute("resource", sentiment.getResource());
}
if (sentiment.hasPolarity()) {
sentimentElem.setAttribute("polarity", sentiment.getPolarity());
}
if (sentiment.hasStrength()) {
sentimentElem.setAttribute("strength", sentiment.getStrength());
}
if (sentiment.hasSubjectivity()) {
sentimentElem.setAttribute("subjectivity", sentiment.getSubjectivity());
}
if (sentiment.hasSentimentSemanticType()) {
sentimentElem.setAttribute("sentiment_semantic_type", sentiment.getSentimentSemanticType());
}
if (sentiment.hasSentimentModifier()) {
sentimentElem.setAttribute("sentiment_modifier", sentiment.getSentimentModifier());
}
if (sentiment.hasSentimentMarker()) {
sentimentElem.setAttribute("sentiment_marker", sentiment.getSentimentMarker());
}
if (sentiment.hasSentimentProductFeature()) {
sentimentElem.setAttribute("sentiment_product_feature", sentiment.getSentimentProductFeature());
}
termElem.addContent(sentimentElem);
}
Element spanElem = new Element("span");
Span<WF> span = term.getSpan();
for (WF target : term.getWFs()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
termElem.addContent(spanElem);
List<Term.Component> components = term.getComponents();
if (components.size() > 0) {
for (Term.Component component : components) {
Element componentElem = new Element("component");
componentElem.setAttribute("id", component.getId());
componentElem.setAttribute("lemma", component.getLemma());
componentElem.setAttribute("pos", component.getPos());
if (component.hasCase()) {
componentElem.setAttribute("case", component.getCase());
}
List<ExternalRef> externalReferences = component.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
componentElem.addContent(externalReferencesElem);
}
termElem.addContent(componentElem);
}
}
List<ExternalRef> externalReferences = term.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
termElem.addContent(externalReferencesElem);
}
termsElem.addContent(termElem);
}
root.addContent(termsElem);
}
List<Dep> deps = annotationContainer.getDeps();
if (deps.size() > 0) {
Element depsElem = new Element("deps");
for (Dep dep : deps) {
Comment depComment = new Comment(dep.getStr());
depsElem.addContent(depComment);
Element depElem = new Element("dep");
depElem.setAttribute("from", dep.getFrom().getId());
depElem.setAttribute("to", dep.getTo().getId());
depElem.setAttribute("rfunc", dep.getRfunc());
if (dep.hasCase()) {
depElem.setAttribute("case", dep.getCase());
}
depsElem.addContent(depElem);
}
root.addContent(depsElem);
}
List<Chunk> chunks = annotationContainer.getChunks();
if (chunks.size() > 0) {
Element chunksElem = new Element("chunks");
for (Chunk chunk : chunks) {
Comment chunkComment = new Comment(chunk.getStr());
chunksElem.addContent(chunkComment);
Element chunkElem = new Element("chunk");
chunkElem.setAttribute("cid", chunk.getId());
chunkElem.setAttribute("head", chunk.getHead().getId());
chunkElem.setAttribute("phrase", chunk.getPhrase());
if (chunk.hasCase()) {
chunkElem.setAttribute("case", chunk.getCase());
}
Element spanElem = new Element("span");
for (Term target : chunk.getTerms()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
spanElem.addContent(targetElem);
}
chunkElem.addContent(spanElem);
chunksElem.addContent(chunkElem);
}
root.addContent(chunksElem);
}
List<Entity> entities = annotationContainer.getEntities();
if (entities.size() > 0) {
Element entitiesElem = new Element("entities");
for (Entity entity : entities) {
Element entityElem = new Element("entity");
entityElem.setAttribute("eid", entity.getId());
entityElem.setAttribute("type", entity.getType());
Element referencesElem = new Element("references");
for (Span<Term> span : entity.getSpans()) {
Comment spanComment = new Comment(entity.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
entityElem.addContent(referencesElem);
List<ExternalRef> externalReferences = entity.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
entityElem.addContent(externalReferencesElem);
}
entitiesElem.addContent(entityElem);
}
root.addContent(entitiesElem);
}
List<Coref> corefs = annotationContainer.getCorefs();
if (corefs.size() > 0) {
Element corefsElem = new Element("coreferences");
for (Coref coref : corefs) {
Element corefElem = new Element("coref");
corefElem.setAttribute("coid", coref.getId());
for (Span<Term> span : coref.getSpans()) {
Comment spanComment = new Comment(coref.getSpanStr(span));
corefElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term target : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
corefElem.addContent(spanElem);
}
corefsElem.addContent(corefElem);
}
root.addContent(corefsElem);
}
Element featuresElem = new Element("features");
List<Feature> properties = annotationContainer.getProperties();
if (properties.size() > 0) {
Element propertiesElem = new Element("properties");
for (Feature property : properties) {
Element propertyElem = new Element("property");
propertyElem.setAttribute("pid", property.getId());
propertyElem.setAttribute("lemma", property.getLemma());
List<Span<Term>> references = property.getSpans();
Element referencesElem = new Element("references");
for (Span<Term> span : references) {
Comment spanComment = new Comment(property.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
propertyElem.addContent(referencesElem);
propertiesElem.addContent(propertyElem);
}
featuresElem.addContent(propertiesElem);
}
List<Feature> categories = annotationContainer.getCategories();
if (categories.size() > 0) {
Element categoriesElem = new Element("categories");
for (Feature category : categories) {
Element categoryElem = new Element("category");
categoryElem.setAttribute("cid", category.getId());
categoryElem.setAttribute("lemma", category.getLemma());
List<Span<Term>> references = category.getSpans();
Element referencesElem = new Element("references");
for (Span<Term> span : references) {
Comment spanComment = new Comment(category.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
categoryElem.addContent(referencesElem);
categoriesElem.addContent(categoryElem);
}
featuresElem.addContent(categoriesElem);
}
if (featuresElem.getChildren().size() > 0) {
root.addContent(featuresElem);
}
List<Opinion> opinions = annotationContainer.getOpinions();
if (opinions.size() > 0) {
Element opinionsElem = new Element("opinions");
for (Opinion opinion : opinions) {
Element opinionElem = new Element("opinion");
opinionElem.setAttribute("oid", opinion.getId());
Opinion.OpinionHolder holder = opinion.getOpinionHolder();
if (holder != null) {
Element opinionHolderElem = new Element("opinion_holder");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionHolder().getSpan()));
opinionHolderElem.addContent(comment);
List<Term> targets = holder.getTerms();
Span<Term> span = holder.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionHolderElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionHolderElem);
}
Opinion.OpinionTarget opTarget = opinion.getOpinionTarget();
if (opTarget != null) {
Element opinionTargetElem = new Element("opinion_target");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionTarget().getSpan()));
opinionTargetElem.addContent(comment);
List<Term> targets = opTarget.getTerms();
Span<Term> span = opTarget.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionTargetElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionTargetElem);
}
Opinion.OpinionExpression expression = opinion.getOpinionExpression();
if (expression != null) {
Element opinionExpressionElem = new Element("opinion_expression");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionExpression().getSpan()));
opinionExpressionElem.addContent(comment);
if (expression.hasPolarity()) {
opinionExpressionElem.setAttribute("polarity", expression.getPolarity());
}
if (expression.hasStrength()) {
opinionExpressionElem.setAttribute("strength", expression.getStrength());
}
if (expression.hasSubjectivity()) {
opinionExpressionElem.setAttribute("subjectivity", expression.getSubjectivity());
}
if (expression.hasSentimentSemanticType()) {
opinionExpressionElem.setAttribute("sentiment_semantic_type", expression.getSentimentSemanticType());
}
if (expression.hasSentimentProductFeature()) {
opinionExpressionElem.setAttribute("sentiment_product_feature", expression.getSentimentProductFeature());
}
List<Term> targets = expression.getTerms();
Span<Term> span = expression.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionExpressionElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionExpressionElem);
}
opinionsElem.addContent(opinionElem);
}
root.addContent(opinionsElem);
}
List<Relation> relations = annotationContainer.getRelations();
if (relations.size() > 0) {
Element relationsElem = new Element("relations");
for (Relation relation : relations) {
Comment comment = new Comment(relation.getStr());
relationsElem.addContent(comment);
Element relationElem = new Element("relation");
relationElem.setAttribute("rid", relation.getId());
relationElem.setAttribute("from", relation.getFrom().getId());
relationElem.setAttribute("to", relation.getTo().getId());
if (relation.hasConfidence()) {
relationElem.setAttribute("confidence", String.valueOf(relation.getConfidence()));
}
relationsElem.addContent(relationElem);
}
root.addContent(relationsElem);
}
List<Predicate> predicates = annotationContainer.getPredicates();
if (predicates.size() > 0) {
Element predicatesElem = new Element("srl");
for (Predicate predicate : predicates) {
Comment predicateComment = new Comment(predicate.getStr());
predicatesElem.addContent(predicateComment);
Element predicateElem = new Element("predicate");
predicateElem.setAttribute("prid", predicate.getId());
if (predicate.hasUri()) {
predicateElem.setAttribute("uri", predicate.getUri());
}
Span<Term> span = predicate.getSpan();
if (span.getTargets().size() > 0) {
Comment spanComment = new Comment(predicate.getSpanStr());
Element spanElem = new Element("span");
predicateElem.addContent(spanComment);
predicateElem.addContent(spanElem);
for (Term target : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
for (Predicate.Role role : predicate.getRoles()) {
Element roleElem = new Element("role");
roleElem.setAttribute("rid", role.getId());
roleElem.setAttribute("semRole", role.getSemRole());
Span<Term> roleSpan = role.getSpan();
if (roleSpan.getTargets().size() > 0) {
Comment spanComment = new Comment(role.getStr());
Element spanElem = new Element("span");
roleElem.addContent(spanComment);
roleElem.addContent(spanElem);
for (Term target : roleSpan.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == roleSpan.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
predicateElem.addContent(roleElem);
}
predicatesElem.addContent(predicateElem);
}
root.addContent(predicatesElem);
}
List<Tree> constituents = annotationContainer.getConstituents();
if (constituents.size() > 0) {
Element constituentsElem = new Element("constituents");
for (Tree tree : constituents) {
Element treeElem = new Element("tree");
constituentsElem.addContent(treeElem);
List<NonTerminal> nonTerminals = new LinkedList<NonTerminal>();
List<Terminal> terminals = new LinkedList<Terminal>();
List<Edge> edges = new ArrayList<Edge>();
TreeNode rootNode = tree.getRoot();
extractTreeNodes(rootNode, nonTerminals, terminals, edges);
Collections.sort(nonTerminals, new Comparator<NonTerminal>() {
public int compare(NonTerminal nt1, NonTerminal nt2) {
if (cmpId(nt1.getId(), nt2.getId()) < 0) {
return -1;
} else if (nt1.getId().equals(nt2.getId())) {
return 0;
} else {
return 1;
}
}
});
Collections.sort(terminals, new Comparator<Terminal>() {
public int compare(Terminal t1, Terminal t2) {
if (cmpId(t1.getId(), t2.getId()) < 0) {
return -1;
} else if (t1.getId().equals(t2.getId())) {
return 0;
} else {
return 1;
}
}
});
Comment ntCom = new Comment("Non-terminals");
treeElem.addContent(ntCom);
for (NonTerminal node : nonTerminals) {
Element nodeElem = new Element("nt");
nodeElem.setAttribute("id", node.getId());
nodeElem.setAttribute("label", node.getLabel());
treeElem.addContent(nodeElem);
}
Comment tCom = new Comment("Terminals");
treeElem.addContent(tCom);
for (Terminal node : terminals) {
Element nodeElem = new Element("t");
nodeElem.setAttribute("id", node.getId());
nodeElem.addContent(createTermSpanElem(node.getSpan()));
// Comment
Comment tStrCom = new Comment(node.getStr());
treeElem.addContent(tStrCom);
treeElem.addContent(nodeElem);
}
Comment edgeCom = new Comment("Tree edges");
treeElem.addContent(edgeCom);
for (Edge edge : edges) {
Element edgeElem = new Element("edge");
edgeElem.setAttribute("id", edge.id);
edgeElem.setAttribute("from", edge.from);
edgeElem.setAttribute("to", edge.to);
if (edge.head) {
edgeElem.setAttribute("head", "yes");
}
treeElem.addContent(edgeElem);
}
}
root.addContent(constituentsElem);
}
return doc;
}
private static void extractTreeNodes(TreeNode node, List<NonTerminal> nonTerminals, List<Terminal> terminals, List<Edge> edges) {
if (node instanceof NonTerminal) {
nonTerminals.add((NonTerminal) node);
List<TreeNode> treeNodes = ((NonTerminal) node).getChildren();
for (TreeNode child : treeNodes) {
edges.add(new Edge(child, node));
extractTreeNodes(child, nonTerminals, terminals, edges);
}
} else {
terminals.add((Terminal) node);
}
}
private static Element externalReferencesToDOM(List<ExternalRef> externalRefs) {
Element externalReferencesElem = new Element("externalReferences");
for (ExternalRef externalRef : externalRefs) {
Element externalRefElem = externalRefToDOM(externalRef);
externalReferencesElem.addContent(externalRefElem);
}
return externalReferencesElem;
}
private static Element externalRefToDOM(ExternalRef externalRef) {
Element externalRefElem = new Element("externalRef");
externalRefElem.setAttribute("resource", externalRef.getResource());
externalRefElem.setAttribute("reference", externalRef.getReference());
if (externalRef.hasConfidence()) {
externalRefElem.setAttribute("confidence", Float.toString(externalRef.getConfidence()));
}
if (externalRef.hasExternalRef()) {
Element subExternalRefElem = externalRefToDOM(externalRef.getExternalRef());
externalRefElem.addContent(subExternalRefElem);
}
return externalRefElem;
}
private static int cmpId(String id1, String id2) {
int nbr1 = extractNumberFromId(id1);
int nbr2 = extractNumberFromId(id2);
if (nbr1 < nbr2) {
return -1;
} else if (nbr1 == nbr2) {
return 0;
} else {
return 1;
}
}
private static int extractNumberFromId(String id) {
Matcher matcher = Pattern.compile("^[a-z]*_?(\\d+)$").matcher(id);
if (!matcher.find()) {
throw new IllegalStateException("IdManager doesn't recognise the given id's (" + id + ") format. Should be [a-z]*_?[0-9]+");
}
return Integer.valueOf(matcher.group(1));
}
}
|
src/main/java/ixa/kaflib/ReadWriteManager.java
|
package ixa.kaflib;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Comment;
import org.jdom2.Namespace;
import org.jdom2.CDATA;
import org.jdom2.output.XMLOutputter;
import org.jdom2.output.Format;
import org.jdom2.input.SAXBuilder;
import org.jdom2.JDOMException;
import org.jdom2.xpath.XPathExpression;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;
import java.io.File;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.*;
/** Reads XML files in KAF format and loads the content in a KAFDocument object, and writes the content into XML files. */
class ReadWriteManager {
/** Loads the content of a KAF file into the given KAFDocument object */
static KAFDocument load(File file) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
}
/** Loads the content of a String in KAF format into the given KAFDocument object */
static KAFDocument load(Reader stream) throws IOException, JDOMException, KAFNotValidException {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(stream);
Element rootElem = document.getRootElement();
return DOMToKAF(document);
}
/** Writes the content of a given KAFDocument to a file. */
static void save(KAFDocument kaf, String filename) {
try {
File file = new File(filename);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println("Error writing to file");
}
}
/** Writes the content of a KAFDocument object to standard output. */
static void print(KAFDocument kaf) {
try {
Writer out = new BufferedWriter(new OutputStreamWriter(System.out, "UTF8"));
out.write(kafToStr(kaf));
out.flush();
} catch (Exception e) {
System.out.println(e);
}
}
/** Returns a string containing the XML content of a KAFDocument object. */
static String kafToStr(KAFDocument kaf) {
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
Document jdom = KAFToDOM(kaf);
return out.outputString(jdom);
}
/** Loads a KAFDocument object from XML content in DOM format */
private static KAFDocument DOMToKAF(Document dom) throws KAFNotValidException {
HashMap<String, WF> wfIndex = new HashMap<String, WF>();
HashMap<String, Term> termIndex = new HashMap<String, Term>();
HashMap<String, Relational> relationalIndex = new HashMap<String, Relational>();
Element rootElem = dom.getRootElement();
String lang = getAttribute("lang", rootElem, Namespace.XML_NAMESPACE);
String kafVersion = getAttribute("version", rootElem);
KAFDocument kaf = new KAFDocument(lang, kafVersion);
List<Element> rootChildrenElems = rootElem.getChildren();
for (Element elem : rootChildrenElems) {
if (elem.getName().equals("kafHeader")) {
List<Element> lpsElems = elem.getChildren("linguisticProcessors");
for (Element lpsElem : lpsElems) {
String layer = getAttribute("layer", lpsElem);
List<Element> lpElems = lpsElem.getChildren();
for (Element lpElem : lpElems) {
String name = getAttribute("name", lpElem);
String timestamp = getOptAttribute("timestamp", lpElem);
String version = getOptAttribute("version", lpElem);
kaf.addLinguisticProcessor(layer, name, timestamp, version);
}
}
Element fileDescElem = elem.getChild("fileDesc");
if (fileDescElem != null) {
KAFDocument.FileDesc fd = kaf.createFileDesc();
String author = getOptAttribute("author", fileDescElem);
if (author != null) {
fd.author = author;
}
String title = getOptAttribute("title", fileDescElem);
if (title != null) {
fd.title = title;
}
String creationtime = getOptAttribute("creationtime", fileDescElem);
if (creationtime != null) {
fd.creationtime = creationtime;
}
String filename = getOptAttribute("filename", fileDescElem);
if (filename != null) {
fd.filename = filename;
}
String filetype = getOptAttribute("filetype", fileDescElem);
if (filetype != null) {
fd.filetype = filetype;
}
String pages = getOptAttribute("pages", fileDescElem);
if (pages != null) {
fd.pages = Integer.parseInt(pages);
}
}
Element publicElem = elem.getChild("public");
if (publicElem != null) {
String publicId = getAttribute("publicId", publicElem);
KAFDocument.Public pub = kaf.createPublic(publicId);
String uri = getOptAttribute("uri", publicElem);
if (uri != null) {
pub.uri = uri;
}
}
}
if (elem.getName().equals("raw")) {
kaf.setRawText(elem.getText());
}
if (elem.getName().equals("text")) {
List<Element> wfElems = elem.getChildren();
for (Element wfElem : wfElems) {
String wid = getAttribute("wid", wfElem);
String wForm = wfElem.getText();
String wSent = getOptAttribute("sent", wfElem);
WF newWf = kaf.newWF(wid, wForm, Integer.valueOf(wSent));
String wPara = getOptAttribute("para", wfElem);
if (wPara != null) {
newWf.setPara(Integer.valueOf(wPara));
}
String wPage = getOptAttribute("page", wfElem);
if (wPage != null) {
newWf.setPage(Integer.valueOf(wPage));
}
String wOffset = getOptAttribute("offset", wfElem);
if (wOffset != null) {
newWf.setOffset(Integer.valueOf(wOffset));
}
String wLength = getOptAttribute("length", wfElem);
if (wLength != null) {
newWf.setLength(Integer.valueOf(wLength));
}
String wXpath = getOptAttribute("xpath", wfElem);
if (wXpath != null) {
newWf.setXpath(wXpath);
}
wfIndex.put(newWf.getId(), newWf);
}
}
if (elem.getName().equals("terms")) {
List<Element> termElems = elem.getChildren();
for (Element termElem : termElems) {
String tid = getAttribute("tid", termElem);
String type = getAttribute("type", termElem);
String lemma = getAttribute("lemma", termElem);
String pos = getAttribute("pos", termElem);
Element spanElem = termElem.getChild("span");
if (spanElem == null) {
throw new IllegalStateException("Every term must contain a span element");
}
List<Element> termsWfElems = spanElem.getChildren("target");
Span<WF> span = kaf.newWFSpan();
for (Element termsWfElem : termsWfElems) {
String wfId = getAttribute("id", termsWfElem);
boolean isHead = isHead(termsWfElem);
WF wf = wfIndex.get(wfId);
if (wf == null) {
throw new KAFNotValidException("Wf " + wfId + " not found when loading term " + tid);
}
span.addTarget(wf, isHead);
}
Term newTerm = kaf.newTerm(tid, type, lemma, pos, span);
String tMorphofeat = getOptAttribute("morphofeat", termElem);
if (tMorphofeat != null) {
newTerm.setMorphofeat(tMorphofeat);
}
String tHead = getOptAttribute("head", termElem);
String termcase = getOptAttribute("case", termElem);
if (termcase != null) {
newTerm.setCase(termcase);
}
List<Element> sentimentElems = termElem.getChildren("sentiment");
if (sentimentElems.size() > 0) {
Element sentimentElem = sentimentElems.get(0);
Term.Sentiment newSentiment = kaf.newSentiment();
String sentResource = getOptAttribute("resource", sentimentElem);
if (sentResource != null) {
newSentiment.setResource(sentResource);
}
String sentPolarity = getOptAttribute("polarity", sentimentElem);
if (sentPolarity != null) {
newSentiment.setPolarity(sentPolarity);
}
String sentStrength = getOptAttribute("strength", sentimentElem);
if (sentStrength != null) {
newSentiment.setStrength(sentStrength);
}
String sentSubjectivity = getOptAttribute("subjectivity", sentimentElem);
if (sentSubjectivity != null) {
newSentiment.setSubjectivity(sentSubjectivity);
}
String sentSentimentSemanticType = getOptAttribute("sentiment_semantic_type", sentimentElem);
if (sentSentimentSemanticType != null) {
newSentiment.setSentimentSemanticType(sentSentimentSemanticType);
}
String sentSentimentModifier = getOptAttribute("sentiment_modifier", sentimentElem);
if (sentSentimentModifier != null) {
newSentiment.setSentimentModifier(sentSentimentModifier);
}
String sentSentimentMarker = getOptAttribute("sentiment_marker", sentimentElem);
if (sentSentimentMarker != null) {
newSentiment.setSentimentMarker(sentSentimentMarker);
}
String sentSentimentProductFeature = getOptAttribute("sentiment_product_feature", sentimentElem);
if (sentSentimentProductFeature != null) {
newSentiment.setSentimentProductFeature(sentSentimentProductFeature);
}
newTerm.setSentiment(newSentiment);
}
List<Element> termsComponentElems = termElem.getChildren("component");
for (Element termsComponentElem : termsComponentElems) {
String compId = getAttribute("id", termsComponentElem);
boolean isHead = ((tHead != null) && tHead.equals(compId));
String compLemma = getAttribute("lemma", termsComponentElem);
String compPos = getAttribute("pos", termsComponentElem);
Term.Component newComponent = kaf.newComponent(compId, newTerm, compLemma, compPos);
List<Element> externalReferencesElems = termsComponentElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newComponent.addExternalRefs(externalRefs);
}
newTerm.addComponent(newComponent, isHead);
}
List<Element> externalReferencesElems = termElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newTerm.addExternalRefs(externalRefs);
}
termIndex.put(newTerm.getId(), newTerm);
}
}
if (elem.getName().equals("deps")) {
List<Element> depElems = elem.getChildren();
for (Element depElem : depElems) {
String fromId = getAttribute("from", depElem);
String toId = getAttribute("to", depElem);
Term from = termIndex.get(fromId);
if (from == null) {
throw new KAFNotValidException("Term " + fromId + " not found when loading Dep (" + fromId + ", " + toId + ")");
}
Term to = termIndex.get(toId);
if (to == null) {
throw new KAFNotValidException("Term " + toId + " not found when loading Dep (" + fromId + ", " + toId + ")");
}
String rfunc = getAttribute("rfunc", depElem);
Dep newDep = kaf.newDep(from, to, rfunc);
String depcase = getOptAttribute("case", depElem);
if (depcase != null) {
newDep.setCase(depcase);
}
}
}
if (elem.getName().equals("chunks")) {
List<Element> chunkElems = elem.getChildren();
for (Element chunkElem : chunkElems) {
String chunkId = getAttribute("cid", chunkElem);
String headId = getAttribute("head", chunkElem);
Term chunkHead = termIndex.get(headId);
if (chunkHead == null) {
throw new KAFNotValidException("Term " + headId + " not found when loading chunk " + chunkId);
}
String chunkPhrase = getAttribute("phrase", chunkElem);
Element spanElem = chunkElem.getChild("span");
if (spanElem == null) {
throw new IllegalStateException("Every chunk must contain a span element");
}
List<Element> chunksTermElems = spanElem.getChildren("target");
Span<Term> span = kaf.newTermSpan();
for (Element chunksTermElem : chunksTermElems) {
String termId = getAttribute("id", chunksTermElem);
boolean isHead = isHead(chunksTermElem);
Term targetTerm = termIndex.get(termId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + termId + " not found when loading chunk " + chunkId);
}
span.addTarget(targetTerm, ((targetTerm == chunkHead) || isHead));
}
if (!span.hasTarget(chunkHead)) {
throw new KAFNotValidException("The head of the chunk is not in it's span.");
}
Chunk newChunk = kaf.newChunk(chunkId, chunkPhrase, span);
String chunkCase = getOptAttribute("case", chunkElem);
if (chunkCase != null) {
newChunk.setCase(chunkCase);
}
}
}
if (elem.getName().equals("entities")) {
List<Element> entityElems = elem.getChildren();
for (Element entityElem : entityElems) {
String entId = getAttribute("eid", entityElem);
String entType = getOptAttribute("type", entityElem);
List<Element> referencesElem = entityElem.getChildren("references");
if (referencesElem.size() < 1) {
throw new IllegalStateException("Every entity must contain a 'references' element");
}
List<Element> spanElems = referencesElem.get(0).getChildren();
if (spanElems.size() < 1) {
throw new IllegalStateException("Every entity must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in an entity must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading entity " + entId);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Entity newEntity = kaf.newEntity(entId, references);
if (entType != null) {
newEntity.setType(entType);
}
List<Element> externalReferencesElems = entityElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newEntity.addExternalRefs(externalRefs);
}
relationalIndex.put(newEntity.getId(), newEntity);
}
}
if (elem.getName().equals("coreferences")) {
List<Element> corefElems = elem.getChildren();
for (Element corefElem : corefElems) {
String coId = getAttribute("id", corefElem);
List<Element> spanElems = corefElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every coref must contain a 'span' element inside 'references'");
}
List<Span<Term>> mentions = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in an entity must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading coref " + coId);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
mentions.add(span);
}
Coref newCoref = kaf.newCoref(coId, mentions);
}
}
if (elem.getName().equals("features")) {
Element propertiesElem = elem.getChild("properties");
Element categoriesElem = elem.getChild("categories");
if (propertiesElem != null) {
List<Element> propertyElems = propertiesElem.getChildren("property");
for (Element propertyElem : propertyElems) {
String pid = getAttribute("pid", propertyElem);
String lemma = getAttribute("lemma", propertyElem);
Element referencesElem = propertyElem.getChild("references");
if (referencesElem == null) {
throw new IllegalStateException("Every property must contain a 'references' element");
}
List<Element> spanElems = referencesElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every property must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in a property must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading property " + pid);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Feature newProperty = kaf.newProperty(pid, lemma, references);
List<Element> externalReferencesElems = propertyElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newProperty.addExternalRefs(externalRefs);
}
relationalIndex.put(newProperty.getId(), newProperty);
}
}
if (categoriesElem != null) {
List<Element> categoryElems = categoriesElem.getChildren("category");
for (Element categoryElem : categoryElems) {
String cid = getAttribute("cid", categoryElem);
String lemma = getAttribute("lemma", categoryElem);
Element referencesElem = categoryElem.getChild("references");
if (referencesElem == null) {
throw new IllegalStateException("Every category must contain a 'references' element");
}
List<Element> spanElems = referencesElem.getChildren("span");
if (spanElems.size() < 1) {
throw new IllegalStateException("Every category must contain a 'span' element inside 'references'");
}
List<Span<Term>> references = new ArrayList<Span<Term>>();
for (Element spanElem : spanElems) {
Span<Term> span = kaf.newTermSpan();
List<Element> targetElems = spanElem.getChildren();
if (targetElems.size() < 1) {
throw new IllegalStateException("Every span in a property must contain at least one target inside");
}
for (Element targetElem : targetElems) {
String targetTermId = getAttribute("id", targetElem);
Term targetTerm = termIndex.get(targetTermId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + targetTermId + " not found when loading category " + cid);
}
boolean isHead = isHead(targetElem);
span.addTarget(targetTerm, isHead);
}
references.add(span);
}
Feature newCategory = kaf.newCategory(cid, lemma, references);
List<Element> externalReferencesElems = categoryElem.getChildren("externalReferences");
if (externalReferencesElems.size() > 0) {
List<ExternalRef> externalRefs = getExternalReferences(externalReferencesElems.get(0), kaf);
newCategory.addExternalRefs(externalRefs);
}
relationalIndex.put(newCategory.getId(), newCategory);
}
}
}
if (elem.getName().equals("opinions")) {
List<Element> opinionElems = elem.getChildren("opinion");
for (Element opinionElem : opinionElems) {
String opinionId = getAttribute("oid", opinionElem);
Opinion opinion = kaf.newOpinion(opinionId);
Element opinionHolderElem = opinionElem.getChild("opinion_holder");
if (opinionHolderElem != null) {
Span<Term> span = kaf.newTermSpan();
Opinion.OpinionHolder opinionHolder = opinion.createOpinionHolder(span);
Element spanElem = opinionHolderElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
Element opinionTargetElem = opinionElem.getChild("opinion_target");
if (opinionTargetElem != null) {
Span<Term> span = kaf.newTermSpan();
Opinion.OpinionTarget opinionTarget = opinion.createOpinionTarget(span);
Element spanElem = opinionTargetElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
Element opinionExpressionElem = opinionElem.getChild("opinion_expression");
if (opinionExpressionElem != null) {
Span<Term> span = kaf.newTermSpan();
String polarity = getOptAttribute("polarity", opinionExpressionElem);
String strength = getOptAttribute("strength", opinionExpressionElem);
String subjectivity = getOptAttribute("subjectivity", opinionExpressionElem);
String sentimentSemanticType = getOptAttribute("sentiment_semantic_type", opinionExpressionElem);
String sentimentProductFeature = getOptAttribute("sentiment_product_feature", opinionExpressionElem);
Opinion.OpinionExpression opinionExpression = opinion.createOpinionExpression(span);
if (polarity != null) {
opinionExpression.setPolarity(polarity);
}
if (strength != null) {
opinionExpression.setStrength(strength);
}
if (subjectivity != null) {
opinionExpression.setSubjectivity(subjectivity);
}
if (sentimentSemanticType != null) {
opinionExpression.setSentimentSemanticType(sentimentSemanticType);
}
if (sentimentProductFeature != null) {
opinionExpression.setSentimentProductFeature(sentimentProductFeature);
}
Element spanElem = opinionExpressionElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String refId = getOptAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(refId);
if (targetTerm == null) {
throw new KAFNotValidException("Term " + refId + " not found when loading opinion " + opinionId);
}
span.addTarget(targetTerm, isHead);
}
}
}
}
}
if (elem.getName().equals("relations")) {
List<Element> relationElems = elem.getChildren("relation");
for (Element relationElem : relationElems) {
String id = getAttribute("rid", relationElem);
String fromId = getAttribute("from", relationElem);
String toId = getAttribute("to", relationElem);
String confidenceStr = getOptAttribute("confidence", relationElem);
float confidence = -1.0f;
if (confidenceStr != null) {
confidence = Float.parseFloat(confidenceStr);
}
Relational from = relationalIndex.get(fromId);
if (from == null) {
throw new KAFNotValidException("Entity/feature object " + fromId + " not found when loading relation " + id);
}
Relational to = relationalIndex.get(toId);
if (to == null) {
throw new KAFNotValidException("Entity/feature object " + toId + " not found when loading relation " + id);
}
Relation newRelation = kaf.newRelation(id, from, to);
if (confidence >= 0) {
newRelation.setConfidence(confidence);
}
}
}
if (elem.getName().equals("srl")) {
List<Element> predicateElems = elem.getChildren("predicate");
for (Element predicateElem : predicateElems) {
String id = getAttribute("prid", predicateElem);
String uri = getOptAttribute("uri", predicateElem);
Span<Term> span = kaf.newTermSpan();
Element spanElem = predicateElem.getChild("span");
if (spanElem != null) {
List<Element> targetElems = spanElem.getChildren("target");
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading predicate " + id);
}
span.addTarget(targetTerm, isHead);
}
}
Predicate newPredicate = kaf.newPredicate(id, span);
if (uri != null) {
newPredicate.setUri(uri);
}
List<Element> roleElems = predicateElem.getChildren("role");
for (Element roleElem : roleElems) {
String rid = getAttribute("rid", roleElem);
String semRole = getAttribute("semRole", roleElem);
Span<Term> roleSpan = kaf.newTermSpan();
Element roleSpanElem = roleElem.getChild("span");
if (roleSpanElem != null) {
List<Element> targetElems = roleSpanElem.getChildren("target");
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = termIndex.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading role " + rid);
}
roleSpan.addTarget(targetTerm, isHead);
}
}
Predicate.Role newRole = kaf.newRole(rid, newPredicate, semRole, roleSpan);
newPredicate.addRole(newRole);
}
Span<Term> spana = kaf.newTermSpan();
Predicate.Role rolea = kaf.newRole(newPredicate, "kaka", spana);
newPredicate.addRole(rolea);
}
}
if (elem.getName().equals("constituents")) {
List<Element> treeElems = elem.getChildren("tree");
for (Element treeElem : treeElems) {
HashMap<String, TreeNode> treeNodes = new HashMap<String, TreeNode>();
HashMap<String, Boolean> rootNodes = new HashMap<String, Boolean>();
// Terminals
List<Element> terminalElems = treeElem.getChildren("t");
for (Element terminalElem : terminalElems) {
String id = getAttribute("id", terminalElem);
Element spanElem = terminalElem.getChild("span");
if (spanElem == null) {
throw new KAFNotValidException("Constituent non terminal nodes need a span");
}
Span<Term> span = loadTermSpan(spanElem, termIndex, id);
treeNodes.put(id, kaf.newTerminal(id, span));
rootNodes.put(id, true);
}
// NonTerminals
List<Element> nonTerminalElems = treeElem.getChildren("nt");
for (Element nonTerminalElem : nonTerminalElems) {
String id = getAttribute("id", nonTerminalElem);
String label = getAttribute("label", nonTerminalElem);
treeNodes.put(id, kaf.newNonTerminal(id, label));
rootNodes.put(id, true);
}
// Edges
List<Element> edgeElems = treeElem.getChildren("edge");
for (Element edgeElem : edgeElems) {
String fromId = getAttribute("from", edgeElem);
String toId = getAttribute("to", edgeElem);
String edgeId = getAttribute("id", edgeElem);
TreeNode parentNode = treeNodes.get(toId);
TreeNode childNode = treeNodes.get(fromId);
if ((parentNode == null) || (childNode == null)) {
throw new KAFNotValidException("There is a problem with the edge(" + fromId + ", " + toId + "). One of its targets doesn't exist.");
}
((NonTerminal) parentNode).addChild(childNode);
rootNodes.put(fromId, false);
childNode.setEdgeId(edgeId);
}
// Constituent objects
for (Map.Entry<String, Boolean> areRoot : rootNodes.entrySet()) {
if (areRoot.getValue()) {
TreeNode rootNode = treeNodes.get(areRoot.getKey());
kaf.newConstituent(rootNode);
}
}
}
}
}
return kaf;
}
private static Span<Term> loadTermSpan(Element spanElem, HashMap<String, Term> terms, String objId) throws KAFNotValidException {
List<Element> targetElems = spanElem.getChildren("target");
if (targetElems.size() < 1) {
throw new KAFNotValidException("A span element can not be empty");
}
Span<Term> span = KAFDocument.newTermSpan();
for (Element targetElem : targetElems) {
String targetId = getAttribute("id", targetElem);
boolean isHead = isHead(targetElem);
Term targetTerm = terms.get(targetId);
if (targetTerm == null) {
throw new KAFNotValidException("Term object " + targetId + " not found when loading object " + objId);
}
span.addTarget(targetTerm, isHead);
}
return span;
}
private static Element createTermSpanElem(Span<Term> span) {
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
String targetId = term.getId();
targetElem.setAttribute("id", targetId);
if (span.isHead(term)) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
return spanElem;
}
private static List<ExternalRef> getExternalReferences(Element externalReferencesElem, KAFDocument kaf) {
List<ExternalRef> externalRefs = new ArrayList<ExternalRef>();
List<Element> externalRefElems = externalReferencesElem.getChildren();
for (Element externalRefElem : externalRefElems) {
ExternalRef externalRef = getExternalRef(externalRefElem, kaf);
externalRefs.add(externalRef);
}
return externalRefs;
}
private static ExternalRef getExternalRef(Element externalRefElem, KAFDocument kaf) {
String resource = getAttribute("resource", externalRefElem);
String references = getAttribute("reference", externalRefElem);
ExternalRef newExternalRef = kaf.newExternalRef(resource, references);
String confidence = getOptAttribute("confidence", externalRefElem);
if (confidence != null) {
newExternalRef.setConfidence(Float.valueOf(confidence));
}
List<Element> subRefElems = externalRefElem.getChildren("externalRef");
if (subRefElems.size() > 0) {
Element subRefElem = subRefElems.get(0);
ExternalRef subRef = getExternalRef(subRefElem, kaf);
newExternalRef.setExternalRef(subRef);
}
return newExternalRef;
}
private static String getAttribute(String attName, Element elem) {
String value = elem.getAttributeValue(attName);
if (value==null) {
throw new IllegalStateException(attName+" attribute must be defined for element "+elem.getName());
}
return value;
}
private static String getAttribute(String attName, Element elem, Namespace nmspace) {
String value = elem.getAttributeValue(attName, nmspace);
if (value==null) {
throw new IllegalStateException(attName+" attribute must be defined for element "+elem.getName());
}
return value;
}
private static String getOptAttribute(String attName, Element elem) {
String value = elem.getAttributeValue(attName);
if (value==null) {
return null;
}
return value;
}
private static boolean isHead(Element elem) {
String value = elem.getAttributeValue("head");
if (value == null) {
return false;
}
if (value.equals("yes")) {
return true;
}
return false;
}
private static class Edge {
String id;
String from;
String to;
boolean head;
Edge(TreeNode from, TreeNode to) {
this.id = from.getEdgeId();
this.from = from.getId();
this.to = to.getId();
this.head = from.getHead();
}
}
/** Returns the content of the given KAFDocument in a DOM document. */
private static Document KAFToDOM(KAFDocument kaf) {
AnnotationContainer annotationContainer = kaf.getAnnotationContainer();
Element root = new Element("KAF");
root.setAttribute("lang", kaf.getLang(), Namespace.XML_NAMESPACE);
root.setAttribute("version", kaf.getVersion());
Document doc = new Document(root);
Element kafHeaderElem = new Element("kafHeader");
root.addContent(kafHeaderElem);
KAFDocument.FileDesc fd = kaf.getFileDesc();
if (fd != null) {
Element fdElem = new Element("fileDesc");
if (fd.author != null) {
fdElem.setAttribute("author", fd.author);
}
if (fd.author != null) {
fdElem.setAttribute("title", fd.title);
}
if (fd.creationtime != null) {
fdElem.setAttribute("creationtime", fd.creationtime);
}
if (fd.author != null) {
fdElem.setAttribute("filename", fd.filename);
}
if (fd.author != null) {
fdElem.setAttribute("filetype", fd.filetype);
}
if (fd.author != null) {
fdElem.setAttribute("pages", Integer.toString(fd.pages));
}
kafHeaderElem.addContent(fdElem);
}
KAFDocument.Public pub = kaf.getPublic();
if (pub != null) {
Element pubElem = new Element("public");
pubElem.setAttribute("publicId", pub.publicId);
if (pub.uri != null) {
pubElem.setAttribute("uri", pub.uri);
}
kafHeaderElem.addContent(pubElem);
}
Map<String, List<KAFDocument.LinguisticProcessor>> lps = kaf.getLinguisticProcessors();
for (Map.Entry entry : lps.entrySet()) {
Element lpsElem = new Element("linguisticProcessors");
lpsElem.setAttribute("layer", (String) entry.getKey());
for (KAFDocument.LinguisticProcessor lp : (List<KAFDocument.LinguisticProcessor>) entry.getValue()) {
Element lpElem = new Element("lp");
lpElem.setAttribute("name", lp.name);
lpElem.setAttribute("timestamp", lp.timestamp);
lpElem.setAttribute("version", lp.version);
lpsElem.addContent(lpElem);
}
kafHeaderElem.addContent(lpsElem);
}
String rawText = annotationContainer.getRawText();
if (rawText.length() > 0) {
Element rawElem = new Element("raw");
CDATA cdataElem = new CDATA(rawText);
rawElem.addContent(cdataElem);
root.addContent(rawElem);
}
List<WF> text = annotationContainer.getText();
if (text.size() > 0) {
Element textElem = new Element("text");
for (WF wf : text) {
Element wfElem = new Element("wf");
wfElem.setAttribute("wid", wf.getId());
if (wf.hasSent()) {
wfElem.setAttribute("sent", Integer.toString(wf.getSent()));
}
if (wf.hasPara()) {
wfElem.setAttribute("para", Integer.toString(wf.getPara()));
}
if (wf.hasPage()) {
wfElem.setAttribute("page", Integer.toString(wf.getPage()));
}
if (wf.hasOffset()) {
wfElem.setAttribute("offset", Integer.toString(wf.getOffset()));
}
if (wf.hasLength()) {
wfElem.setAttribute("length", Integer.toString(wf.getLength()));
}
if (wf.hasXpath()) {
wfElem.setAttribute("xpath", wf.getXpath());
}
wfElem.setText(wf.getForm());
textElem.addContent(wfElem);
}
root.addContent(textElem);
}
List<Term> terms = annotationContainer.getTerms();
if (terms.size() > 0) {
Element termsElem = new Element("terms");
for (Term term : terms) {
String morphofeat;
Term.Component head;
String termcase;
Comment termComment = new Comment(term.getStr());
termsElem.addContent(termComment);
Element termElem = new Element("term");
termElem.setAttribute("tid", term.getId());
termElem.setAttribute("type", term.getType());
termElem.setAttribute("lemma", term.getLemma());
termElem.setAttribute("pos", term.getPos());
if (term.hasMorphofeat()) {
termElem.setAttribute("morphofeat", term.getMorphofeat());
}
if (term.hasHead()) {
termElem.setAttribute("head", term.getHead().getId());
}
if (term.hasCase()) {
termElem.setAttribute("case", term.getCase());
}
if (term.hasSentiment()) {
Term.Sentiment sentiment = term.getSentiment();
Element sentimentElem = new Element("sentiment");
if (sentiment.hasResource()) {
sentimentElem.setAttribute("resource", sentiment.getResource());
}
if (sentiment.hasPolarity()) {
sentimentElem.setAttribute("polarity", sentiment.getPolarity());
}
if (sentiment.hasStrength()) {
sentimentElem.setAttribute("strength", sentiment.getStrength());
}
if (sentiment.hasSubjectivity()) {
sentimentElem.setAttribute("subjectivity", sentiment.getSubjectivity());
}
if (sentiment.hasSentimentSemanticType()) {
sentimentElem.setAttribute("sentiment_semantic_type", sentiment.getSentimentSemanticType());
}
if (sentiment.hasSentimentModifier()) {
sentimentElem.setAttribute("sentiment_modifier", sentiment.getSentimentModifier());
}
if (sentiment.hasSentimentMarker()) {
sentimentElem.setAttribute("sentiment_marker", sentiment.getSentimentMarker());
}
if (sentiment.hasSentimentProductFeature()) {
sentimentElem.setAttribute("sentiment_product_feature", sentiment.getSentimentProductFeature());
}
termElem.addContent(sentimentElem);
}
Element spanElem = new Element("span");
Span<WF> span = term.getSpan();
for (WF target : term.getWFs()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
termElem.addContent(spanElem);
List<Term.Component> components = term.getComponents();
if (components.size() > 0) {
for (Term.Component component : components) {
Element componentElem = new Element("component");
componentElem.setAttribute("id", component.getId());
componentElem.setAttribute("lemma", component.getLemma());
componentElem.setAttribute("pos", component.getPos());
if (component.hasCase()) {
componentElem.setAttribute("case", component.getCase());
}
List<ExternalRef> externalReferences = component.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
componentElem.addContent(externalReferencesElem);
}
termElem.addContent(componentElem);
}
}
List<ExternalRef> externalReferences = term.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
termElem.addContent(externalReferencesElem);
}
termsElem.addContent(termElem);
}
root.addContent(termsElem);
}
List<Dep> deps = annotationContainer.getDeps();
if (deps.size() > 0) {
Element depsElem = new Element("deps");
for (Dep dep : deps) {
Comment depComment = new Comment(dep.getStr());
depsElem.addContent(depComment);
Element depElem = new Element("dep");
depElem.setAttribute("from", dep.getFrom().getId());
depElem.setAttribute("to", dep.getTo().getId());
depElem.setAttribute("rfunc", dep.getRfunc());
if (dep.hasCase()) {
depElem.setAttribute("case", dep.getCase());
}
depsElem.addContent(depElem);
}
root.addContent(depsElem);
}
List<Chunk> chunks = annotationContainer.getChunks();
if (chunks.size() > 0) {
Element chunksElem = new Element("chunks");
for (Chunk chunk : chunks) {
Comment chunkComment = new Comment(chunk.getStr());
chunksElem.addContent(chunkComment);
Element chunkElem = new Element("chunk");
chunkElem.setAttribute("cid", chunk.getId());
chunkElem.setAttribute("head", chunk.getHead().getId());
chunkElem.setAttribute("phrase", chunk.getPhrase());
if (chunk.hasCase()) {
chunkElem.setAttribute("case", chunk.getCase());
}
Element spanElem = new Element("span");
for (Term target : chunk.getTerms()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
spanElem.addContent(targetElem);
}
chunkElem.addContent(spanElem);
chunksElem.addContent(chunkElem);
}
root.addContent(chunksElem);
}
List<Entity> entities = annotationContainer.getEntities();
if (entities.size() > 0) {
Element entitiesElem = new Element("entities");
for (Entity entity : entities) {
Element entityElem = new Element("entity");
entityElem.setAttribute("eid", entity.getId());
entityElem.setAttribute("type", entity.getType());
Element referencesElem = new Element("references");
for (Span<Term> span : entity.getSpans()) {
Comment spanComment = new Comment(entity.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
entityElem.addContent(referencesElem);
List<ExternalRef> externalReferences = entity.getExternalRefs();
if (externalReferences.size() > 0) {
Element externalReferencesElem = externalReferencesToDOM(externalReferences);
entityElem.addContent(externalReferencesElem);
}
entitiesElem.addContent(entityElem);
}
root.addContent(entitiesElem);
}
List<Coref> corefs = annotationContainer.getCorefs();
if (corefs.size() > 0) {
Element corefsElem = new Element("coreferences");
for (Coref coref : corefs) {
Element corefElem = new Element("coref");
corefElem.setAttribute("coid", coref.getId());
for (Span<Term> span : coref.getSpans()) {
Comment spanComment = new Comment(coref.getSpanStr(span));
corefElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term target : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
corefElem.addContent(spanElem);
}
corefsElem.addContent(corefElem);
}
root.addContent(corefsElem);
}
Element featuresElem = new Element("features");
List<Feature> properties = annotationContainer.getProperties();
if (properties.size() > 0) {
Element propertiesElem = new Element("properties");
for (Feature property : properties) {
Element propertyElem = new Element("property");
propertyElem.setAttribute("pid", property.getId());
propertyElem.setAttribute("lemma", property.getLemma());
List<Span<Term>> references = property.getSpans();
Element referencesElem = new Element("references");
for (Span<Term> span : references) {
Comment spanComment = new Comment(property.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
propertyElem.addContent(referencesElem);
propertiesElem.addContent(propertyElem);
}
featuresElem.addContent(propertiesElem);
}
List<Feature> categories = annotationContainer.getCategories();
if (categories.size() > 0) {
Element categoriesElem = new Element("categories");
for (Feature category : categories) {
Element categoryElem = new Element("category");
categoryElem.setAttribute("cid", category.getId());
categoryElem.setAttribute("lemma", category.getLemma());
List<Span<Term>> references = category.getSpans();
Element referencesElem = new Element("references");
for (Span<Term> span : references) {
Comment spanComment = new Comment(category.getSpanStr(span));
referencesElem.addContent(spanComment);
Element spanElem = new Element("span");
for (Term term : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", term.getId());
if (term == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
referencesElem.addContent(spanElem);
}
categoryElem.addContent(referencesElem);
categoriesElem.addContent(categoryElem);
}
featuresElem.addContent(categoriesElem);
}
if (featuresElem.getChildren().size() > 0) {
root.addContent(featuresElem);
}
List<Opinion> opinions = annotationContainer.getOpinions();
if (opinions.size() > 0) {
Element opinionsElem = new Element("opinions");
for (Opinion opinion : opinions) {
Element opinionElem = new Element("opinion");
opinionElem.setAttribute("oid", opinion.getId());
Opinion.OpinionHolder holder = opinion.getOpinionHolder();
if (holder != null) {
Element opinionHolderElem = new Element("opinion_holder");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionHolder().getSpan()));
opinionHolderElem.addContent(comment);
List<Term> targets = holder.getTerms();
Span<Term> span = holder.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionHolderElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionHolderElem);
}
Opinion.OpinionTarget opTarget = opinion.getOpinionTarget();
if (opTarget != null) {
Element opinionTargetElem = new Element("opinion_target");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionTarget().getSpan()));
opinionTargetElem.addContent(comment);
List<Term> targets = opTarget.getTerms();
Span<Term> span = opTarget.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionTargetElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionTargetElem);
}
Opinion.OpinionExpression expression = opinion.getOpinionExpression();
if (expression != null) {
Element opinionExpressionElem = new Element("opinion_expression");
Comment comment = new Comment(opinion.getSpanStr(opinion.getOpinionExpression().getSpan()));
opinionExpressionElem.addContent(comment);
if (expression.hasPolarity()) {
opinionExpressionElem.setAttribute("polarity", expression.getPolarity());
}
if (expression.hasStrength()) {
opinionExpressionElem.setAttribute("strength", expression.getStrength());
}
if (expression.hasSubjectivity()) {
opinionExpressionElem.setAttribute("subjectivity", expression.getSubjectivity());
}
if (expression.hasSentimentSemanticType()) {
opinionExpressionElem.setAttribute("sentiment_semantic_type", expression.getSentimentSemanticType());
}
if (expression.hasSentimentProductFeature()) {
opinionExpressionElem.setAttribute("sentiment_product_feature", expression.getSentimentProductFeature());
}
List<Term> targets = expression.getTerms();
Span<Term> span = expression.getSpan();
if (targets.size() > 0) {
Element spanElem = new Element("span");
opinionExpressionElem.addContent(spanElem);
for (Term target : targets) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
opinionElem.addContent(opinionExpressionElem);
}
opinionsElem.addContent(opinionElem);
}
root.addContent(opinionsElem);
}
List<Relation> relations = annotationContainer.getRelations();
if (relations.size() > 0) {
Element relationsElem = new Element("relations");
for (Relation relation : relations) {
Comment comment = new Comment(relation.getStr());
relationsElem.addContent(comment);
Element relationElem = new Element("relation");
relationElem.setAttribute("rid", relation.getId());
relationElem.setAttribute("from", relation.getFrom().getId());
relationElem.setAttribute("to", relation.getTo().getId());
if (relation.hasConfidence()) {
relationElem.setAttribute("confidence", String.valueOf(relation.getConfidence()));
}
relationsElem.addContent(relationElem);
}
root.addContent(relationsElem);
}
List<Predicate> predicates = annotationContainer.getPredicates();
if (predicates.size() > 0) {
Element predicatesElem = new Element("srl");
for (Predicate predicate : predicates) {
Comment predicateComment = new Comment(predicate.getStr());
predicatesElem.addContent(predicateComment);
Element predicateElem = new Element("predicate");
predicateElem.setAttribute("prid", predicate.getId());
if (predicate.hasUri()) {
predicateElem.setAttribute("uri", predicate.getUri());
}
Span<Term> span = predicate.getSpan();
if (span.getTargets().size() > 0) {
Comment spanComment = new Comment(predicate.getSpanStr());
Element spanElem = new Element("span");
predicateElem.addContent(spanComment);
predicateElem.addContent(spanElem);
for (Term target : span.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == span.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
for (Predicate.Role role : predicate.getRoles()) {
Element roleElem = new Element("role");
roleElem.setAttribute("rid", role.getId());
roleElem.setAttribute("semRole", role.getSemRole());
Span<Term> roleSpan = role.getSpan();
if (roleSpan.getTargets().size() > 0) {
Comment spanComment = new Comment(role.getStr());
Element spanElem = new Element("span");
roleElem.addContent(spanComment);
roleElem.addContent(spanElem);
for (Term target : roleSpan.getTargets()) {
Element targetElem = new Element("target");
targetElem.setAttribute("id", target.getId());
if (target == roleSpan.getHead()) {
targetElem.setAttribute("head", "yes");
}
spanElem.addContent(targetElem);
}
}
predicateElem.addContent(roleElem);
}
predicatesElem.addContent(predicateElem);
}
root.addContent(predicatesElem);
}
List<Tree> constituents = annotationContainer.getConstituents();
if (constituents.size() > 0) {
Element constituentsElem = new Element("constituents");
for (Tree tree : constituents) {
Element treeElem = new Element("tree");
constituentsElem.addContent(treeElem);
List<NonTerminal> nonTerminals = new LinkedList<NonTerminal>();
List<Terminal> terminals = new LinkedList<Terminal>();
List<Edge> edges = new ArrayList<Edge>();
TreeNode rootNode = tree.getRoot();
extractTreeNodes(rootNode, nonTerminals, terminals, edges);
Collections.sort(nonTerminals, new Comparator<NonTerminal>() {
public int compare(NonTerminal nt1, NonTerminal nt2) {
if (cmpId(nt1.getId(), nt2.getId()) < 0) {
return -1;
} else if (nt1.getId().equals(nt2.getId())) {
return 0;
} else {
return 1;
}
}
});
Collections.sort(terminals, new Comparator<Terminal>() {
public int compare(Terminal t1, Terminal t2) {
if (cmpId(t1.getId(), t2.getId()) < 0) {
return -1;
} else if (t1.getId().equals(t2.getId())) {
return 0;
} else {
return 1;
}
}
});
Comment ntCom = new Comment("Non-terminals");
treeElem.addContent(ntCom);
for (NonTerminal node : nonTerminals) {
Element nodeElem = new Element("nt");
nodeElem.setAttribute("id", node.getId());
nodeElem.setAttribute("label", node.getLabel());
treeElem.addContent(nodeElem);
}
Comment tCom = new Comment("Terminals");
treeElem.addContent(tCom);
for (Terminal node : terminals) {
Element nodeElem = new Element("t");
nodeElem.setAttribute("id", node.getId());
nodeElem.addContent(createTermSpanElem(node.getSpan()));
// Comment
Comment tStrCom = new Comment(node.getStr());
treeElem.addContent(tStrCom);
treeElem.addContent(nodeElem);
}
Comment edgeCom = new Comment("Tree edges");
treeElem.addContent(edgeCom);
for (Edge edge : edges) {
Element edgeElem = new Element("edge");
edgeElem.setAttribute("id", edge.id);
edgeElem.setAttribute("from", edge.from);
edgeElem.setAttribute("to", edge.to);
if (edge.head) {
edgeElem.setAttribute("head", "yes");
}
treeElem.addContent(edgeElem);
}
}
root.addContent(constituentsElem);
}
return doc;
}
private static void extractTreeNodes(TreeNode node, List<NonTerminal> nonTerminals, List<Terminal> terminals, List<Edge> edges) {
if (node instanceof NonTerminal) {
nonTerminals.add((NonTerminal) node);
List<TreeNode> treeNodes = ((NonTerminal) node).getChildren();
for (TreeNode child : treeNodes) {
edges.add(new Edge(child, node));
extractTreeNodes(child, nonTerminals, terminals, edges);
}
} else {
terminals.add((Terminal) node);
}
}
private static Element externalReferencesToDOM(List<ExternalRef> externalRefs) {
Element externalReferencesElem = new Element("externalReferences");
for (ExternalRef externalRef : externalRefs) {
Element externalRefElem = externalRefToDOM(externalRef);
externalReferencesElem.addContent(externalRefElem);
}
return externalReferencesElem;
}
private static Element externalRefToDOM(ExternalRef externalRef) {
Element externalRefElem = new Element("externalRef");
externalRefElem.setAttribute("resource", externalRef.getResource());
externalRefElem.setAttribute("reference", externalRef.getReference());
if (externalRef.hasConfidence()) {
externalRefElem.setAttribute("confidence", Float.toString(externalRef.getConfidence()));
}
if (externalRef.hasExternalRef()) {
Element subExternalRefElem = externalRefToDOM(externalRef.getExternalRef());
externalRefElem.addContent(subExternalRefElem);
}
return externalRefElem;
}
private static int cmpId(String id1, String id2) {
int nbr1 = extractNumberFromId(id1);
int nbr2 = extractNumberFromId(id2);
if (nbr1 < nbr2) {
return -1;
} else if (nbr1 == nbr2) {
return 0;
} else {
return 1;
}
}
private static int extractNumberFromId(String id) {
Matcher matcher = Pattern.compile("^[a-z]*_?(\\d+)$").matcher(id);
if (!matcher.find()) {
throw new IllegalStateException("IdManager doesn't recognise the given id's (" + id + ") format. Should be [a-z]*_?[0-9]+");
}
return Integer.valueOf(matcher.group(1));
}
}
|
change coref element id to coid part 2
|
src/main/java/ixa/kaflib/ReadWriteManager.java
|
change coref element id to coid part 2
|
<ide><path>rc/main/java/ixa/kaflib/ReadWriteManager.java
<ide> if (elem.getName().equals("coreferences")) {
<ide> List<Element> corefElems = elem.getChildren();
<ide> for (Element corefElem : corefElems) {
<del> String coId = getAttribute("id", corefElem);
<add> String coId = getAttribute("coid", corefElem);
<ide> List<Element> spanElems = corefElem.getChildren("span");
<ide> if (spanElems.size() < 1) {
<ide> throw new IllegalStateException("Every coref must contain a 'span' element inside 'references'");
|
|
Java
|
bsd-3-clause
|
0b77a55a6ab8f7c967a948f25d8071e2129536fa
| 0 |
psygate/Citadel,psygate/Citadel
|
package vg.civcraft.mc.citadel.listener;
import java.util.Objects;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.block.Container;
import org.bukkit.block.Dispenser;
import org.bukkit.block.DoubleChest;
import org.bukkit.block.Dropper;
import org.bukkit.block.Hopper;
import org.bukkit.block.data.Directional;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import vg.civcraft.mc.citadel.ReinforcementLogic;
import vg.civcraft.mc.citadel.model.Reinforcement;
import vg.civcraft.mc.civmodcore.api.BlockAPI;
import vg.civcraft.mc.civmodcore.api.WorldAPI;
import vg.civcraft.mc.civmodcore.util.Iteration;
public class InventoryListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) {
Inventory fromInventory = event.getSource();
Inventory destInventory = event.getDestination();
// [LagFix] If either inventory's base location is unloaded, just cancel
if (!WorldAPI.isBlockLoaded(fromInventory.getLocation())
|| !WorldAPI.isBlockLoaded(destInventory.getLocation())) {
event.setCancelled(true);
return;
}
InventoryHolder fromHolder = fromInventory.getHolder();
InventoryHolder destHolder = destInventory.getHolder();
// Determine the reinforcement of the source
Reinforcement fromReinforcement = null;
if (fromHolder instanceof DoubleChest) {
DoubleChest doubleChest = (DoubleChest) fromHolder;
Location chestLocation = Objects.requireNonNull((Chest) doubleChest.getLeftSide()).getLocation();
Location otherLocation = Objects.requireNonNull((Chest) doubleChest.getRightSide()).getLocation();
// [LagFix] If either side of the double chest is not loaded then the reinforcement cannot be retrieved
// [LagFix] without necessarily loading the chunk to check against reinforcement logic, therefore this
// [LagFix] should air on the side of caution and prevent the transfer.
if (!WorldAPI.isBlockLoaded(chestLocation) || !WorldAPI.isBlockLoaded(otherLocation)) {
event.setCancelled(true);
return;
}
if (destHolder instanceof Hopper) {
Location drainedLocation = ((Hopper) destHolder).getLocation().add(0, 1, 0);
if (Iteration.contains(drainedLocation, chestLocation, otherLocation)) {
fromReinforcement = ReinforcementLogic.getReinforcementProtecting(drainedLocation.getBlock());
}
}
}
else if (fromHolder instanceof Container) {
Container container = (Container) fromHolder;
// [LagFix] This shouldn't be contributing to lag since there's isn't an implementation of 'Container' that
// [LagFix] spans more than one block, so the 'container.getBlock()' is permissible since we can reasonably
// [LagFix] assume that since this event was called, this block is loaded.
fromReinforcement = ReinforcementLogic.getReinforcementProtecting(container.getBlock());
}
// Determine the reinforcement of the destination
Reinforcement destReinforcement = null;
if (fromHolder instanceof Hopper || fromHolder instanceof Dropper || fromHolder instanceof Dispenser) {
Container container = (Container) fromHolder;
BlockFace direction = ((Directional) container.getBlockData()).getFacing();
// [LagFix] If the transfer is happening laterally and the target location is not loaded, then air on the
// [LagFix] side of caution and prevent the transfer.. though this may cause some issues with dispensers
// [LagFix] and droppers.
Location target = container.getLocation().add(direction.getDirection());
if (BlockAPI.PLANAR_SIDES.contains(direction) && !WorldAPI.isBlockLoaded(target)) {
event.setCancelled(true);
return;
}
destReinforcement = ReinforcementLogic.getReinforcementProtecting(target.getBlock());
}
else if (destHolder instanceof Container) {
Container container = (Container) destHolder;
// [LagFix] Just like the other 'Container' this shouldn't be an issue.
destReinforcement = ReinforcementLogic.getReinforcementProtecting(container.getBlock());
}
// Allow the transfer if neither are reinforced
if (fromReinforcement == null && destReinforcement == null) {
return;
}
// Allow the transfer if the destination is un-reinforced and the source is insecure
if (destReinforcement == null) {
if (!fromReinforcement.isInsecure()) {
event.setCancelled(true);
}
return;
}
// Allow the transfer if the source is un-reinforced and the destination is insecure
if (fromReinforcement == null) {
if (!destReinforcement.isInsecure()) {
event.setCancelled(true);
}
return;
}
// Allow the transfer if both the source and destination are insecure
if (fromReinforcement.isInsecure() && destReinforcement.isInsecure()) {
return;
}
// Allow the transfer if both the source and destination are on the same group
if (fromReinforcement.getGroupId() == destReinforcement.getGroupId()) {
return;
}
event.setCancelled(true);
}
}
|
src/main/java/vg/civcraft/mc/citadel/listener/InventoryListener.java
|
package vg.civcraft.mc.citadel.listener;
import java.util.Objects;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.block.Container;
import org.bukkit.block.Dispenser;
import org.bukkit.block.DoubleChest;
import org.bukkit.block.Dropper;
import org.bukkit.block.Hopper;
import org.bukkit.block.data.Directional;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import vg.civcraft.mc.citadel.ReinforcementLogic;
import vg.civcraft.mc.citadel.model.Reinforcement;
import vg.civcraft.mc.civmodcore.api.BlockAPI;
import vg.civcraft.mc.civmodcore.api.WorldAPI;
import vg.civcraft.mc.civmodcore.util.Iteration;
public class InventoryListener implements Listener {
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) {
Inventory fromInventory = event.getSource();
Inventory destInventory = event.getDestination();
InventoryHolder fromHolder = fromInventory.getHolder();
InventoryHolder destHolder = destInventory.getHolder();
// Determine the reinforcement of the source
Reinforcement fromReinforcement = null;
if (fromHolder instanceof DoubleChest) {
DoubleChest doubleChest = (DoubleChest) fromHolder;
Location chestLocation = Objects.requireNonNull((Chest) doubleChest.getLeftSide()).getLocation();
Location otherLocation = Objects.requireNonNull((Chest) doubleChest.getRightSide()).getLocation();
// [LagFix] If either side of the double chest is not loaded then the reinforcement cannot be retrieved
// [LagFix] without necessarily loading the chunk to check against reinforcement logic, therefore this
// [LagFix] should air on the side of caution and prevent the transfer.
if (!WorldAPI.isBlockLoaded(chestLocation) || !WorldAPI.isBlockLoaded(otherLocation)) {
event.setCancelled(true);
return;
}
if (destHolder instanceof Hopper) {
Location drainedLocation = ((Hopper) destHolder).getLocation().add(0, 1, 0);
if (Iteration.contains(drainedLocation, chestLocation, otherLocation)) {
fromReinforcement = ReinforcementLogic.getReinforcementProtecting(drainedLocation.getBlock());
}
}
}
else if (fromHolder instanceof Container) {
Container container = (Container) fromHolder;
// [LagFix] This shouldn't be contributing to lag since there's isn't an implementation of 'Container' that
// [LagFix] spans more than one block, so the 'container.getBlock()' is permissible since we can reasonably
// [LagFix] assume that since this event was called, this block is loaded.
fromReinforcement = ReinforcementLogic.getReinforcementProtecting(container.getBlock());
}
// Determine the reinforcement of the destination
Reinforcement destReinforcement = null;
if (fromHolder instanceof Hopper || fromHolder instanceof Dropper || fromHolder instanceof Dispenser) {
Container container = (Container) fromHolder;
BlockFace direction = ((Directional) container.getBlockData()).getFacing();
// [LagFix] If the transfer is happening laterally and the target location is not loaded, then air on the
// [LagFix] side of caution and prevent the transfer.. though this may cause some issues with dispensers
// [LagFix] and droppers.
Location target = container.getLocation().add(direction.getDirection());
if (BlockAPI.PLANAR_SIDES.contains(direction) && !WorldAPI.isBlockLoaded(target)) {
event.setCancelled(true);
return;
}
destReinforcement = ReinforcementLogic.getReinforcementProtecting(target.getBlock());
}
else if (destHolder instanceof Container) {
Container container = (Container) destHolder;
// [LagFix] Just like the other 'Container' this shouldn't be an issue.
destReinforcement = ReinforcementLogic.getReinforcementProtecting(container.getBlock());
}
// Allow the transfer if neither are reinforced
if (fromReinforcement == null && destReinforcement == null) {
return;
}
// Allow the transfer if the destination is un-reinforced and the source is insecure
if (destReinforcement == null) {
if (!fromReinforcement.isInsecure()) {
event.setCancelled(true);
}
return;
}
// Allow the transfer if the source is un-reinforced and the destination is insecure
if (fromReinforcement == null) {
if (!destReinforcement.isInsecure()) {
event.setCancelled(true);
}
return;
}
// Allow the transfer if both the source and destination are insecure
if (fromReinforcement.isInsecure() && destReinforcement.isInsecure()) {
return;
}
// Allow the transfer if both the source and destination are on the same group
if (fromReinforcement.getGroupId() == destReinforcement.getGroupId()) {
return;
}
event.setCancelled(true);
}
}
|
InventoryListener :: add preliminary is-loaded check
|
src/main/java/vg/civcraft/mc/citadel/listener/InventoryListener.java
|
InventoryListener :: add preliminary is-loaded check
|
<ide><path>rc/main/java/vg/civcraft/mc/citadel/listener/InventoryListener.java
<ide> public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) {
<ide> Inventory fromInventory = event.getSource();
<ide> Inventory destInventory = event.getDestination();
<add> // [LagFix] If either inventory's base location is unloaded, just cancel
<add> if (!WorldAPI.isBlockLoaded(fromInventory.getLocation())
<add> || !WorldAPI.isBlockLoaded(destInventory.getLocation())) {
<add> event.setCancelled(true);
<add> return;
<add> }
<ide> InventoryHolder fromHolder = fromInventory.getHolder();
<ide> InventoryHolder destHolder = destInventory.getHolder();
<ide> // Determine the reinforcement of the source
|
|
Java
|
apache-2.0
|
afae6c1f94558c44d350d5bd1663d9d1a229e3aa
| 0 |
IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service,IHTSDO/OTF-Mapping-Service
|
package org.ihtsdo.otf.mapping.rest;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.ihtsdo.otf.mapping.helpers.FeedbackEmail;
import org.ihtsdo.otf.mapping.helpers.LocalException;
import org.ihtsdo.otf.mapping.jpa.services.MappingServiceJpa;
import org.ihtsdo.otf.mapping.model.MapUser;
import org.ihtsdo.otf.mapping.model.UserError;
import org.ihtsdo.otf.mapping.services.MappingService;
/**
* Top level class for all REST services.
*/
public class RootServiceRest {
//
// Fields
//
/** The config. */
public Properties config = null;
/** The address that messages will appear as though they come from. */
String m_from = "";
/** The password for the SMTP host. */
String host_password = "";
/** The SMTP host that will be transmitting the message. */
String host = "";
/** The port on the SMTP host. */
String port = "";
/** The list of addresses to send the message to. */
String recipients = "";
/** Subject text for the email. */
String m_subject = "IHTSDO Mapping Tool Exception Report";
/** Text for the email. */
StringBuffer m_text;
/**
* Returns the config properties.
*
* @throws Exception the exception
*/
public void getConfigProperties() throws Exception {
if (config == null) {
String configFileName = System.getProperty("run.config");
Logger.getLogger(this.getClass())
.info(" run.config = " + configFileName);
config = new Properties();
FileReader in = new FileReader(new File(configFileName));
config.load(in);
in.close();
m_from = config.getProperty("mail.smtp.user");
host_password = config.getProperty("mail.smtp.password");
host = config.getProperty("mail.smtp.host");
port = config.getProperty("mail.smtp.port");
recipients = config.getProperty("mail.smtp.to");
Logger.getLogger(this.getClass()).info(" properties = " + config);
}
}
/**
* Handle exception. For {@link LocalException} print the stack trace and inform the
* user with a message generated by the application. For all other exceptions, also
* send email to administrators with the message and the stack trace.
*
* @param e the e
* @param whatIsHappening the what is happening
* @throws WebApplicationException the web application exception
*/
public void handleException(Exception e, String whatIsHappening)
throws WebApplicationException {
e.printStackTrace();
if (e instanceof LocalException) {
throw new WebApplicationException(Response.status(500).entity(e.getMessage()).build());
}
try {
getConfigProperties();
sendEmail(e, whatIsHappening);
} catch(Exception ex) {
ex.printStackTrace();
throw new WebApplicationException(Response.status(500).entity(ex.getMessage()).build());
}
throw new WebApplicationException(Response.status(500).entity(
"Unexpected error trying to " + whatIsHappening + ". Please contact the administrator.").build());
}
/**
* Send email regarding Exception e.
*
* @param e the e
* @param whatIsHappening the what is happening
*/
private void sendEmail(Exception e, String whatIsHappening) {
Properties props = new Properties();
props.put("mail.smtp.user", m_from);
props.put("mail.smtp.password", host_password);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
m_subject = "IHTSDO Mapping Tool Exception Report";
m_text = new StringBuffer();
if (!(e instanceof LocalException))
m_text.append("Unexpected error trying to " + whatIsHappening + ". Please contact the administrator.").append("\n\n");
m_text.append("MESSAGE: " + e.getMessage()).append("\n\n");
for (StackTraceElement element : e.getStackTrace()) {
m_text.append(" ").append(element).append("\n");
}
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text.toString());
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(m_from));
String[] recipientsArray = recipients.split(";");
for (String recipient : recipientsArray) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
/**
* Send user error email.
*
* @param userError the user error
*/
public void sendUserErrorEmail(UserError userError) {
Properties props = new Properties();
props.put("mail.smtp.user", m_from);
props.put("mail.smtp.password", host_password);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
m_subject = "IHTSDO Mapping Tool Editing Error Report";
m_text = new StringBuffer();
m_text.append("USER ERROR on " + userError.getMapRecord().getConceptId() + ": "
+ userError.getMapRecord().getConceptName()).append("\n\n");
m_text.append("Error type: " + userError.getMapError()).append("\n");
m_text.append("Reporting lead: " + userError.getMapUserReporting().getName()).append("\n");
m_text.append("Comment: " + userError.getNote()).append("\n");
m_text.append("Reporting date: " + userError.getTimestamp()).append("\n");
//m_text.append("Record URL: https://mapping.snomedtools.org/index.html#/record/conflicts/" + userError.getMapRecord().getId());
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text.toString());
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(m_from));
String[] recipientsArray = recipients.split(";");
for (String recipient : recipientsArray) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
public void sendEmail(FeedbackEmail feedbackEmail) {
try {
getConfigProperties();
Properties props = new Properties();
props.put("mail.smtp.user", m_from);
props.put("mail.smtp.password", host_password);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
//msg.setText(feedbackEmail.getEmailText());
msg.setSubject(feedbackEmail.getSubject());
msg.setFrom(new InternetAddress(m_from));
// get the recipients
MappingService mappingService = new MappingServiceJpa();
for (String recipient : feedbackEmail.getRecipients()) {
MapUser mapUser = mappingService.getMapUser(recipient);
System.out.println(mapUser.getEmail());
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mapUser.getEmail()));
}
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("***REMOVED***"));
msg.setContent(feedbackEmail.getEmailText(), "text/html");
// msg.addRecipient(Message.RecipientType.TO, new InternetAddress(feedbackEmail.getSender().getEmail()));
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
/**
* SMTPAuthenticator.
*/
public class SMTPAuthenticator extends javax.mail.Authenticator {
/* (non-Javadoc)
* @see javax.mail.Authenticator#getPasswordAuthentication()
*/
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(m_from, host_password);
}
}
}
|
rest/src/main/java/org/ihtsdo/otf/mapping/rest/RootServiceRest.java
|
package org.ihtsdo.otf.mapping.rest;
import java.io.File;
import java.io.FileReader;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.ihtsdo.otf.mapping.helpers.FeedbackEmail;
import org.ihtsdo.otf.mapping.helpers.LocalException;
import org.ihtsdo.otf.mapping.jpa.services.MappingServiceJpa;
import org.ihtsdo.otf.mapping.model.MapUser;
import org.ihtsdo.otf.mapping.model.UserError;
import org.ihtsdo.otf.mapping.services.MappingService;
/**
* Top level class for all REST services.
*/
public class RootServiceRest {
//
// Fields
//
/** The config. */
public Properties config = null;
/** The address that messages will appear as though they come from. */
String m_from = "";
/** The password for the SMTP host. */
String host_password = "";
/** The SMTP host that will be transmitting the message. */
String host = "";
/** The port on the SMTP host. */
String port = "";
/** The list of addresses to send the message to. */
String recipients = "";
/** Subject text for the email. */
String m_subject = "IHTSDO Mapping Tool Exception Report";
/** Text for the email. */
StringBuffer m_text;
/**
* Returns the config properties.
*
* @throws Exception the exception
*/
public void getConfigProperties() throws Exception {
if (config == null) {
String configFileName = System.getProperty("run.config");
Logger.getLogger(this.getClass())
.info(" run.config = " + configFileName);
config = new Properties();
FileReader in = new FileReader(new File(configFileName));
config.load(in);
in.close();
m_from = config.getProperty("mail.smtp.user");
host_password = config.getProperty("mail.smtp.password");
host = config.getProperty("mail.smtp.host");
port = config.getProperty("mail.smtp.port");
recipients = config.getProperty("mail.smtp.to");
Logger.getLogger(this.getClass()).info(" properties = " + config);
}
}
/**
* Handle exception. For {@link LocalException} print the stack trace and inform the
* user with a message generated by the application. For all other exceptions, also
* send email to administrators with the message and the stack trace.
*
* @param e the e
* @param whatIsHappening the what is happening
* @throws WebApplicationException the web application exception
*/
public void handleException(Exception e, String whatIsHappening)
throws WebApplicationException {
e.printStackTrace();
if (e instanceof LocalException) {
throw new WebApplicationException(Response.status(500).entity(e.getMessage()).build());
}
try {
getConfigProperties();
sendEmail(e, whatIsHappening);
} catch(Exception ex) {
ex.printStackTrace();
throw new WebApplicationException(Response.status(500).entity(ex.getMessage()).build());
}
throw new WebApplicationException(Response.status(500).entity(
"Unexpected error trying to " + whatIsHappening + ". Please contact the administrator.").build());
}
/**
* Send email regarding Exception e.
*
* @param e the e
* @param whatIsHappening the what is happening
*/
private void sendEmail(Exception e, String whatIsHappening) {
Properties props = new Properties();
props.put("mail.smtp.user", m_from);
props.put("mail.smtp.password", host_password);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
m_subject = "IHTSDO Mapping Tool Exception Report";
m_text = new StringBuffer();
if (!(e instanceof LocalException))
m_text.append("Unexpected error trying to " + whatIsHappening + ". Please contact the administrator.").append("\n\n");
m_text.append("MESSAGE: " + e.getMessage()).append("\n\n");
for (StackTraceElement element : e.getStackTrace()) {
m_text.append(" ").append(element).append("\n");
}
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text.toString());
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(m_from));
String[] recipientsArray = recipients.split(";");
for (String recipient : recipientsArray) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
/**
* Send user error email.
*
* @param userError the user error
*/
public void sendUserErrorEmail(UserError userError) {
Properties props = new Properties();
props.put("mail.smtp.user", m_from);
props.put("mail.smtp.password", host_password);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
m_subject = "IHTSDO Mapping Tool Editing Error Report";
m_text = new StringBuffer();
m_text.append("USER ERROR on " + userError.getMapRecord().getConceptId() + ":"
+ userError.getMapRecord().getConceptName()).append("\n\n");
m_text.append("Error type: " + userError.getMapError()).append("\n");
m_text.append("Reporting lead: " + userError.getMapUserReporting().getName()).append("\n");
m_text.append("Comment: " + userError.getNote()).append("\n");
m_text.append("Reporting date: " + userError.getTimestamp()).append("\n");
//m_text.append("Record URL: https://mapping.snomedtools.org/index.html#/record/conflicts/" + userError.getMapRecord().getId());
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text.toString());
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(m_from));
String[] recipientsArray = recipients.split(";");
for (String recipient : recipientsArray) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
public void sendEmail(FeedbackEmail feedbackEmail) {
try {
getConfigProperties();
Properties props = new Properties();
props.put("mail.smtp.user", m_from);
props.put("mail.smtp.password", host_password);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
//msg.setText(feedbackEmail.getEmailText());
msg.setSubject(feedbackEmail.getSubject());
msg.setFrom(new InternetAddress(m_from));
// get the recipients
MappingService mappingService = new MappingServiceJpa();
for (String recipient : feedbackEmail.getRecipients()) {
MapUser mapUser = mappingService.getMapUser(recipient);
System.out.println(mapUser.getEmail());
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mapUser.getEmail()));
}
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("***REMOVED***"));
msg.setContent(feedbackEmail.getEmailText(), "text/html");
// msg.addRecipient(Message.RecipientType.TO, new InternetAddress(feedbackEmail.getSender().getEmail()));
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}
}
/**
* SMTPAuthenticator.
*/
public class SMTPAuthenticator extends javax.mail.Authenticator {
/* (non-Javadoc)
* @see javax.mail.Authenticator#getPasswordAuthentication()
*/
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(m_from, host_password);
}
}
}
|
MAP-629: Create object to track lead-reported user errors
|
rest/src/main/java/org/ihtsdo/otf/mapping/rest/RootServiceRest.java
|
MAP-629: Create object to track lead-reported user errors
|
<ide><path>est/src/main/java/org/ihtsdo/otf/mapping/rest/RootServiceRest.java
<ide> m_subject = "IHTSDO Mapping Tool Editing Error Report";
<ide> m_text = new StringBuffer();
<ide>
<del> m_text.append("USER ERROR on " + userError.getMapRecord().getConceptId() + ":"
<add> m_text.append("USER ERROR on " + userError.getMapRecord().getConceptId() + ": "
<ide> + userError.getMapRecord().getConceptName()).append("\n\n");
<ide> m_text.append("Error type: " + userError.getMapError()).append("\n");
<ide> m_text.append("Reporting lead: " + userError.getMapUserReporting().getName()).append("\n");
|
|
Java
|
agpl-3.0
|
ec3dbc7b2fa3c6f50851ba87fad451e4820791ec
| 0 |
elki-project/elki,elki-project/elki,elki-project/elki
|
package de.lmu.ifi.dbs.algorithm.clustering;
import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.algorithm.result.Result;
import de.lmu.ifi.dbs.algorithm.result.clustering.PALMEResult;
import de.lmu.ifi.dbs.data.ClassLabel;
import de.lmu.ifi.dbs.data.DatabaseObject;
import de.lmu.ifi.dbs.data.MultiRepresentedObject;
import de.lmu.ifi.dbs.database.AssociationID;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.Distance;
import de.lmu.ifi.dbs.distance.RepresentationSelectingDistanceFunction;
import de.lmu.ifi.dbs.utilities.Description;
import de.lmu.ifi.dbs.utilities.Progress;
import de.lmu.ifi.dbs.utilities.QueryResult;
import de.lmu.ifi.dbs.utilities.UnableToComplyException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.*;
/**
* TODO: comment and new name
*
* @author Elke Achtert (<a href="mailto:[email protected]">[email protected]</a>)
*/
public class PALME<O extends DatabaseObject, D extends Distance<D>, M extends MultiRepresentedObject<O>> extends AbstractAlgorithm<M> {
/**
* The distance function for the single representations.
*/
private RepresentationSelectingDistanceFunction<O, M, D> mr_distanceFunction;
/**
* The result of this algorithm.
*/
private Result<M> result;
public PALME() {
super();
}
/**
* The run method encapsulated in measure of runtime. An extending class
* needs not to take care of runtime itself.
*
* @param database the database to run the algorithm on
* @throws IllegalStateException if the algorithm has not been initialized properly (e.g. the
* setParameters(String[]) method has been failed to be called).
*/
protected void runInTime(Database<M> database) throws IllegalStateException {
try {
if (database.size() == 0) {
result = new PALMEResult<O, D, M>(database);
return;
}
System.out.println("database.size " + database.size());
mr_distanceFunction.setDatabase(database, isVerbose());
int numberOfRepresentations = database.get(database.iterator().next()).getNumberOfRepresentations();
Map<ClassLabel, Set<Integer>> classMap = determineClassPartitions(database);
Progress progress = new Progress(2 * database.size() * numberOfRepresentations);
List<D> maxDistances = new ArrayList<D>(numberOfRepresentations);
List<List<Ranges>> resultList = new ArrayList<List<Ranges>>(numberOfRepresentations);
for (int r = 0; r < numberOfRepresentations; r++) {
int processed = 0;
if (isVerbose()) {
System.out.println("\nRepresentation " + (r + 1));
}
mr_distanceFunction.setCurrentRepresentationIndex(r);
List<DistanceObject> distances = determineDistances(database, progress, r);
D similarityRange = null;
D dissimilarityRange = null;
double foundAndDesired = 0;
double inverseFoundAndDesired = 0;
for (int i = 0; i < distances.size(); i++) {
DistanceObject distanceObject = distances.get(i);
if (distanceObject.sameClass) {
foundAndDesired++;
}
distanceObject.similarityPrecision = foundAndDesired / (i+1);
if (distanceObject.similarityPrecision > 0.9) {
similarityRange = distanceObject.distance;
}
DistanceObject inverseDistanceObject = distances.get(distances.size() - 1 - i);
if (! inverseDistanceObject.sameClass) {
inverseFoundAndDesired++;
}
inverseDistanceObject.dissimilarityPrecision = inverseFoundAndDesired / (i+1);
if (inverseDistanceObject.dissimilarityPrecision > 0.9) {
dissimilarityRange = inverseDistanceObject.distance;
}
}
output(r, distances, similarityRange, dissimilarityRange);
// maxDistances.add(maxDist);
// outputRanges(r, rangesList);
// resultList.add(rangesList);
}
this.result = new PALMEResult<O, D, M>(database);
}
catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws IllegalArgumentException {
String[] remainungParams = super.setParameters(args);
mr_distanceFunction = new RepresentationSelectingDistanceFunction<O, M, D>();
return mr_distanceFunction.setParameters(remainungParams);
}
/**
* Returns the result of the algorithm.
*
* @return the result of the algorithm
*/
public Result<M> getResult() {
return result;
}
/**
* Returns a description of the algorithm.
*
* @return a description of the algorithm
*/
public Description getDescription() {
// todo
return new Description("PALME",
"algorithm without name ;-)",
"First it determines the Recall and Precision levels for each representation " +
"of a database containing multirepresented_old objects according to a training set. " +
"Second a multirepresented_old version of OPTICS will be applied.",
"unpublished");
}
private Map<ClassLabel, Set<Integer>> determineClassPartitions(Database<M> database) throws IllegalStateException {
Map<ClassLabel, Set<Integer>> classMap = new HashMap<ClassLabel, Set<Integer>>();
Iterator<Integer> it = database.iterator();
while (it.hasNext()) {
Integer id = it.next();
ClassLabel classLabel = (ClassLabel) database.getAssociation(AssociationID.CLASS, id);
Set<Integer> ids = classMap.get(classLabel);
if (ids == null) {
ids = new HashSet<Integer>();
classMap.put(classLabel, ids);
}
ids.add(id);
}
return classMap;
}
private List<DistanceObject> determineDistances(Database<M> database, Progress progress, int r) {
int processed = r * database.size();
if (isVerbose()) {
System.out.println("... determine distances");
}
List<DistanceObject> distances = new ArrayList<DistanceObject>((database.size() * database.size() - 1) / 2);
for (Iterator<Integer> it1 = database.iterator(); it1.hasNext();) {
Integer id1 = it1.next();
ClassLabel classLabel1 = (ClassLabel) database.getAssociation(AssociationID.CLASS, id1);
String externalID1 = (String) database.getAssociation(AssociationID.EXTERNAL_ID, id1);
for (Iterator<Integer> it2 = database.iterator(); it2.hasNext();) {
Integer id2 = it2.next();
if (id1 >= id2) continue;
ClassLabel classLabel2 = (ClassLabel) database.getAssociation(AssociationID.CLASS, id2);
String externalID2 = (String) database.getAssociation(AssociationID.EXTERNAL_ID, id2);
D distance = mr_distanceFunction.distance(id1, id2);
DistanceObject object = new DistanceObject(externalID1, externalID2, classLabel1, classLabel2, distance);
distances.add(object);
}
if (isVerbose()) {
progress.setProcessed(++processed);
System.out.print("\r" + progress.toString());
}
}
Collections.sort(distances);
return distances;
}
private Ranges getProbabilityRanges(String id, ClassLabel classLabel, Set<Integer> desiredSet, List<QueryResult<D>> neighbors) {
if (neighbors.isEmpty())
throw new IllegalArgumentException("Empty neighbors!");
D similarityPrecision = null;
D dissimilaityPrecision = null;
double foundAndDesired = 0;
double inverseFoundAndDesired = 0;
double found = 0;
double inverseFound = 0;
double ws = (1.0 * desiredSet.size()) / (1.0 * neighbors.size());
double pp = ws + (1.0 - ws) * 0.9;
double ipp = (1 - ws) + ws * 0.9;
// System.out.println("ws = " + ws);
// System.out.println("pp = " + pp);
// System.out.println("ipp = " + ipp);
int size = neighbors.size() - 1;
for (int i = 0; i <= size; i++) {
found++;
QueryResult<D> neighbor = neighbors.get(i);
if (desiredSet.contains(neighbor.getID())) {
foundAndDesired++;
}
// precision
double p = foundAndDesired / found;
if (p >= pp) {
similarityPrecision = neighbor.getDistance();
}
inverseFound++;
QueryResult<D> i_neighbor = neighbors.get(size - i);
if (! desiredSet.contains(i_neighbor.getID())) {
inverseFoundAndDesired++;
}
// inverse precision
double ip = inverseFoundAndDesired / inverseFound;
if (ip >= ipp)
dissimilaityPrecision = i_neighbor.getDistance();
}
if (dissimilaityPrecision == null) {
dissimilaityPrecision = neighbors.get(neighbors.size() - 1).getDistance();
}
if (similarityPrecision == null) {
similarityPrecision = neighbors.get(0).getDistance();
}
return new Ranges(id, classLabel, similarityPrecision, dissimilaityPrecision);
}
private void output(int r, List<DistanceObject> distanceObjects, D similarityRange, D dissimilarityRange) throws UnableToComplyException {
try {
String fileName = "../Stock4b/palme_elki/ranges_rep_" + r + ".txt";
File file = new File(fileName);
file.getParentFile().mkdirs();
PrintStream outStream = new PrintStream(new FileOutputStream(file));
outStream.println("similarity-range " + similarityRange);
outStream.println("dissimilarity-range " + dissimilarityRange);
outStream.println(distanceObjects.get(0).getDescription());
for (DistanceObject object : distanceObjects) {
outStream.println(object);
}
}
catch (FileNotFoundException e) {
throw new UnableToComplyException(e);
}
}
public class Ranges {
String id;
ClassLabel classLabel;
D similarityPrecision;
D dissimilarityPrecision;
public Ranges(String id, ClassLabel classLabel, D similarityPrecision, D dissimilarityPrecision) {
this.id = id;
this.classLabel = classLabel;
this.similarityPrecision = similarityPrecision;
this.dissimilarityPrecision = dissimilarityPrecision;
}
public String toString() {
return id + " " + classLabel + " " + similarityPrecision + " " + dissimilarityPrecision;
}
public String getDescription() {
return "id class-label similarity-precision dissimilarity-precision";
}
}
public class DistanceObject implements Comparable<DistanceObject> {
String id1;
String id2;
ClassLabel classLabel1;
ClassLabel classLabel2;
boolean sameClass;
D distance;
double similarityPrecision;
double dissimilarityPrecision;
public DistanceObject(String id1, String id2, ClassLabel classLabel1, ClassLabel classLabel2, D distance) {
this.id1 = id1;
this.id2 = id2;
this.classLabel1 = classLabel1;
this.classLabel2 = classLabel2;
this.sameClass = classLabel1.equals(classLabel2);
this.distance = distance;
}
public String getDescription() {
return "id1 id2 class_label1 class_label2 same_class distance similarity-precision dissimilarity-precision";
}
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
public String toString() {
StringBuffer result = new StringBuffer();
result.append(id1);
result.append(" ");
result.append(id2);
result.append(" ");
result.append(classLabel1);
result.append(" ");
result.append(classLabel2);
result.append(" ");
result.append(sameClass);
result.append(" ");
result.append(distance);
result.append(" ");
result.append(similarityPrecision);
result.append(" ");
result.append(dissimilarityPrecision);
result.append(" ");
return result.toString();
}
/**
* @see Comparable#compareTo(Object)
*/
public int compareTo(DistanceObject o) {
int comp = this.distance.compareTo(o.distance);
if (comp != 0) return comp;
comp = this.id1.compareTo(o.id2);
if (comp != 0) return comp;
return this.id2.compareTo(o.id2);
}
}
}
|
src/de/lmu/ifi/dbs/algorithm/clustering/PALME.java
|
package de.lmu.ifi.dbs.algorithm.clustering;
import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.algorithm.result.Result;
import de.lmu.ifi.dbs.algorithm.result.clustering.PALMEResult;
import de.lmu.ifi.dbs.data.ClassLabel;
import de.lmu.ifi.dbs.data.DatabaseObject;
import de.lmu.ifi.dbs.data.MultiRepresentedObject;
import de.lmu.ifi.dbs.database.AssociationID;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.AbstractDistanceFunction;
import de.lmu.ifi.dbs.distance.Distance;
import de.lmu.ifi.dbs.distance.RepresentationSelectingDistanceFunction;
import de.lmu.ifi.dbs.utilities.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.*;
/**
* TODO: comment and new name
*
* @author Elke Achtert (<a href="mailto:[email protected]">[email protected]</a>)
*/
public class PALME<O extends DatabaseObject, D extends Distance<D>, M extends MultiRepresentedObject<O>> extends AbstractAlgorithm<M> {
/**
* The distance function for the single representations.
*/
private RepresentationSelectingDistanceFunction<O, M, D> mr_distanceFunction;
/**
* The result of this algorithm.
*/
private Result<M> result;
public PALME() {
super();
}
/**
* The run method encapsulated in measure of runtime. An extending class
* needs not to take care of runtime itself.
*
* @param database the database to run the algorithm on
* @throws IllegalStateException if the algorithm has not been initialized properly (e.g. the
* setParameters(String[]) method has been failed to be called).
*/
protected void runInTime(Database<M> database) throws IllegalStateException {
try {
if (database.size() == 0) {
result = new PALMEResult<O, D, M>(database);
return;
}
System.out.println("database.size " + database.size());
mr_distanceFunction.setDatabase(database, isVerbose());
int numberOfRepresentations = database.get(database.iterator().next()).getNumberOfRepresentations();
Map<ClassLabel, Set<Integer>> classMap = determineClassPartitions(database);
Progress progress = new Progress(2 * database.size() * numberOfRepresentations);
List<D> maxDistances = new ArrayList<D>(numberOfRepresentations);
List<List<Ranges>> resultList = new ArrayList<List<Ranges>>(numberOfRepresentations);
for (int r = 0; r < numberOfRepresentations; r++) {
int processed = 0;
if (isVerbose()) {
System.out.println("Representation " + (r + 1));
}
mr_distanceFunction.setCurrentRepresentationIndex(r);
List<DistanceObject> distances = determineDistances(database, progress);
for (DistanceObject object: distances) {
}
// maxDistances.add(maxDist);
// outputRanges(r, rangesList);
// resultList.add(rangesList);
}
this.result = new PALMEResult<O, D, M>(database);
}
catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws IllegalArgumentException {
String[] remainungParams = super.setParameters(args);
mr_distanceFunction = new RepresentationSelectingDistanceFunction<O, M, D>();
return mr_distanceFunction.setParameters(remainungParams);
}
/**
* Returns the result of the algorithm.
*
* @return the result of the algorithm
*/
public Result<M> getResult() {
return result;
}
/**
* Returns a description of the algorithm.
*
* @return a description of the algorithm
*/
public Description getDescription() {
// todo
return new Description("PALME",
"algorithm without name ;-)",
"First it determines the Recall and Precision levels for each representation " +
"of a database containing multirepresented_old objects according to a training set. " +
"Second a multirepresented_old version of OPTICS will be applied.",
"unpublished");
}
private Map<ClassLabel, Set<Integer>> determineClassPartitions(Database<M> database) throws IllegalStateException {
Map<ClassLabel, Set<Integer>> classMap = new HashMap<ClassLabel, Set<Integer>>();
Iterator<Integer> it = database.iterator();
while (it.hasNext()) {
Integer id = it.next();
ClassLabel classLabel = (ClassLabel) database.getAssociation(AssociationID.CLASS, id);
Set<Integer> ids = classMap.get(classLabel);
if (ids == null) {
ids = new HashSet<Integer>();
classMap.put(classLabel, ids);
}
ids.add(id);
}
return classMap;
}
private List<DistanceObject> determineDistances(Database<M> database, Progress progress) {
int processed = 0;
if (isVerbose()) {
System.out.println(" ...determine distances ");
}
List<DistanceObject> distances = new ArrayList<DistanceObject>((database.size() * database.size() - 1) / 2);
for (Iterator<Integer> it1 = database.iterator(); it1.hasNext();) {
Integer id1 = it1.next();
ClassLabel classLabel1 = (ClassLabel) database.getAssociation(AssociationID.CLASS, id1);
String externalID1 = (String) database.getAssociation(AssociationID.EXTERNAL_ID, id1);
for (Iterator<Integer> it2 = database.iterator(); it2.hasNext();) {
Integer id2 = it2.next();
ClassLabel classLabel2 = (ClassLabel) database.getAssociation(AssociationID.CLASS, id2);
String externalID2 = (String) database.getAssociation(AssociationID.EXTERNAL_ID, id2);
D distance = mr_distanceFunction.distance(id1, id2);
DistanceObject object = new DistanceObject(externalID1, externalID2, classLabel1, classLabel2, distance);
distances.add(object);
}
if (isVerbose()) {
progress.setProcessed(processed++);
System.out.print("\r" + progress.toString());
}
}
Collections.sort(distances);
return distances;
}
private void determineProbabilityRanges(List<DistanceObject> distanceObjects) {
for (DistanceObject distanceObject: distanceObjects) {
}
}
private Ranges getProbabilityRanges(String id, ClassLabel classLabel, Set<Integer> desiredSet, List<QueryResult<D>> neighbors) {
if (neighbors.isEmpty())
throw new IllegalArgumentException("Empty neighbors!");
D similarityPrecision = null;
D dissimilaityPrecision = null;
double foundAndDesired = 0;
double inverseFoundAndDesired = 0;
double found = 0;
double inverseFound = 0;
double ws = (1.0 * desiredSet.size()) / (1.0 * neighbors.size());
double pp = ws + (1.0 - ws) * 0.9;
double ipp = (1 - ws) + ws * 0.9;
// System.out.println("ws = " + ws);
// System.out.println("pp = " + pp);
// System.out.println("ipp = " + ipp);
int size = neighbors.size() - 1;
for (int i = 0; i <= size; i++) {
found++;
QueryResult<D> neighbor = neighbors.get(i);
if (desiredSet.contains(neighbor.getID())) {
foundAndDesired++;
}
// precision
double p = foundAndDesired / found;
if (p >= pp) {
similarityPrecision = neighbor.getDistance();
}
inverseFound++;
QueryResult<D> i_neighbor = neighbors.get(size - i);
if (! desiredSet.contains(i_neighbor.getID())) {
inverseFoundAndDesired++;
}
// inverse precision
double ip = inverseFoundAndDesired / inverseFound;
if (ip >= ipp)
dissimilaityPrecision = i_neighbor.getDistance();
}
if (dissimilaityPrecision == null) {
dissimilaityPrecision = neighbors.get(neighbors.size() - 1).getDistance();
}
if (similarityPrecision == null) {
similarityPrecision = neighbors.get(0).getDistance();
}
return new Ranges(id, classLabel, similarityPrecision, dissimilaityPrecision);
}
private void output(int r, List<DistanceObject> distanceObjects) throws UnableToComplyException {
try {
String fileName = "../Stock4b/palme_elki/ranges_rep_" + r + ".txt";
File file = new File(fileName);
file.getParentFile().mkdirs();
PrintStream outStream = new PrintStream(new FileOutputStream(file));
outStream.println(distanceObjects.get(0).getDescription());
for (DistanceObject object : distanceObjects) {
outStream.println(object);
}
}
catch (FileNotFoundException e) {
throw new UnableToComplyException(e);
}
}
public class Ranges {
String id;
ClassLabel classLabel;
D similarityPrecision;
D dissimilarityPrecision;
public Ranges(String id, ClassLabel classLabel, D similarityPrecision, D dissimilarityPrecision) {
this.id = id;
this.classLabel = classLabel;
this.similarityPrecision = similarityPrecision;
this.dissimilarityPrecision = dissimilarityPrecision;
}
public String toString() {
return id + " " + classLabel + " " + similarityPrecision + " " + dissimilarityPrecision;
}
public String getDescription() {
return "id class-label similarity-precision dissimilarity-precision";
}
}
public class DistanceObject implements Comparable<DistanceObject> {
String id1;
String id2;
ClassLabel classLabel1;
ClassLabel classLabel2;
boolean sameClass;
D distance;
D similarityPrecision;
D dissimilarityPrecision;
public DistanceObject(String id1, String id2, ClassLabel classLabel1, ClassLabel classLabel2, D distance) {
this.id1 = id1;
this.id2 = id2;
this.classLabel1 = classLabel1;
this.classLabel2 = classLabel2;
this.sameClass = classLabel1.equals(classLabel2);
this.distance = distance;
}
public String getDescription() {
return "id1 id2 class_label1 class_label2 same_class distance similarity-precision dissimilarity-precision";
}
/**
* @see Comparable#compareTo(Object)
*/
public int compareTo(DistanceObject o) {
int comp = this.distance.compareTo(o.distance);
if (comp != 0) return comp;
comp = this.id1.compareTo(o.id2);
if (comp != 0) return comp;
return this.id2.compareTo(o.id2);
}
}
}
|
refactoring PALME
|
src/de/lmu/ifi/dbs/algorithm/clustering/PALME.java
|
refactoring PALME
|
<ide><path>rc/de/lmu/ifi/dbs/algorithm/clustering/PALME.java
<ide> import de.lmu.ifi.dbs.data.MultiRepresentedObject;
<ide> import de.lmu.ifi.dbs.database.AssociationID;
<ide> import de.lmu.ifi.dbs.database.Database;
<del>import de.lmu.ifi.dbs.distance.AbstractDistanceFunction;
<ide> import de.lmu.ifi.dbs.distance.Distance;
<ide> import de.lmu.ifi.dbs.distance.RepresentationSelectingDistanceFunction;
<del>import de.lmu.ifi.dbs.utilities.*;
<add>import de.lmu.ifi.dbs.utilities.Description;
<add>import de.lmu.ifi.dbs.utilities.Progress;
<add>import de.lmu.ifi.dbs.utilities.QueryResult;
<add>import de.lmu.ifi.dbs.utilities.UnableToComplyException;
<ide>
<ide> import java.io.File;
<ide> import java.io.FileNotFoundException;
<ide> for (int r = 0; r < numberOfRepresentations; r++) {
<ide> int processed = 0;
<ide> if (isVerbose()) {
<del> System.out.println("Representation " + (r + 1));
<add> System.out.println("\nRepresentation " + (r + 1));
<ide> }
<ide> mr_distanceFunction.setCurrentRepresentationIndex(r);
<ide>
<del> List<DistanceObject> distances = determineDistances(database, progress);
<del> for (DistanceObject object: distances) {
<del>
<add> List<DistanceObject> distances = determineDistances(database, progress, r);
<add>
<add>
<add> D similarityRange = null;
<add> D dissimilarityRange = null;
<add> double foundAndDesired = 0;
<add> double inverseFoundAndDesired = 0;
<add> for (int i = 0; i < distances.size(); i++) {
<add> DistanceObject distanceObject = distances.get(i);
<add> if (distanceObject.sameClass) {
<add> foundAndDesired++;
<add> }
<add> distanceObject.similarityPrecision = foundAndDesired / (i+1);
<add> if (distanceObject.similarityPrecision > 0.9) {
<add> similarityRange = distanceObject.distance;
<add> }
<add>
<add> DistanceObject inverseDistanceObject = distances.get(distances.size() - 1 - i);
<add> if (! inverseDistanceObject.sameClass) {
<add> inverseFoundAndDesired++;
<add> }
<add> inverseDistanceObject.dissimilarityPrecision = inverseFoundAndDesired / (i+1);
<add> if (inverseDistanceObject.dissimilarityPrecision > 0.9) {
<add> dissimilarityRange = inverseDistanceObject.distance;
<add> }
<ide> }
<add>
<add> output(r, distances, similarityRange, dissimilarityRange);
<ide>
<ide> // maxDistances.add(maxDist);
<ide> // outputRanges(r, rangesList);
<ide> return classMap;
<ide> }
<ide>
<del> private List<DistanceObject> determineDistances(Database<M> database, Progress progress) {
<del> int processed = 0;
<add> private List<DistanceObject> determineDistances(Database<M> database, Progress progress, int r) {
<add> int processed = r * database.size();
<ide> if (isVerbose()) {
<del> System.out.println(" ...determine distances ");
<add> System.out.println("... determine distances");
<ide> }
<ide>
<ide> List<DistanceObject> distances = new ArrayList<DistanceObject>((database.size() * database.size() - 1) / 2);
<ide>
<ide> for (Iterator<Integer> it2 = database.iterator(); it2.hasNext();) {
<ide> Integer id2 = it2.next();
<add> if (id1 >= id2) continue;
<ide> ClassLabel classLabel2 = (ClassLabel) database.getAssociation(AssociationID.CLASS, id2);
<ide> String externalID2 = (String) database.getAssociation(AssociationID.EXTERNAL_ID, id2);
<ide>
<ide> }
<ide>
<ide> if (isVerbose()) {
<del> progress.setProcessed(processed++);
<add> progress.setProcessed(++processed);
<ide> System.out.print("\r" + progress.toString());
<ide> }
<ide> }
<ide>
<ide> Collections.sort(distances);
<ide> return distances;
<del> }
<del>
<del> private void determineProbabilityRanges(List<DistanceObject> distanceObjects) {
<del> for (DistanceObject distanceObject: distanceObjects) {
<del>
<del> }
<del>
<ide> }
<ide>
<ide> private Ranges getProbabilityRanges(String id, ClassLabel classLabel, Set<Integer> desiredSet, List<QueryResult<D>> neighbors) {
<ide> return new Ranges(id, classLabel, similarityPrecision, dissimilaityPrecision);
<ide> }
<ide>
<del> private void output(int r, List<DistanceObject> distanceObjects) throws UnableToComplyException {
<add> private void output(int r, List<DistanceObject> distanceObjects, D similarityRange, D dissimilarityRange) throws UnableToComplyException {
<ide> try {
<ide> String fileName = "../Stock4b/palme_elki/ranges_rep_" + r + ".txt";
<ide> File file = new File(fileName);
<ide> file.getParentFile().mkdirs();
<ide> PrintStream outStream = new PrintStream(new FileOutputStream(file));
<ide>
<add> outStream.println("similarity-range " + similarityRange);
<add> outStream.println("dissimilarity-range " + dissimilarityRange);
<ide> outStream.println(distanceObjects.get(0).getDescription());
<ide> for (DistanceObject object : distanceObjects) {
<ide> outStream.println(object);
<ide> ClassLabel classLabel2;
<ide> boolean sameClass;
<ide> D distance;
<del> D similarityPrecision;
<del> D dissimilarityPrecision;
<add> double similarityPrecision;
<add> double dissimilarityPrecision;
<ide>
<ide> public DistanceObject(String id1, String id2, ClassLabel classLabel1, ClassLabel classLabel2, D distance) {
<ide> this.id1 = id1;
<ide> }
<ide>
<ide> /**
<add> * Returns a string representation of the object.
<add> *
<add> * @return a string representation of the object.
<add> */
<add> public String toString() {
<add> StringBuffer result = new StringBuffer();
<add> result.append(id1);
<add> result.append(" ");
<add> result.append(id2);
<add> result.append(" ");
<add> result.append(classLabel1);
<add> result.append(" ");
<add> result.append(classLabel2);
<add> result.append(" ");
<add> result.append(sameClass);
<add> result.append(" ");
<add> result.append(distance);
<add> result.append(" ");
<add> result.append(similarityPrecision);
<add> result.append(" ");
<add> result.append(dissimilarityPrecision);
<add> result.append(" ");
<add> return result.toString();
<add> }
<add>
<add> /**
<ide> * @see Comparable#compareTo(Object)
<ide> */
<ide> public int compareTo(DistanceObject o) {
|
|
Java
|
mit
|
3d2addfa084ba652ed9432e5a0925269f9f408bc
| 0 |
PaddySmalls/JScheme
|
package hdm.pk070.jscheme.symbolTable;
import hdm.pk070.jscheme.SchemeConstants;
import hdm.pk070.jscheme.error.SchemeError;
import hdm.pk070.jscheme.hash.HashAlgProvider;
import hdm.pk070.jscheme.hash.impl.StandardHashAlgProvider;
import hdm.pk070.jscheme.obj.type.SchemeSymbol;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Objects;
/**
*
*/
public class SchemeSymbolTable {
private static final Logger LOGGER = LogManager.getLogger(SchemeSymbolTable.class.getName());
private static int tableSize = SchemeConstants.INITIAL_SYMBOL_TABLE_SIZE;
private static SchemeSymbolTable schemeSymbolTable;
private SchemeSymbol[] symbolTable;
private int tableFillSize;
private HashAlgProvider hashAlgProvider;
public static SchemeSymbolTable getInstance() {
return withHashAlgorithm(new StandardHashAlgProvider());
}
public static SchemeSymbolTable withHashAlgorithm(HashAlgProvider hashAlgProvider) {
if (Objects.isNull(schemeSymbolTable)) {
schemeSymbolTable = new SchemeSymbolTable(hashAlgProvider);
}
return schemeSymbolTable;
}
private SchemeSymbolTable(HashAlgProvider hashAlgProvider) {
this.hashAlgProvider = hashAlgProvider;
this.symbolTable = new SchemeSymbol[tableSize];
this.tableFillSize = 0;
}
public SchemeSymbol getOrAdd(String symbolName) throws SchemeError {
Objects.requireNonNull(symbolName);
int nextIndex;
int hashVal = hashAlgProvider.computeHash(symbolName);
int startIndex = hashVal % tableSize;
SchemeSymbol symbol;
nextIndex = startIndex;
for (; ; ) {
// In case the current index marks a free slot
if (isFreeSlot(nextIndex)) {
SchemeSymbol schemeSymbol = new SchemeSymbol(symbolName);
addToTable(schemeSymbol, nextIndex);
incrementFillSize();
doRehashIfRequired();
return schemeSymbol;
}
// in case the slot is occupied: check if object in slot is searched symbol
symbol = symbolTable[nextIndex];
if (symbol.getValue().equals(symbolName)) {
// return symbol in slot 'nextIndex'
LOGGER.debug(String.format("Symbol '%s' already present in symbol table, gets returned", symbol
.toString()));
return symbol;
}
// if the symbol at slot 'nextIndex' is not the symbol we searched for, we have
// a hash collision > store new symbol at next slot available
nextIndex = ++nextIndex % tableSize;
// if there's no free slot available in the table, throw error
if (nextIndex == startIndex) {
throw new SchemeError("Symbol table problem!");
}
}
}
private void doRehashIfRequired() throws SchemeError {
if (tableFillSize > 0.75 * tableSize) {
LOGGER.debug("Rehash initiated ...");
startRehash();
}
}
private void startRehash() throws SchemeError {
int oldTableSize = tableSize;
LOGGER.debug(String.format("Rehash: Old symbol table size is %d", oldTableSize));
int newTableSize = getNextPowerOfTwoMinusOne();
tableSize = newTableSize;
LOGGER.debug(String.format("Rehash: New table size is %d", newTableSize));
SchemeSymbol[] oldSymbolTable = symbolTable;
symbolTable = new SchemeSymbol[newTableSize];
for (int oldTableIndex = 0; oldTableIndex < oldTableSize; oldTableIndex++) {
SchemeSymbol oldSymbol = oldSymbolTable[oldTableIndex];
// in case oldSymbol is not null
if (Objects.nonNull(oldSymbol)) {
// re-compute hash
int hash = hashAlgProvider.computeHash(oldSymbol.getValue());
int startIndex = hash % newTableSize;
int nextIndex = startIndex;
// same old story: search for free slot
for (; ; ) {
if (isFreeSlot(nextIndex)) {
// if slot is free: add symbol and end loop
symbolTable[nextIndex] = oldSymbol;
break;
}
// increment search index if slot is occupied
nextIndex = ++nextIndex % newTableSize;
// if the whole table has been searched, there's no free slot > error!
if (nextIndex == startIndex) {
// switch back to old table in case of there's no free slot
symbolTable = oldSymbolTable;
LOGGER.debug("Symbol table error. No free slot found!");
throw new SchemeError("Symbol table problem!");
}
}
}
}
}
private int getNextPowerOfTwoMinusOne() {
return (tableSize + 1) * 2 - 1;
}
private void incrementFillSize() {
tableFillSize++;
}
private boolean isFreeSlot(int slotNum) {
if (slotNum > 0 && slotNum < tableSize) {
return Objects.isNull(symbolTable[slotNum]) ? true : false;
}
throw new IllegalArgumentException(String.format("symbolTable index must be between %d and %d!", 0,
(tableSize - 1)));
}
private void addToTable(SchemeSymbol symbol, int slotNum) {
symbolTable[slotNum] = symbol;
LOGGER.debug(String.format("Symbol '%s' has been added to symbol table", symbol.toString()));
}
}
|
src/main/java/hdm/pk070/jscheme/symbolTable/SchemeSymbolTable.java
|
package hdm.pk070.jscheme.symbolTable;
import hdm.pk070.jscheme.SchemeConstants;
import hdm.pk070.jscheme.error.SchemeError;
import hdm.pk070.jscheme.hash.HashAlgProvider;
import hdm.pk070.jscheme.hash.impl.StandardHashAlgProvider;
import hdm.pk070.jscheme.obj.type.SchemeSymbol;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Objects;
/**
*
*/
public class SchemeSymbolTable {
private static final Logger LOGGER = LogManager.getLogger(SchemeSymbolTable.class.getName());
private static int tableSize = SchemeConstants.INITIAL_SYMBOL_TABLE_SIZE;
private static SchemeSymbolTable schemeSymbolTable;
private SchemeSymbol[] symbolTable;
private int tableFillSize;
private HashAlgProvider hashAlgProvider;
public static SchemeSymbolTable getInstance() {
return withHashAlgorithm(new StandardHashAlgProvider());
}
public static SchemeSymbolTable withHashAlgorithm(HashAlgProvider hashAlgProvider) {
if (Objects.isNull(schemeSymbolTable)) {
schemeSymbolTable = new SchemeSymbolTable(hashAlgProvider);
}
return schemeSymbolTable;
}
private SchemeSymbolTable(HashAlgProvider hashAlgProvider) {
this.hashAlgProvider = hashAlgProvider;
this.symbolTable = new SchemeSymbol[tableSize];
this.tableFillSize = 0;
}
public SchemeSymbol getOrAdd(String symbolName) throws SchemeError {
Objects.requireNonNull(symbolName);
int nextIndex;
int hashVal = hashAlgProvider.computeHash(symbolName);
int startIndex = hashVal % tableSize;
SchemeSymbol symbol;
nextIndex = startIndex;
for (; ; ) {
// In case the current index marks a free slot
if (isFreeSlot(nextIndex)) {
SchemeSymbol schemeSymbol = new SchemeSymbol(symbolName);
addToTable(schemeSymbol, nextIndex);
incrementFillSize();
doRehashIfRequired();
return schemeSymbol;
}
// in case the slot is occupied: check if object in slot is searched symbol
symbol = symbolTable[nextIndex];
if (symbol.getValue().equals(symbolName)) {
// return symbol in slot 'nextIndex'
LOGGER.debug(String.format("Symbol '%s' already present in symbol table, gets returned", symbol
.toString()));
return symbol;
}
// if the symbol at slot 'nextIndex' is not the symbol we searched for, we have
// a hash collision > store new symbol at next slot available
nextIndex = ++nextIndex % tableSize;
// if there's no free slot available in the table, throw error
if (nextIndex == startIndex) {
throw new SchemeError("Symbol table problem!");
}
}
}
private void doRehashIfRequired() throws SchemeError {
if (tableFillSize > 0.75 * tableSize) {
LOGGER.debug("Rehash initiated ...");
startRehash();
}
}
private void startRehash() throws SchemeError {
int oldTableSize = tableSize;
LOGGER.debug(String.format("Old symbol table size is %d", oldTableSize));
int newTableSize = getNextPowerOfTwoMinusOne();
tableSize = newTableSize;
LOGGER.debug(String.format("New table size is %d", newTableSize));
SchemeSymbol[] oldSymbolTable = symbolTable;
symbolTable = new SchemeSymbol[newTableSize];
for (int oldTableIndex = 0; oldTableIndex < oldTableSize; oldTableIndex++) {
SchemeSymbol oldSymbol = oldSymbolTable[oldTableIndex];
// in case oldSymbol is not null
if (Objects.nonNull(oldSymbol)) {
// re-compute hash
int hash = hashAlgProvider.computeHash(oldSymbol.getValue());
int startIndex = hash % newTableSize;
int nextIndex = startIndex;
// same old story: search for free slot
for (; ; ) {
if (isFreeSlot(nextIndex)) {
// if slot is free: add symbol and end loop
symbolTable[nextIndex] = oldSymbol;
break;
}
// increment search index if slot is occupied
nextIndex = ++nextIndex % newTableSize;
// if the whole table has been searched, there's no free slot > error!
if (nextIndex == startIndex) {
// switch back to old table in case of there's no free slot
symbolTable = oldSymbolTable;
LOGGER.debug("Symbol table error. No free slot found!");
throw new SchemeError("Symbol table problem!");
}
}
}
}
}
private int getNextPowerOfTwoMinusOne() {
return (tableSize + 1) * 2 - 1;
}
private void incrementFillSize() {
tableFillSize++;
}
private boolean isFreeSlot(int slotNum) {
if (slotNum > 0 && slotNum < tableSize) {
return Objects.isNull(symbolTable[slotNum]) ? true : false;
}
throw new IllegalArgumentException(String.format("symbolTable index must be between %d and %d!", 0,
(tableSize - 1)));
}
private void addToTable(SchemeSymbol symbol, int slotNum) {
symbolTable[slotNum] = symbol;
LOGGER.debug(String.format("Symbol '%s' has been added to symbol table", symbol.toString()));
}
}
|
Modified logging output
|
src/main/java/hdm/pk070/jscheme/symbolTable/SchemeSymbolTable.java
|
Modified logging output
|
<ide><path>rc/main/java/hdm/pk070/jscheme/symbolTable/SchemeSymbolTable.java
<ide>
<ide> private void startRehash() throws SchemeError {
<ide> int oldTableSize = tableSize;
<del> LOGGER.debug(String.format("Old symbol table size is %d", oldTableSize));
<add> LOGGER.debug(String.format("Rehash: Old symbol table size is %d", oldTableSize));
<ide>
<ide> int newTableSize = getNextPowerOfTwoMinusOne();
<ide> tableSize = newTableSize;
<del> LOGGER.debug(String.format("New table size is %d", newTableSize));
<add> LOGGER.debug(String.format("Rehash: New table size is %d", newTableSize));
<ide>
<ide> SchemeSymbol[] oldSymbolTable = symbolTable;
<ide> symbolTable = new SchemeSymbol[newTableSize];
|
|
Java
|
epl-1.0
|
ef31c925bfde8187b325596d1ddd5bef74e29632
| 0 |
opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt
|
/*
* Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.netvirt.natservice.internal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.opendaylight.controller.liblldp.NetUtils;
import org.opendaylight.controller.liblldp.PacketException;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
import org.opendaylight.genius.mdsalutil.ActionInfo;
import org.opendaylight.genius.mdsalutil.FlowEntity;
import org.opendaylight.genius.mdsalutil.InstructionInfo;
import org.opendaylight.genius.mdsalutil.MDSALUtil;
import org.opendaylight.genius.mdsalutil.MatchInfo;
import org.opendaylight.genius.mdsalutil.MetaDataUtil;
import org.opendaylight.genius.mdsalutil.NwConstants;
import org.opendaylight.genius.mdsalutil.actions.ActionOutput;
import org.opendaylight.genius.mdsalutil.actions.ActionPushVlan;
import org.opendaylight.genius.mdsalutil.actions.ActionSetDestinationIp;
import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetSource;
import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldTunnelId;
import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldVlanVid;
import org.opendaylight.genius.mdsalutil.actions.ActionSetSourceIp;
import org.opendaylight.genius.mdsalutil.actions.ActionSetTcpDestinationPort;
import org.opendaylight.genius.mdsalutil.actions.ActionSetTcpSourcePort;
import org.opendaylight.genius.mdsalutil.actions.ActionSetUdpDestinationPort;
import org.opendaylight.genius.mdsalutil.actions.ActionSetUdpSourcePort;
import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
import org.opendaylight.genius.mdsalutil.instructions.InstructionWriteMetadata;
import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
import org.opendaylight.genius.mdsalutil.matches.MatchIpProtocol;
import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination;
import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Source;
import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
import org.opendaylight.genius.mdsalutil.matches.MatchTcpDestinationPort;
import org.opendaylight.genius.mdsalutil.matches.MatchTcpSourcePort;
import org.opendaylight.genius.mdsalutil.matches.MatchUdpDestinationPort;
import org.opendaylight.genius.mdsalutil.matches.MatchUdpSourcePort;
import org.opendaylight.genius.mdsalutil.packet.Ethernet;
import org.opendaylight.genius.mdsalutil.packet.IPv4;
import org.opendaylight.genius.mdsalutil.packet.TCP;
import org.opendaylight.genius.mdsalutil.packet.UDP;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetInterfaceFromIfIndexInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetInterfaceFromIfIndexInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetInterfaceFromIfIndexOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NaptEventHandler {
private static final Logger LOG = LoggerFactory.getLogger(NaptEventHandler.class);
private final DataBroker dataBroker;
private static IMdsalApiManager mdsalManager;
private final PacketProcessingService pktService;
private final OdlInterfaceRpcService interfaceManagerRpc;
private final NaptManager naptManager;
private IInterfaceManager interfaceManager;
public NaptEventHandler(final DataBroker dataBroker, final IMdsalApiManager mdsalManager,
final NaptManager naptManager,
final PacketProcessingService pktService,
final OdlInterfaceRpcService interfaceManagerRpc,
final IInterfaceManager interfaceManager) {
this.dataBroker = dataBroker;
NaptEventHandler.mdsalManager = mdsalManager;
this.naptManager = naptManager;
this.pktService = pktService;
this.interfaceManagerRpc = interfaceManagerRpc;
this.interfaceManager = interfaceManager;
}
// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
public void handleEvent(NAPTEntryEvent naptEntryEvent) {
/*
Flow programming logic of the OUTBOUND NAPT TABLE :
1) Get the internal IP address, port number, router ID from the event.
2) Use the NAPT service getExternalAddressMapping() to get the External IP and the port.
3) Build the flow for replacing the Internal IP and port with the External IP and port.
a) Write the matching criteria.
b) Match the router ID in the metadata.
d) Write the VPN ID to the metadata.
e) Write the other data.
f) Set the apply actions instruction with the action setfield.
4) Write the flow to the OUTBOUND NAPT Table and forward to FIB table for routing the traffic.
Flow programming logic of the INBOUND NAPT TABLE :
Same as Outbound table logic except that :
1) Build the flow for replacing the External IP and port with the Internal IP and port.
2) Match the VPN ID in the metadata.
3) Write the router ID to the metadata.
5) Write the flow to the INBOUND NAPT Table and forward to FIB table for routing the traffic.
*/
try {
Long routerId = naptEntryEvent.getRouterId();
LOG.info("NAT Service : handleEvent() entry for IP {}, port {}, routerID {}",
naptEntryEvent.getIpAddress(), naptEntryEvent.getPortNumber(), routerId);
//Get the DPN ID
BigInteger dpnId = NatUtil.getPrimaryNaptfromRouterId(dataBroker, routerId);
long bgpVpnId = NatConstants.INVALID_ID;
if (dpnId == null) {
LOG.warn("NAT Service : dpnId is null. Assuming the router ID {} as the BGP VPN ID and proceeding....",
routerId);
bgpVpnId = routerId;
LOG.debug("NAT Service : BGP VPN ID {}", bgpVpnId);
String vpnName = NatUtil.getRouterName(dataBroker, bgpVpnId);
String routerName = NatUtil.getRouterIdfromVpnInstance(dataBroker, vpnName);
if (routerName == null) {
LOG.error("NAT Service: Unable to find router for VpnName {}", vpnName);
return;
}
routerId = NatUtil.getVpnId(dataBroker, routerName);
LOG.debug("NAT Service : Router ID {}", routerId);
dpnId = NatUtil.getPrimaryNaptfromRouterId(dataBroker, routerId);
if (dpnId == null) {
LOG.error("NAT Service : dpnId is null for the router {}", routerId);
return;
}
}
if (naptEntryEvent.getOperation() == NAPTEntryEvent.Operation.ADD) {
LOG.debug("NAT Service : Inside Add operation of NaptEventHandler");
// Get the External Gateway MAC Address
String extGwMacAddress = NatUtil.getExtGwMacAddFromRouterId(dataBroker, routerId);
if (extGwMacAddress != null) {
LOG.debug("NAT Service : External Gateway MAC address {} found for External Router ID {}",
extGwMacAddress, routerId);
} else {
LOG.error("NAT Service : No External Gateway MAC address found for External Router ID {}",
routerId);
return;
}
//Get the external network ID from the ExternalRouter model
Uuid networkId = NatUtil.getNetworkIdFromRouterId(dataBroker, routerId);
if (networkId == null) {
LOG.error("NAT Service : networkId is null");
return;
}
//Get the VPN ID from the ExternalNetworks model
Uuid vpnUuid = NatUtil.getVpnIdfromNetworkId(dataBroker, networkId);
if (vpnUuid == null) {
LOG.error("NAT Service : vpnUuid is null");
return;
}
Long vpnId = NatUtil.getVpnId(dataBroker, vpnUuid.getValue());
//Get the internal IpAddress, internal port number from the event
String internalIpAddress = naptEntryEvent.getIpAddress();
int internalPort = naptEntryEvent.getPortNumber();
SessionAddress internalAddress = new SessionAddress(internalIpAddress, internalPort);
NAPTEntryEvent.Protocol protocol = naptEntryEvent.getProtocol();
//Get the external IP address for the corresponding internal IP address
SessionAddress externalAddress =
naptManager.getExternalAddressMapping(routerId, internalAddress, naptEntryEvent.getProtocol());
if (externalAddress == null) {
LOG.error("NAT Service : externalAddress is null");
return;
}
// Build and install the NAPT translation flows in the Outbound and Inbound NAPT tables
if (!naptEntryEvent.isPktProcessed()) {
// Added External Gateway MAC Address
buildAndInstallNatFlows(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, vpnId, routerId, bgpVpnId,
internalAddress, externalAddress, protocol, extGwMacAddress);
buildAndInstallNatFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE, vpnId, routerId, bgpVpnId,
externalAddress, internalAddress, protocol, extGwMacAddress);
}
//Send Packetout - tcp or udp packets which got punted to controller.
BigInteger metadata = naptEntryEvent.getPacketReceived().getMatch().getMetadata().getMetadata();
byte[] inPayload = naptEntryEvent.getPacketReceived().getPayload();
Ethernet ethPkt = new Ethernet();
if (inPayload != null) {
try {
ethPkt.deserialize(inPayload, 0, inPayload.length * NetUtils.NumBitsInAByte);
} catch (Exception e) {
LOG.warn("NAT Service : Failed to decode Packet", e);
return;
}
}
long portTag = MetaDataUtil.getLportFromMetadata(metadata).intValue();
LOG.debug("NAT Service : portTag from incoming packet is {}", portTag);
String interfaceName = getInterfaceNameFromTag(portTag);
LOG.debug("NAT Service : interfaceName fetched from portTag is {}", interfaceName);
org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
.interfaces.Interface iface = null;
int vlanId = 0;
iface = interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
if (iface == null) {
LOG.error("NAT Service : Unable to read interface {} from config DataStore", interfaceName);
return;
}
IfL2vlan ifL2vlan = iface.getAugmentation(IfL2vlan.class);
if (ifL2vlan != null && ifL2vlan.getVlanId() != null) {
vlanId = ifL2vlan.getVlanId().getValue() == null ? 0 : ifL2vlan.getVlanId().getValue();
}
InterfaceInfo infInfo = interfaceManager.getInterfaceInfoFromOperationalDataStore(interfaceName);
if (infInfo != null) {
LOG.debug("NAT Service : portName fetched from interfaceManager is {}", infInfo.getPortName());
}
byte[] pktOut = buildNaptPacketOut(ethPkt);
List<ActionInfo> actionInfos = new ArrayList<>();
if (ethPkt.getPayload() instanceof IPv4) {
IPv4 ipPkt = (IPv4) ethPkt.getPayload();
if ((ipPkt.getPayload() instanceof TCP) || (ipPkt.getPayload() instanceof UDP)) {
if (ethPkt.getEtherType() != (short) NwConstants.ETHTYPE_802_1Q) {
// VLAN Access port
if (infInfo != null) {
LOG.debug("NAT Service : vlanId is {}", vlanId);
if (vlanId != 0) {
// Push vlan
actionInfos.add(new ActionPushVlan(0));
actionInfos.add(new ActionSetFieldVlanVid(1, vlanId));
} else {
LOG.debug("NAT Service : No vlanId {}, may be untagged", vlanId);
}
} else {
LOG.error("NAT Service : error in getting interfaceInfo");
return;
}
} else {
// VLAN Trunk Port
LOG.debug("NAT Service : This is VLAN Trunk port case - need not do VLAN tagging again");
}
}
}
if (pktOut != null) {
sendNaptPacketOut(pktOut, infInfo, actionInfos, routerId);
} else {
LOG.warn("NAT Service : Unable to send Packet Out");
}
} else {
LOG.debug("NAT Service : Inside delete Operation of NaptEventHandler");
removeNatFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE, routerId, naptEntryEvent.getIpAddress(),
naptEntryEvent.getPortNumber());
}
LOG.info("NAT Service : handleNaptEvent() exited for IP {}, port {}, routerID : {}",
naptEntryEvent.getIpAddress(), naptEntryEvent.getPortNumber(), routerId);
} catch (Exception e) {
LOG.error("NAT Service :Exception in NaptEventHandler.handleEvent() payload {}", naptEntryEvent, e);
}
}
public static void buildAndInstallNatFlows(BigInteger dpnId, short tableId, long vpnId, long routerId,
long bgpVpnId, SessionAddress actualSourceAddress,
SessionAddress translatedSourceAddress,
NAPTEntryEvent.Protocol protocol, String extGwMacAddress) {
LOG.debug("NAT Service : Build and install NAPT flows in InBound and OutBound tables for "
+ "dpnId {} and routerId {}", dpnId, routerId);
//Build the flow for replacing the actual IP and port with the translated IP and port.
int idleTimeout = 0;
if (tableId == NwConstants.OUTBOUND_NAPT_TABLE) {
idleTimeout = NatConstants.DEFAULT_NAPT_IDLE_TIMEOUT;
}
long intranetVpnId;
if (bgpVpnId != NatConstants.INVALID_ID) {
intranetVpnId = bgpVpnId;
} else {
intranetVpnId = routerId;
}
LOG.debug("NAT Service : Intranet VPN ID {}", intranetVpnId);
LOG.debug("NAT Service : Router ID {}", routerId);
String translatedIp = translatedSourceAddress.getIpAddress();
int translatedPort = translatedSourceAddress.getPortNumber();
String actualIp = actualSourceAddress.getIpAddress();
int actualPort = actualSourceAddress.getPortNumber();
String switchFlowRef =
NatUtil.getNaptFlowRef(dpnId, tableId, String.valueOf(routerId), actualIp, actualPort);
FlowEntity snatFlowEntity = MDSALUtil.buildFlowEntity(dpnId, tableId, switchFlowRef,
NatConstants.DEFAULT_NAPT_FLOW_PRIORITY, NatConstants.NAPT_FLOW_NAME, idleTimeout, 0,
NatUtil.getCookieNaptFlow(routerId),
buildAndGetMatchInfo(actualIp, actualPort, tableId, protocol, intranetVpnId, vpnId),
buildAndGetSetActionInstructionInfo(translatedIp, translatedPort, intranetVpnId, vpnId, tableId,
protocol, extGwMacAddress));
snatFlowEntity.setSendFlowRemFlag(true);
LOG.debug("NAT Service : Installing the NAPT flow in the table {} for the switch with the DPN ID {} ",
tableId, dpnId);
mdsalManager.syncInstallFlow(snatFlowEntity, 1);
LOG.trace("NAT Service : Exited buildAndInstallNatflows");
}
private static List<MatchInfo> buildAndGetMatchInfo(String ip, int port, short tableId,
NAPTEntryEvent.Protocol protocol, long segmentId, long vpnId) {
MatchInfo ipMatchInfo = null;
MatchInfo portMatchInfo = null;
MatchInfo protocolMatchInfo = null;
InetAddress ipAddress = null;
String ipAddressAsString = null;
try {
ipAddress = InetAddress.getByName(ip);
ipAddressAsString = ipAddress.getHostAddress();
} catch (UnknownHostException e) {
LOG.error("NAT Service : UnknowHostException in buildAndGetMatchInfo. Failed to build NAPT Flow for "
+ "ip {}", ipAddress);
return null;
}
MatchInfo metaDataMatchInfo = null;
if (tableId == NwConstants.OUTBOUND_NAPT_TABLE) {
ipMatchInfo = new MatchIpv4Source(ipAddressAsString, "32");
if (protocol == NAPTEntryEvent.Protocol.TCP) {
protocolMatchInfo = MatchIpProtocol.TCP;
portMatchInfo = new MatchTcpSourcePort(port);
} else if (protocol == NAPTEntryEvent.Protocol.UDP) {
protocolMatchInfo = MatchIpProtocol.UDP;
portMatchInfo = new MatchUdpSourcePort(port);
}
metaDataMatchInfo =
new MatchMetadata(MetaDataUtil.getVpnIdMetadata(segmentId), MetaDataUtil.METADATA_MASK_VRFID);
} else {
ipMatchInfo = new MatchIpv4Destination(ipAddressAsString, "32");
if (protocol == NAPTEntryEvent.Protocol.TCP) {
protocolMatchInfo = MatchIpProtocol.TCP;
portMatchInfo = new MatchTcpDestinationPort(port);
} else if (protocol == NAPTEntryEvent.Protocol.UDP) {
protocolMatchInfo = MatchIpProtocol.UDP;
portMatchInfo = new MatchUdpDestinationPort(port);
}
//metaDataMatchInfo = new MatchMetadata(BigInteger.valueOf(vpnId), MetaDataUtil.METADATA_MASK_VRFID);
}
ArrayList<MatchInfo> matchInfo = new ArrayList<>();
matchInfo.add(MatchEthernetType.IPV4);
matchInfo.add(ipMatchInfo);
matchInfo.add(protocolMatchInfo);
matchInfo.add(portMatchInfo);
if (tableId == NwConstants.OUTBOUND_NAPT_TABLE) {
matchInfo.add(metaDataMatchInfo);
}
return matchInfo;
}
private static List<InstructionInfo> buildAndGetSetActionInstructionInfo(String ipAddress, int port,
long segmentId, long vpnId,
short tableId,
NAPTEntryEvent.Protocol protocol,
String extGwMacAddress) {
ActionInfo ipActionInfo = null;
ActionInfo macActionInfo = null;
ActionInfo portActionInfo = null;
ArrayList<ActionInfo> listActionInfo = new ArrayList<>();
ArrayList<InstructionInfo> instructionInfo = new ArrayList<>();
switch (tableId) {
case NwConstants.OUTBOUND_NAPT_TABLE:
ipActionInfo = new ActionSetSourceIp(ipAddress);
// Added External Gateway MAC Address
macActionInfo = new ActionSetFieldEthernetSource(new MacAddress(extGwMacAddress));
if (protocol == NAPTEntryEvent.Protocol.TCP) {
portActionInfo = new ActionSetTcpSourcePort(port);
} else if (protocol == NAPTEntryEvent.Protocol.UDP) {
portActionInfo = new ActionSetUdpSourcePort(port);
}
// reset the split-horizon bit to allow traffic from tunnel to be sent back to the provider port
instructionInfo.add(new InstructionWriteMetadata(MetaDataUtil.getVpnIdMetadata(vpnId),
MetaDataUtil.METADATA_MASK_VRFID.or(MetaDataUtil.METADATA_MASK_SH_FLAG)));
break;
case NwConstants.INBOUND_NAPT_TABLE:
ipActionInfo = new ActionSetDestinationIp(ipAddress);
if (protocol == NAPTEntryEvent.Protocol.TCP) {
portActionInfo = new ActionSetTcpDestinationPort(port);
} else if (protocol == NAPTEntryEvent.Protocol.UDP) {
portActionInfo = new ActionSetUdpDestinationPort(port);
}
instructionInfo.add(new InstructionWriteMetadata(
MetaDataUtil.getVpnIdMetadata(segmentId), MetaDataUtil.METADATA_MASK_VRFID));
break;
default:
LOG.error("NAT Service : Neither OUTBOUND_NAPT_TABLE nor INBOUND_NAPT_TABLE matches with "
+ "input table id {}", tableId);
return null;
}
listActionInfo.add(ipActionInfo);
listActionInfo.add(portActionInfo);
if (macActionInfo != null) {
listActionInfo.add(macActionInfo);
LOG.debug("NAT Service : External GW MAC Address {} is found ", macActionInfo);
}
instructionInfo.add(new InstructionApplyActions(listActionInfo));
instructionInfo.add(new InstructionGotoTable(NwConstants.NAPT_PFIB_TABLE));
return instructionInfo;
}
void removeNatFlows(BigInteger dpnId, short tableId ,long segmentId, String ip, int port) {
if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
LOG.error("NAT Service : DPN ID {} is invalid" , dpnId);
}
LOG.debug("NAT Service : Remove NAPT flows for dpnId {}, segmentId {}, ip {} and port {} ",
dpnId, segmentId, ip, port);
//Build the flow with the port IP and port as the match info.
String switchFlowRef = NatUtil.getNaptFlowRef(dpnId, tableId, String.valueOf(segmentId), ip, port);
FlowEntity snatFlowEntity = NatUtil.buildFlowEntity(dpnId, tableId, switchFlowRef);
LOG.debug("NAT Service : Remove the flow in the table {} for the switch with the DPN ID {}",
NwConstants.INBOUND_NAPT_TABLE, dpnId);
mdsalManager.removeFlow(snatFlowEntity);
}
protected byte[] buildNaptPacketOut(Ethernet etherPkt) {
LOG.debug("NAT Service : About to build Napt Packet Out");
if (etherPkt.getPayload() instanceof IPv4) {
byte[] rawPkt;
IPv4 ipPkt = (IPv4) etherPkt.getPayload();
if ((ipPkt.getPayload() instanceof TCP) || (ipPkt.getPayload() instanceof UDP)) {
try {
rawPkt = etherPkt.serialize();
return rawPkt;
} catch (PacketException e2) {
LOG.error("failed to build NAPT Packet out ", e2);
return null;
}
} else {
LOG.error("NAT Service : Unable to build NaptPacketOut since its neither TCP nor UDP");
return null;
}
}
LOG.error("NAT Service : Unable to build NaptPacketOut since its not IPv4 packet");
return null;
}
private void sendNaptPacketOut(byte[] pktOut, InterfaceInfo infInfo, List<ActionInfo> actionInfos, Long routerId) {
LOG.trace("NAT Service: Sending packet out DpId {}, interfaceInfo {}", infInfo.getDpId(), infInfo);
// set inPort, and action as OFPP_TABLE so that it starts from table 0 (lowest table as per spec)
actionInfos.add(new ActionSetFieldTunnelId(2, BigInteger.valueOf(routerId)));
actionInfos.add(new ActionOutput(3, new Uri("0xfffffff9")));
NodeConnectorRef inPort = MDSALUtil.getNodeConnRef(infInfo.getDpId(), String.valueOf(infInfo.getPortNo()));
LOG.debug("NAT Service : inPort for packetout is being set to {}", String.valueOf(infInfo.getPortNo()));
TransmitPacketInput output = MDSALUtil.getPacketOut(actionInfos, pktOut, infInfo.getDpId().longValue(), inPort);
LOG.trace("NAT Service: Transmitting packet: {}",output);
this.pktService.transmitPacket(output);
}
private String getInterfaceNameFromTag(long portTag) {
String interfaceName = null;
GetInterfaceFromIfIndexInput input =
new GetInterfaceFromIfIndexInputBuilder().setIfIndex((int) portTag).build();
Future<RpcResult<GetInterfaceFromIfIndexOutput>> futureOutput =
interfaceManagerRpc.getInterfaceFromIfIndex(input);
try {
GetInterfaceFromIfIndexOutput output = futureOutput.get().getResult();
interfaceName = output.getInterfaceName();
} catch (InterruptedException | ExecutionException e) {
LOG.error("NAT Service : Error while retrieving the interfaceName from tag using "
+ "getInterfaceFromIfIndex RPC");
}
LOG.trace("NAT Service : Returning interfaceName {} for tag {} form getInterfaceNameFromTag",
interfaceName, portTag);
return interfaceName;
}
}
|
vpnservice/natservice/natservice-impl/src/main/java/org/opendaylight/netvirt/natservice/internal/NaptEventHandler.java
|
/*
* Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.netvirt.natservice.internal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.opendaylight.controller.liblldp.NetUtils;
import org.opendaylight.controller.liblldp.PacketException;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.genius.interfacemanager.globals.InterfaceInfo;
import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
import org.opendaylight.genius.mdsalutil.ActionInfo;
import org.opendaylight.genius.mdsalutil.FlowEntity;
import org.opendaylight.genius.mdsalutil.InstructionInfo;
import org.opendaylight.genius.mdsalutil.MDSALUtil;
import org.opendaylight.genius.mdsalutil.MatchInfo;
import org.opendaylight.genius.mdsalutil.MetaDataUtil;
import org.opendaylight.genius.mdsalutil.NwConstants;
import org.opendaylight.genius.mdsalutil.actions.ActionOutput;
import org.opendaylight.genius.mdsalutil.actions.ActionPushVlan;
import org.opendaylight.genius.mdsalutil.actions.ActionSetDestinationIp;
import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetSource;
import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldTunnelId;
import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldVlanVid;
import org.opendaylight.genius.mdsalutil.actions.ActionSetSourceIp;
import org.opendaylight.genius.mdsalutil.actions.ActionSetTcpDestinationPort;
import org.opendaylight.genius.mdsalutil.actions.ActionSetTcpSourcePort;
import org.opendaylight.genius.mdsalutil.actions.ActionSetUdpDestinationPort;
import org.opendaylight.genius.mdsalutil.actions.ActionSetUdpSourcePort;
import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
import org.opendaylight.genius.mdsalutil.instructions.InstructionWriteMetadata;
import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
import org.opendaylight.genius.mdsalutil.matches.MatchIpProtocol;
import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination;
import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Source;
import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
import org.opendaylight.genius.mdsalutil.matches.MatchTcpDestinationPort;
import org.opendaylight.genius.mdsalutil.matches.MatchTcpSourcePort;
import org.opendaylight.genius.mdsalutil.matches.MatchUdpDestinationPort;
import org.opendaylight.genius.mdsalutil.matches.MatchUdpSourcePort;
import org.opendaylight.genius.mdsalutil.packet.Ethernet;
import org.opendaylight.genius.mdsalutil.packet.IPv4;
import org.opendaylight.genius.mdsalutil.packet.TCP;
import org.opendaylight.genius.mdsalutil.packet.UDP;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetInterfaceFromIfIndexInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetInterfaceFromIfIndexInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetInterfaceFromIfIndexOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NaptEventHandler {
private static final Logger LOG = LoggerFactory.getLogger(NaptEventHandler.class);
private final DataBroker dataBroker;
private static IMdsalApiManager mdsalManager;
private final PacketProcessingService pktService;
private final OdlInterfaceRpcService interfaceManagerRpc;
private final NaptManager naptManager;
private IInterfaceManager interfaceManager;
public NaptEventHandler(final DataBroker dataBroker, final IMdsalApiManager mdsalManager,
final NaptManager naptManager,
final PacketProcessingService pktService,
final OdlInterfaceRpcService interfaceManagerRpc,
final IInterfaceManager interfaceManager) {
this.dataBroker = dataBroker;
NaptEventHandler.mdsalManager = mdsalManager;
this.naptManager = naptManager;
this.pktService = pktService;
this.interfaceManagerRpc = interfaceManagerRpc;
this.interfaceManager = interfaceManager;
}
// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
public void handleEvent(NAPTEntryEvent naptEntryEvent) {
/*
Flow programming logic of the OUTBOUND NAPT TABLE :
1) Get the internal IP address, port number, router ID from the event.
2) Use the NAPT service getExternalAddressMapping() to get the External IP and the port.
3) Build the flow for replacing the Internal IP and port with the External IP and port.
a) Write the matching criteria.
b) Match the router ID in the metadata.
d) Write the VPN ID to the metadata.
e) Write the other data.
f) Set the apply actions instruction with the action setfield.
4) Write the flow to the OUTBOUND NAPT Table and forward to FIB table for routing the traffic.
Flow programming logic of the INBOUND NAPT TABLE :
Same as Outbound table logic except that :
1) Build the flow for replacing the External IP and port with the Internal IP and port.
2) Match the VPN ID in the metadata.
3) Write the router ID to the metadata.
5) Write the flow to the INBOUND NAPT Table and forward to FIB table for routing the traffic.
*/
try {
Long routerId = naptEntryEvent.getRouterId();
LOG.info("NAT Service : handleEvent() entry for IP {}, port {}, routerID {}",
naptEntryEvent.getIpAddress(), naptEntryEvent.getPortNumber(), routerId);
// Get the External Gateway MAC Address
String extGwMacAddress = NatUtil.getExtGwMacAddFromRouterId(dataBroker, routerId);
if (extGwMacAddress != null) {
LOG.debug("NAT Service : External Gateway MAC address {} found for External Router ID {}",
extGwMacAddress, routerId);
} else {
LOG.error("NAT Service : No External Gateway MAC address found for External Router ID {}", routerId);
return;
}
//Get the DPN ID
BigInteger dpnId = NatUtil.getPrimaryNaptfromRouterId(dataBroker, routerId);
long bgpVpnId = NatConstants.INVALID_ID;
if (dpnId == null) {
LOG.warn("NAT Service : dpnId is null. Assuming the router ID {} as the BGP VPN ID and proceeding....",
routerId);
bgpVpnId = routerId;
LOG.debug("NAT Service : BGP VPN ID {}", bgpVpnId);
String vpnName = NatUtil.getRouterName(dataBroker, bgpVpnId);
String routerName = NatUtil.getRouterIdfromVpnInstance(dataBroker, vpnName);
if (routerName == null) {
LOG.error("NAT Service: Unable to find router for VpnName {}", vpnName);
return;
}
routerId = NatUtil.getVpnId(dataBroker, routerName);
LOG.debug("NAT Service : Router ID {}", routerId);
dpnId = NatUtil.getPrimaryNaptfromRouterId(dataBroker, routerId);
if (dpnId == null) {
LOG.error("NAT Service : dpnId is null for the router {}", routerId);
return;
}
}
if (naptEntryEvent.getOperation() == NAPTEntryEvent.Operation.ADD) {
LOG.debug("NAT Service : Inside Add operation of NaptEventHandler");
//Get the external network ID from the ExternalRouter model
Uuid networkId = NatUtil.getNetworkIdFromRouterId(dataBroker, routerId);
if (networkId == null) {
LOG.error("NAT Service : networkId is null");
return;
}
//Get the VPN ID from the ExternalNetworks model
Uuid vpnUuid = NatUtil.getVpnIdfromNetworkId(dataBroker, networkId);
if (vpnUuid == null) {
LOG.error("NAT Service : vpnUuid is null");
return;
}
Long vpnId = NatUtil.getVpnId(dataBroker, vpnUuid.getValue());
//Get the internal IpAddress, internal port number from the event
String internalIpAddress = naptEntryEvent.getIpAddress();
int internalPort = naptEntryEvent.getPortNumber();
SessionAddress internalAddress = new SessionAddress(internalIpAddress, internalPort);
NAPTEntryEvent.Protocol protocol = naptEntryEvent.getProtocol();
//Get the external IP address for the corresponding internal IP address
SessionAddress externalAddress =
naptManager.getExternalAddressMapping(routerId, internalAddress, naptEntryEvent.getProtocol());
if (externalAddress == null) {
LOG.error("NAT Service : externalAddress is null");
return;
}
// Build and install the NAPT translation flows in the Outbound and Inbound NAPT tables
if (!naptEntryEvent.isPktProcessed()) {
// Added External Gateway MAC Address
buildAndInstallNatFlows(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, vpnId, routerId, bgpVpnId,
internalAddress, externalAddress, protocol, extGwMacAddress);
buildAndInstallNatFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE, vpnId, routerId, bgpVpnId,
externalAddress, internalAddress, protocol, extGwMacAddress);
}
//Send Packetout - tcp or udp packets which got punted to controller.
BigInteger metadata = naptEntryEvent.getPacketReceived().getMatch().getMetadata().getMetadata();
byte[] inPayload = naptEntryEvent.getPacketReceived().getPayload();
Ethernet ethPkt = new Ethernet();
if (inPayload != null) {
try {
ethPkt.deserialize(inPayload, 0, inPayload.length * NetUtils.NumBitsInAByte);
} catch (Exception e) {
LOG.warn("NAT Service : Failed to decode Packet", e);
return;
}
}
long portTag = MetaDataUtil.getLportFromMetadata(metadata).intValue();
LOG.debug("NAT Service : portTag from incoming packet is {}", portTag);
String interfaceName = getInterfaceNameFromTag(portTag);
LOG.debug("NAT Service : interfaceName fetched from portTag is {}", interfaceName);
org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508
.interfaces.Interface iface = null;
int vlanId = 0;
iface = interfaceManager.getInterfaceInfoFromConfigDataStore(interfaceName);
if (iface == null) {
LOG.error("NAT Service : Unable to read interface {} from config DataStore", interfaceName);
return;
}
IfL2vlan ifL2vlan = iface.getAugmentation(IfL2vlan.class);
if (ifL2vlan != null && ifL2vlan.getVlanId() != null) {
vlanId = ifL2vlan.getVlanId().getValue() == null ? 0 : ifL2vlan.getVlanId().getValue();
}
InterfaceInfo infInfo = interfaceManager.getInterfaceInfoFromOperationalDataStore(interfaceName);
if (infInfo != null) {
LOG.debug("NAT Service : portName fetched from interfaceManager is {}", infInfo.getPortName());
}
byte[] pktOut = buildNaptPacketOut(ethPkt);
List<ActionInfo> actionInfos = new ArrayList<>();
if (ethPkt.getPayload() instanceof IPv4) {
IPv4 ipPkt = (IPv4) ethPkt.getPayload();
if ((ipPkt.getPayload() instanceof TCP) || (ipPkt.getPayload() instanceof UDP)) {
if (ethPkt.getEtherType() != (short) NwConstants.ETHTYPE_802_1Q) {
// VLAN Access port
if (infInfo != null) {
LOG.debug("NAT Service : vlanId is {}", vlanId);
if (vlanId != 0) {
// Push vlan
actionInfos.add(new ActionPushVlan(0));
actionInfos.add(new ActionSetFieldVlanVid(1, vlanId));
} else {
LOG.debug("NAT Service : No vlanId {}, may be untagged", vlanId);
}
} else {
LOG.error("NAT Service : error in getting interfaceInfo");
return;
}
} else {
// VLAN Trunk Port
LOG.debug("NAT Service : This is VLAN Trunk port case - need not do VLAN tagging again");
}
}
}
if (pktOut != null) {
sendNaptPacketOut(pktOut, infInfo, actionInfos, routerId);
} else {
LOG.warn("NAT Service : Unable to send Packet Out");
}
} else {
LOG.debug("NAT Service : Inside delete Operation of NaptEventHandler");
removeNatFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE, routerId, naptEntryEvent.getIpAddress(),
naptEntryEvent.getPortNumber());
}
LOG.info("NAT Service : handleNaptEvent() exited for IP {}, port {}, routerID : {}",
naptEntryEvent.getIpAddress(), naptEntryEvent.getPortNumber(), routerId);
} catch (Exception e) {
LOG.error("NAT Service :Exception in NaptEventHandler.handleEvent() payload {}", naptEntryEvent, e);
}
}
public static void buildAndInstallNatFlows(BigInteger dpnId, short tableId, long vpnId, long routerId,
long bgpVpnId, SessionAddress actualSourceAddress,
SessionAddress translatedSourceAddress,
NAPTEntryEvent.Protocol protocol, String extGwMacAddress) {
LOG.debug("NAT Service : Build and install NAPT flows in InBound and OutBound tables for "
+ "dpnId {} and routerId {}", dpnId, routerId);
//Build the flow for replacing the actual IP and port with the translated IP and port.
int idleTimeout = 0;
if (tableId == NwConstants.OUTBOUND_NAPT_TABLE) {
idleTimeout = NatConstants.DEFAULT_NAPT_IDLE_TIMEOUT;
}
long intranetVpnId;
if (bgpVpnId != NatConstants.INVALID_ID) {
intranetVpnId = bgpVpnId;
} else {
intranetVpnId = routerId;
}
LOG.debug("NAT Service : Intranet VPN ID {}", intranetVpnId);
LOG.debug("NAT Service : Router ID {}", routerId);
String translatedIp = translatedSourceAddress.getIpAddress();
int translatedPort = translatedSourceAddress.getPortNumber();
String actualIp = actualSourceAddress.getIpAddress();
int actualPort = actualSourceAddress.getPortNumber();
String switchFlowRef =
NatUtil.getNaptFlowRef(dpnId, tableId, String.valueOf(routerId), actualIp, actualPort);
FlowEntity snatFlowEntity = MDSALUtil.buildFlowEntity(dpnId, tableId, switchFlowRef,
NatConstants.DEFAULT_NAPT_FLOW_PRIORITY, NatConstants.NAPT_FLOW_NAME, idleTimeout, 0,
NatUtil.getCookieNaptFlow(routerId),
buildAndGetMatchInfo(actualIp, actualPort, tableId, protocol, intranetVpnId, vpnId),
buildAndGetSetActionInstructionInfo(translatedIp, translatedPort, intranetVpnId, vpnId, tableId,
protocol, extGwMacAddress));
snatFlowEntity.setSendFlowRemFlag(true);
LOG.debug("NAT Service : Installing the NAPT flow in the table {} for the switch with the DPN ID {} ",
tableId, dpnId);
mdsalManager.syncInstallFlow(snatFlowEntity, 1);
LOG.trace("NAT Service : Exited buildAndInstallNatflows");
}
private static List<MatchInfo> buildAndGetMatchInfo(String ip, int port, short tableId,
NAPTEntryEvent.Protocol protocol, long segmentId, long vpnId) {
MatchInfo ipMatchInfo = null;
MatchInfo portMatchInfo = null;
MatchInfo protocolMatchInfo = null;
InetAddress ipAddress = null;
String ipAddressAsString = null;
try {
ipAddress = InetAddress.getByName(ip);
ipAddressAsString = ipAddress.getHostAddress();
} catch (UnknownHostException e) {
LOG.error("NAT Service : UnknowHostException in buildAndGetMatchInfo. Failed to build NAPT Flow for "
+ "ip {}", ipAddress);
return null;
}
MatchInfo metaDataMatchInfo = null;
if (tableId == NwConstants.OUTBOUND_NAPT_TABLE) {
ipMatchInfo = new MatchIpv4Source(ipAddressAsString, "32");
if (protocol == NAPTEntryEvent.Protocol.TCP) {
protocolMatchInfo = MatchIpProtocol.TCP;
portMatchInfo = new MatchTcpSourcePort(port);
} else if (protocol == NAPTEntryEvent.Protocol.UDP) {
protocolMatchInfo = MatchIpProtocol.UDP;
portMatchInfo = new MatchUdpSourcePort(port);
}
metaDataMatchInfo =
new MatchMetadata(MetaDataUtil.getVpnIdMetadata(segmentId), MetaDataUtil.METADATA_MASK_VRFID);
} else {
ipMatchInfo = new MatchIpv4Destination(ipAddressAsString, "32");
if (protocol == NAPTEntryEvent.Protocol.TCP) {
protocolMatchInfo = MatchIpProtocol.TCP;
portMatchInfo = new MatchTcpDestinationPort(port);
} else if (protocol == NAPTEntryEvent.Protocol.UDP) {
protocolMatchInfo = MatchIpProtocol.UDP;
portMatchInfo = new MatchUdpDestinationPort(port);
}
//metaDataMatchInfo = new MatchMetadata(BigInteger.valueOf(vpnId), MetaDataUtil.METADATA_MASK_VRFID);
}
ArrayList<MatchInfo> matchInfo = new ArrayList<>();
matchInfo.add(MatchEthernetType.IPV4);
matchInfo.add(ipMatchInfo);
matchInfo.add(protocolMatchInfo);
matchInfo.add(portMatchInfo);
if (tableId == NwConstants.OUTBOUND_NAPT_TABLE) {
matchInfo.add(metaDataMatchInfo);
}
return matchInfo;
}
private static List<InstructionInfo> buildAndGetSetActionInstructionInfo(String ipAddress, int port,
long segmentId, long vpnId,
short tableId,
NAPTEntryEvent.Protocol protocol,
String extGwMacAddress) {
ActionInfo ipActionInfo = null;
ActionInfo macActionInfo = null;
ActionInfo portActionInfo = null;
ArrayList<ActionInfo> listActionInfo = new ArrayList<>();
ArrayList<InstructionInfo> instructionInfo = new ArrayList<>();
switch (tableId) {
case NwConstants.OUTBOUND_NAPT_TABLE:
ipActionInfo = new ActionSetSourceIp(ipAddress);
// Added External Gateway MAC Address
macActionInfo = new ActionSetFieldEthernetSource(new MacAddress(extGwMacAddress));
if (protocol == NAPTEntryEvent.Protocol.TCP) {
portActionInfo = new ActionSetTcpSourcePort(port);
} else if (protocol == NAPTEntryEvent.Protocol.UDP) {
portActionInfo = new ActionSetUdpSourcePort(port);
}
// reset the split-horizon bit to allow traffic from tunnel to be sent back to the provider port
instructionInfo.add(new InstructionWriteMetadata(MetaDataUtil.getVpnIdMetadata(vpnId),
MetaDataUtil.METADATA_MASK_VRFID.or(MetaDataUtil.METADATA_MASK_SH_FLAG)));
break;
case NwConstants.INBOUND_NAPT_TABLE:
ipActionInfo = new ActionSetDestinationIp(ipAddress);
if (protocol == NAPTEntryEvent.Protocol.TCP) {
portActionInfo = new ActionSetTcpDestinationPort(port);
} else if (protocol == NAPTEntryEvent.Protocol.UDP) {
portActionInfo = new ActionSetUdpDestinationPort(port);
}
instructionInfo.add(new InstructionWriteMetadata(
MetaDataUtil.getVpnIdMetadata(segmentId), MetaDataUtil.METADATA_MASK_VRFID));
break;
default:
LOG.error("NAT Service : Neither OUTBOUND_NAPT_TABLE nor INBOUND_NAPT_TABLE matches with "
+ "input table id {}", tableId);
return null;
}
listActionInfo.add(ipActionInfo);
listActionInfo.add(portActionInfo);
if (macActionInfo != null) {
listActionInfo.add(macActionInfo);
LOG.debug("NAT Service : External GW MAC Address {} is found ", macActionInfo);
}
instructionInfo.add(new InstructionApplyActions(listActionInfo));
instructionInfo.add(new InstructionGotoTable(NwConstants.NAPT_PFIB_TABLE));
return instructionInfo;
}
void removeNatFlows(BigInteger dpnId, short tableId ,long segmentId, String ip, int port) {
if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
LOG.error("NAT Service : DPN ID {} is invalid" , dpnId);
}
LOG.debug("NAT Service : Remove NAPT flows for dpnId {}, segmentId {}, ip {} and port {} ",
dpnId, segmentId, ip, port);
//Build the flow with the port IP and port as the match info.
String switchFlowRef = NatUtil.getNaptFlowRef(dpnId, tableId, String.valueOf(segmentId), ip, port);
FlowEntity snatFlowEntity = NatUtil.buildFlowEntity(dpnId, tableId, switchFlowRef);
LOG.debug("NAT Service : Remove the flow in the table {} for the switch with the DPN ID {}",
NwConstants.INBOUND_NAPT_TABLE, dpnId);
mdsalManager.removeFlow(snatFlowEntity);
}
protected byte[] buildNaptPacketOut(Ethernet etherPkt) {
LOG.debug("NAT Service : About to build Napt Packet Out");
if (etherPkt.getPayload() instanceof IPv4) {
byte[] rawPkt;
IPv4 ipPkt = (IPv4) etherPkt.getPayload();
if ((ipPkt.getPayload() instanceof TCP) || (ipPkt.getPayload() instanceof UDP)) {
try {
rawPkt = etherPkt.serialize();
return rawPkt;
} catch (PacketException e2) {
LOG.error("failed to build NAPT Packet out ", e2);
return null;
}
} else {
LOG.error("NAT Service : Unable to build NaptPacketOut since its neither TCP nor UDP");
return null;
}
}
LOG.error("NAT Service : Unable to build NaptPacketOut since its not IPv4 packet");
return null;
}
private void sendNaptPacketOut(byte[] pktOut, InterfaceInfo infInfo, List<ActionInfo> actionInfos, Long routerId) {
LOG.trace("NAT Service: Sending packet out DpId {}, interfaceInfo {}", infInfo.getDpId(), infInfo);
// set inPort, and action as OFPP_TABLE so that it starts from table 0 (lowest table as per spec)
actionInfos.add(new ActionSetFieldTunnelId(2, BigInteger.valueOf(routerId)));
actionInfos.add(new ActionOutput(3, new Uri("0xfffffff9")));
NodeConnectorRef inPort = MDSALUtil.getNodeConnRef(infInfo.getDpId(), String.valueOf(infInfo.getPortNo()));
LOG.debug("NAT Service : inPort for packetout is being set to {}", String.valueOf(infInfo.getPortNo()));
TransmitPacketInput output = MDSALUtil.getPacketOut(actionInfos, pktOut, infInfo.getDpId().longValue(), inPort);
LOG.trace("NAT Service: Transmitting packet: {}",output);
this.pktService.transmitPacket(output);
}
private String getInterfaceNameFromTag(long portTag) {
String interfaceName = null;
GetInterfaceFromIfIndexInput input =
new GetInterfaceFromIfIndexInputBuilder().setIfIndex((int) portTag).build();
Future<RpcResult<GetInterfaceFromIfIndexOutput>> futureOutput =
interfaceManagerRpc.getInterfaceFromIfIndex(input);
try {
GetInterfaceFromIfIndexOutput output = futureOutput.get().getResult();
interfaceName = output.getInterfaceName();
} catch (InterruptedException | ExecutionException e) {
LOG.error("NAT Service : Error while retrieving the interfaceName from tag using "
+ "getInterfaceFromIfIndex RPC");
}
LOG.trace("NAT Service : Returning interfaceName {} for tag {} form getInterfaceNameFromTag",
interfaceName, portTag);
return interfaceName;
}
}
|
Bug 7667: SNAT table 46&44 are not getting programmed when private BGPVPN
Problem Description:
=====================
SNAT: Table 46(OUTBOUND_NAPT) and table 44 (INBOUND_NAPT) are not getting
programmed (SNAT Forward Traffic and SNAT Reverse Traffic) with NAT
translation when router is
associated with Private/Internal BGP-VPN.Due to this issue, SNAT traffic
is getting failed when interval bgp-vpn is configured.
Root Cause of the Problem:
==========================
As part of bug (Bug 7478) fix SNAT traffic is used to send router-gw mac
address instead of VM mac. With this code changes router gw-mac was
getting from external-router Yang Model using router name as key.
When private/internal bgp-vpn is configured router-id (Internal Private
VPN ID) should be replaced with created private/internal bgp-vpn id. With
this approach when querying external-router Yang model for getting
router-gw mac address using new router-id (bgp-vpn id) will not match with
router-name.
Solution:
===========
When querying external-router yang model for getting router-gw mac address
it should use old router-id instead of bgp-vpn id. For doing this change
in NAPTEventHandler re-aligned the router-gw mac address code to
appropriate place to be working as expected.
Change-Id: Ieefd799d6b2349464bfb737e3fcc8101036c3619
Signed-off-by: karthikeyan <[email protected]>
|
vpnservice/natservice/natservice-impl/src/main/java/org/opendaylight/netvirt/natservice/internal/NaptEventHandler.java
|
Bug 7667: SNAT table 46&44 are not getting programmed when private BGPVPN
|
<ide><path>pnservice/natservice/natservice-impl/src/main/java/org/opendaylight/netvirt/natservice/internal/NaptEventHandler.java
<ide> Long routerId = naptEntryEvent.getRouterId();
<ide> LOG.info("NAT Service : handleEvent() entry for IP {}, port {}, routerID {}",
<ide> naptEntryEvent.getIpAddress(), naptEntryEvent.getPortNumber(), routerId);
<del> // Get the External Gateway MAC Address
<del> String extGwMacAddress = NatUtil.getExtGwMacAddFromRouterId(dataBroker, routerId);
<del> if (extGwMacAddress != null) {
<del> LOG.debug("NAT Service : External Gateway MAC address {} found for External Router ID {}",
<del> extGwMacAddress, routerId);
<del> } else {
<del> LOG.error("NAT Service : No External Gateway MAC address found for External Router ID {}", routerId);
<del> return;
<del> }
<ide> //Get the DPN ID
<ide> BigInteger dpnId = NatUtil.getPrimaryNaptfromRouterId(dataBroker, routerId);
<ide> long bgpVpnId = NatConstants.INVALID_ID;
<ide> }
<ide> if (naptEntryEvent.getOperation() == NAPTEntryEvent.Operation.ADD) {
<ide> LOG.debug("NAT Service : Inside Add operation of NaptEventHandler");
<del>
<add> // Get the External Gateway MAC Address
<add> String extGwMacAddress = NatUtil.getExtGwMacAddFromRouterId(dataBroker, routerId);
<add> if (extGwMacAddress != null) {
<add> LOG.debug("NAT Service : External Gateway MAC address {} found for External Router ID {}",
<add> extGwMacAddress, routerId);
<add> } else {
<add> LOG.error("NAT Service : No External Gateway MAC address found for External Router ID {}",
<add> routerId);
<add> return;
<add> }
<ide> //Get the external network ID from the ExternalRouter model
<ide> Uuid networkId = NatUtil.getNetworkIdFromRouterId(dataBroker, routerId);
<ide> if (networkId == null) {
|
|
Java
|
mit
|
aa984ba53eba632da6caace9c039d9879eb366ae
| 0 |
PrinceOfAmber/Cyclic,PrinceOfAmber/CyclicMagic
|
package com.lothrazar.cyclicmagic.block;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import com.lothrazar.cyclicmagic.IHasConfig;
import com.lothrazar.cyclicmagic.ModCyclic;
import com.lothrazar.cyclicmagic.item.ItemMagicBean;
import com.lothrazar.cyclicmagic.util.Const;
import net.minecraft.block.BlockCrops;
import net.minecraft.block.BlockDoublePlant;
import net.minecraft.block.BlockFlower;
import net.minecraft.block.BlockPlanks;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFishFood;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.config.Configuration;
public class BlockCropMagicBean extends BlockCrops implements IHasConfig {
public static final int MAX_AGE = 7;
public static final PropertyInteger AGE = PropertyInteger.create("age", 0, MAX_AGE);
private static final AxisAlignedBB[] AABB = new AxisAlignedBB[] { new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.125D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.1875D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.25D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.3125D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.375D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.4375D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.5D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.5625D, 1.0D) };
private List<ItemStack> myDrops = new ArrayList<ItemStack>();
private ItemMagicBean seed;
private boolean allowBonemeal;
private boolean dropSeedOnHarvest;
private ArrayList<String> myDropStrings;
public BlockCropMagicBean() {
Item[] drops = new Item[] {
//treasure
Items.REDSTONE, Items.GUNPOWDER, Items.GLOWSTONE_DUST, Items.DIAMOND, Items.EMERALD,
Items.COAL, Items.GOLD_NUGGET, Items.IRON_INGOT, Items.GOLD_INGOT,
Items.NETHER_STAR, Items.QUARTZ, Items.LEAD, Items.NAME_TAG,
//mob drops
Items.ENDER_PEARL, Items.ENDER_EYE, Items.SLIME_BALL,
Items.BLAZE_POWDER, Items.BLAZE_ROD, Items.LEATHER,
Items.ROTTEN_FLESH, Items.BONE, Items.STRING, Items.SPIDER_EYE,
Items.FLINT, Items.GHAST_TEAR,
// footstuffs
Items.APPLE, Items.STICK, Items.SUGAR, Items.COOKED_FISH,
Items.CARROT, Items.POTATO, Items.BEETROOT, Items.WHEAT, Items.MELON,
Items.BEETROOT_SEEDS, Items.MELON_SEEDS, Items.PUMPKIN_SEEDS, Items.WHEAT_SEEDS,
Items.EGG,
//random crap
Items.COMPASS, Items.CLOCK, Items.CAULDRON, Items.COMPARATOR, Items.REPEATER,
Items.FIRE_CHARGE, Items.POISONOUS_POTATO,
Items.RABBIT_FOOT, Items.RABBIT_HIDE, Items.PUMPKIN_PIE,
Items.FERMENTED_SPIDER_EYE, Items.EXPERIENCE_BOTTLE,
Items.FLOWER_POT, Items.ITEM_FRAME, Items.PAINTING,
Items.CAKE, Items.COOKIE, Items.SPECKLED_MELON, Items.SNOWBALL,
Items.GLASS_BOTTLE, Items.BOOK, Items.PAPER, Items.CLAY_BALL, Items.BRICK,
//plants
Items.NETHER_WART, Item.getItemFromBlock(Blocks.YELLOW_FLOWER),
Item.getItemFromBlock(Blocks.RED_MUSHROOM), Item.getItemFromBlock(Blocks.BROWN_MUSHROOM),
Item.getItemFromBlock(Blocks.TALLGRASS), Item.getItemFromBlock(Blocks.REEDS),
Item.getItemFromBlock(Blocks.DEADBUSH), Item.getItemFromBlock(Blocks.CACTUS),
Item.getItemFromBlock(Blocks.VINE), Item.getItemFromBlock(Blocks.WATERLILY),
Item.getItemFromBlock(Blocks.END_ROD), Item.getItemFromBlock(Blocks.CHORUS_PLANT)
};
//metadata specific blocks
myDrops.add(new ItemStack(Items.COAL, 1, 1));//charcoal
myDrops.add(new ItemStack(Blocks.PUMPKIN));
myDrops.add(new ItemStack(Blocks.LIT_PUMPKIN));
myDrops.add(new ItemStack(Blocks.REDSTONE_LAMP));
for (Item i : drops) {
myDrops.add(new ItemStack(i));
}
for (EnumDyeColor dye : EnumDyeColor.values()) {//all 16 cols
myDrops.add(new ItemStack(Items.DYE, 1, dye.getMetadata()));
myDrops.add(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, dye.getMetadata()));//these ones are new
myDrops.add(new ItemStack(Blocks.WOOL, 1, dye.getMetadata()));
myDrops.add(new ItemStack(Blocks.STAINED_GLASS, 1, dye.getMetadata()));
myDrops.add(new ItemStack(Blocks.STAINED_GLASS_PANE, 1, dye.getMetadata()));
}
for (ItemFishFood.FishType f : ItemFishFood.FishType.values()) {
myDrops.add(new ItemStack(Items.FISH, 1, f.getMetadata()));
}
for (BlockPlanks.EnumType b : BlockPlanks.EnumType.values()) {
myDrops.add(new ItemStack(Blocks.SAPLING, 1, b.getMetadata()));
}
for (BlockFlower.EnumFlowerType b : BlockFlower.EnumFlowerType.values()) {
myDrops.add(new ItemStack(Blocks.RED_FLOWER, 1, b.getMeta()));
}
for (BlockDoublePlant.EnumPlantType b : BlockDoublePlant.EnumPlantType.values()) {
myDrops.add(new ItemStack(Blocks.DOUBLE_PLANT, 1, b.getMeta()));
}
}
@Override
protected PropertyInteger getAgeProperty() {
return AGE;
}
@Nullable
@Override
public Item getItemDropped(IBlockState state, Random rand, int fortune) {
return this.isMaxAge(state) ? this.getSeed() : this.getSeed();//the null tells harvestcraft hey: dont remove my drops
}
@Override
protected Item getSeed() {
return seed;
}
public void setSeed(ItemMagicBean item) {
seed = item;
}
@Override
protected Item getCrop() {
return null;//ItemRegistry.sprout_seed;
}
private ItemStack getCropStack(Random rand) {
String res = this.myDropStrings.get(rand.nextInt(myDropStrings.size()));
try {
String[] ares = res.split(Pattern.quote("*"));
Item item = Item.getByNameOrId(ares[0]);
if (item == null) {
ModCyclic.logger.error("Magic Bean config: loot item not found " + res);
this.myDropStrings.remove(res);
return getCropStack(rand);
}
String meta = (ares.length > 1) ? ares[1] : "0";
int imeta = Integer.parseInt(meta);
ItemStack stack = new ItemStack(item, 1, imeta);
return stack;
}
catch (Exception e) {
ModCyclic.logger.error("Magic Bean config: loot item not found " + res);
ModCyclic.logger.error(e.getMessage());
return new ItemStack(Blocks.DIRT);
}
// return myDrops.get(rand.nextInt(myDrops.size()));
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
return AABB[((Integer) state.getValue(this.getAgeProperty())).intValue()];
}
@Override
public int quantityDropped(Random random) {
return super.quantityDropped(random) + 1;
}
@Override
public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
// Used by regular 'block break' and also by other harvesting features
java.util.List<ItemStack> ret = new ArrayList<ItemStack>();
boolean isGrown = this.isMaxAge(state);
if (isGrown) {
Random rand = world instanceof World ? ((World) world).rand : new Random();
int count = quantityDropped(state, fortune, rand);
for (int i = 0; i < count; i++) {
ret.add(getCropStack(rand).copy()); //copy to make sure we return a new instance
}
}
if (!isGrown || dropSeedOnHarvest) {//either its !grown, so drop seed, OR it is grown, but config says drop on full grown
ret.add(new ItemStack(getSeed()));//always a seed, grown or not
}
return ret;
}
@Override
public int getMaxAge() {
return MAX_AGE;
}
@Override
protected int getBonemealAgeIncrease(World worldIn) {
return allowBonemeal ? 1 : 0;
}
@Override
public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, IBlockState state) {
return getBonemealAgeIncrease(worldIn) > 0;
}
@Override
public void syncConfig(Configuration config) {
String category = Const.ConfigCategory.blocks + ".magicbean";
allowBonemeal = config.getBoolean("MagicBeanBonemeal", category, true, "Allow bonemeal on magic bean");
dropSeedOnHarvest = config.getBoolean("MagicBeanGrownDropSeed", category, true, "Allow dropping the seed item if fully grown. (if its not grown it will still drop when broken)");
ArrayList<String> deft = new ArrayList<String>();
for (ItemStack drop : myDrops) {
if (drop == null || drop.getItem() == null) {
continue;
}
String resource = drop.getItem().getRegistryName().getResourceDomain() + ":" + drop.getItem().getRegistryName().getResourcePath();
if (drop.getMetadata() > 0) {
resource += "*" + drop.getMetadata();
}
System.out.println(resource);
deft.add(resource);
}
myDropStrings = new ArrayList<String>(Arrays.asList(config.getStringList("MagicBeanDropList", category, deft.toArray(new String[0]), "Drop list")));
if (myDropStrings.size() == 0) {
//do not let it be empty! avoid infloop
myDropStrings.add("minecraft:dirt");
}
}
}
|
src/main/java/com/lothrazar/cyclicmagic/block/BlockCropMagicBean.java
|
package com.lothrazar.cyclicmagic.block;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import com.lothrazar.cyclicmagic.IHasConfig;
import com.lothrazar.cyclicmagic.ModCyclic;
import com.lothrazar.cyclicmagic.item.ItemMagicBean;
import com.lothrazar.cyclicmagic.util.Const;
import net.minecraft.block.BlockCrops;
import net.minecraft.block.BlockDoublePlant;
import net.minecraft.block.BlockFlower;
import net.minecraft.block.BlockPlanks;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFishFood;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.config.Configuration;
import scala.actors.threadpool.Arrays;
public class BlockCropMagicBean extends BlockCrops implements IHasConfig {
public static final int MAX_AGE = 7;
public static final PropertyInteger AGE = PropertyInteger.create("age", 0, MAX_AGE);
private static final AxisAlignedBB[] AABB = new AxisAlignedBB[] { new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.125D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.1875D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.25D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.3125D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.375D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.4375D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.5D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.5625D, 1.0D) };
private List<ItemStack> myDrops = new ArrayList<ItemStack>();
private ItemMagicBean seed;
private boolean allowBonemeal;
private boolean dropSeedOnHarvest;
private ArrayList<String> myDropStrings;
public BlockCropMagicBean() {
Item[] drops = new Item[] {
//treasure
Items.REDSTONE, Items.GUNPOWDER, Items.GLOWSTONE_DUST, Items.DIAMOND, Items.EMERALD,
Items.COAL, Items.GOLD_NUGGET, Items.IRON_INGOT, Items.GOLD_INGOT,
Items.NETHER_STAR, Items.QUARTZ, Items.LEAD, Items.NAME_TAG,
//mob drops
Items.ENDER_PEARL, Items.ENDER_EYE, Items.SLIME_BALL,
Items.BLAZE_POWDER, Items.BLAZE_ROD, Items.LEATHER,
Items.ROTTEN_FLESH, Items.BONE, Items.STRING, Items.SPIDER_EYE,
Items.FLINT, Items.GHAST_TEAR,
// footstuffs
Items.APPLE, Items.STICK, Items.SUGAR, Items.COOKED_FISH,
Items.CARROT, Items.POTATO, Items.BEETROOT, Items.WHEAT, Items.MELON,
Items.BEETROOT_SEEDS, Items.MELON_SEEDS, Items.PUMPKIN_SEEDS, Items.WHEAT_SEEDS,
Items.EGG,
//random crap
Items.COMPASS, Items.CLOCK, Items.CAULDRON, Items.COMPARATOR, Items.REPEATER,
Items.FIRE_CHARGE, Items.POISONOUS_POTATO,
Items.RABBIT_FOOT, Items.RABBIT_HIDE, Items.PUMPKIN_PIE,
Items.FERMENTED_SPIDER_EYE, Items.EXPERIENCE_BOTTLE,
Items.FLOWER_POT, Items.ITEM_FRAME, Items.PAINTING,
Items.CAKE, Items.COOKIE, Items.SPECKLED_MELON, Items.SNOWBALL,
Items.GLASS_BOTTLE, Items.BOOK, Items.PAPER, Items.CLAY_BALL, Items.BRICK,
//plants
Items.NETHER_WART, Item.getItemFromBlock(Blocks.YELLOW_FLOWER),
Item.getItemFromBlock(Blocks.RED_MUSHROOM), Item.getItemFromBlock(Blocks.BROWN_MUSHROOM),
Item.getItemFromBlock(Blocks.TALLGRASS), Item.getItemFromBlock(Blocks.REEDS),
Item.getItemFromBlock(Blocks.DEADBUSH), Item.getItemFromBlock(Blocks.CACTUS),
Item.getItemFromBlock(Blocks.VINE), Item.getItemFromBlock(Blocks.WATERLILY),
Item.getItemFromBlock(Blocks.END_ROD), Item.getItemFromBlock(Blocks.CHORUS_PLANT)
};
//metadata specific blocks
myDrops.add(new ItemStack(Items.COAL, 1, 1));//charcoal
myDrops.add(new ItemStack(Blocks.PUMPKIN));
myDrops.add(new ItemStack(Blocks.LIT_PUMPKIN));
myDrops.add(new ItemStack(Blocks.REDSTONE_LAMP));
for (Item i : drops) {
myDrops.add(new ItemStack(i));
}
for (EnumDyeColor dye : EnumDyeColor.values()) {//all 16 cols
myDrops.add(new ItemStack(Items.DYE, 1, dye.getMetadata()));
myDrops.add(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, dye.getMetadata()));//these ones are new
myDrops.add(new ItemStack(Blocks.WOOL, 1, dye.getMetadata()));
myDrops.add(new ItemStack(Blocks.STAINED_GLASS, 1, dye.getMetadata()));
myDrops.add(new ItemStack(Blocks.STAINED_GLASS_PANE, 1, dye.getMetadata()));
}
for (ItemFishFood.FishType f : ItemFishFood.FishType.values()) {
myDrops.add(new ItemStack(Items.FISH, 1, f.getMetadata()));
}
for (BlockPlanks.EnumType b : BlockPlanks.EnumType.values()) {
myDrops.add(new ItemStack(Blocks.SAPLING, 1, b.getMetadata()));
}
for (BlockFlower.EnumFlowerType b : BlockFlower.EnumFlowerType.values()) {
myDrops.add(new ItemStack(Blocks.RED_FLOWER, 1, b.getMeta()));
}
for (BlockDoublePlant.EnumPlantType b : BlockDoublePlant.EnumPlantType.values()) {
myDrops.add(new ItemStack(Blocks.DOUBLE_PLANT, 1, b.getMeta()));
}
}
@Override
protected PropertyInteger getAgeProperty() {
return AGE;
}
@Nullable
@Override
public Item getItemDropped(IBlockState state, Random rand, int fortune) {
return this.isMaxAge(state) ? this.getSeed() : this.getSeed();//the null tells harvestcraft hey: dont remove my drops
}
@Override
protected Item getSeed() {
return seed;
}
public void setSeed(ItemMagicBean item) {
seed = item;
}
@Override
protected Item getCrop() {
return null;//ItemRegistry.sprout_seed;
}
private ItemStack getCropStack(Random rand) {
String res = this.myDropStrings.get(rand.nextInt(myDropStrings.size()));
try {
String[] ares = res.split(Pattern.quote("*"));
Item item = Item.getByNameOrId(ares[0]);
if (item == null) {
ModCyclic.logger.error("Magic Bean config: loot item not found " + res);
this.myDropStrings.remove(res);
return getCropStack(rand);
}
String meta = (ares.length > 1) ? ares[1] : "0";
int imeta = Integer.parseInt(meta);
ItemStack stack = new ItemStack(item, 1, imeta);
return stack;
}
catch (Exception e) {
ModCyclic.logger.error("Magic Bean config: loot item not found " + res);
ModCyclic.logger.error(e.getMessage());
return new ItemStack(Blocks.DIRT);
}
// return myDrops.get(rand.nextInt(myDrops.size()));
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
return AABB[((Integer) state.getValue(this.getAgeProperty())).intValue()];
}
@Override
public int quantityDropped(Random random) {
return super.quantityDropped(random) + 1;
}
@Override
public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
// Used by regular 'block break' and also by other harvesting features
java.util.List<ItemStack> ret = new ArrayList<ItemStack>();
boolean isGrown = this.isMaxAge(state);
if (isGrown) {
Random rand = world instanceof World ? ((World) world).rand : new Random();
int count = quantityDropped(state, fortune, rand);
for (int i = 0; i < count; i++) {
ret.add(getCropStack(rand).copy()); //copy to make sure we return a new instance
}
}
if (!isGrown || dropSeedOnHarvest) {//either its !grown, so drop seed, OR it is grown, but config says drop on full grown
ret.add(new ItemStack(getSeed()));//always a seed, grown or not
}
return ret;
}
@Override
public int getMaxAge() {
return MAX_AGE;
}
@Override
protected int getBonemealAgeIncrease(World worldIn) {
return allowBonemeal ? 1 : 0;
}
@Override
public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, IBlockState state) {
return getBonemealAgeIncrease(worldIn) > 0;
}
@SuppressWarnings("unchecked")
@Override
public void syncConfig(Configuration config) {
String category = Const.ConfigCategory.blocks + ".magicbean";
allowBonemeal = config.getBoolean("MagicBeanBonemeal", category, true, "Allow bonemeal on magic bean");
dropSeedOnHarvest = config.getBoolean("MagicBeanGrownDropSeed", category, true, "Allow dropping the seed item if fully grown. (if its not grown it will still drop when broken)");
ArrayList<String> deft = new ArrayList<String>();
for (ItemStack drop : myDrops) {
if (drop == null || drop.getItem() == null) {
continue;
}
String resource = drop.getItem().getRegistryName().getResourceDomain() + ":" + drop.getItem().getRegistryName().getResourcePath();
if (drop.getMetadata() > 0) {
resource += "*" + drop.getMetadata();
}
System.out.println(resource);
deft.add(resource);
}
myDropStrings = new ArrayList<String>(Arrays.asList(config.getStringList("MagicBeanDropList", category, deft.toArray(new String[0]), "Drop list")));
if (myDropStrings.size() == 0) {
//do not let it be empty! avoid infloop
myDropStrings.add("minecraft:dirt");
}
}
}
|
scala can go die in a fire
|
src/main/java/com/lothrazar/cyclicmagic/block/BlockCropMagicBean.java
|
scala can go die in a fire
|
<ide><path>rc/main/java/com/lothrazar/cyclicmagic/block/BlockCropMagicBean.java
<ide> package com.lothrazar.cyclicmagic.block;
<ide> import java.util.ArrayList;
<add>import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.Random;
<ide> import java.util.regex.Pattern;
<ide> import net.minecraft.world.IBlockAccess;
<ide> import net.minecraft.world.World;
<ide> import net.minecraftforge.common.config.Configuration;
<del>import scala.actors.threadpool.Arrays;
<ide>
<ide> public class BlockCropMagicBean extends BlockCrops implements IHasConfig {
<ide> public static final int MAX_AGE = 7;
<ide> public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, IBlockState state) {
<ide> return getBonemealAgeIncrease(worldIn) > 0;
<ide> }
<del> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public void syncConfig(Configuration config) {
<ide> String category = Const.ConfigCategory.blocks + ".magicbean";
|
|
Java
|
apache-2.0
|
239ef9b2999411d4a66f80a536c9fa9deafbec07
| 0 |
batfish/batfish,intentionet/batfish,intentionet/batfish,intentionet/batfish,arifogel/batfish,batfish/batfish,dhalperi/batfish,intentionet/batfish,arifogel/batfish,intentionet/batfish,dhalperi/batfish,arifogel/batfish,batfish/batfish,dhalperi/batfish
|
package org.batfish.common.topology;
import static org.batfish.common.util.CommonUtil.forEachWithIndex;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import com.google.common.graph.EndpointPair;
import com.google.common.graph.Graph;
import com.google.common.graph.Graphs;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.batfish.common.Pair;
import org.batfish.common.util.CommonUtil;
import org.batfish.datamodel.AclIpSpace;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.Edge;
import org.batfish.datamodel.Interface;
import org.batfish.datamodel.InterfaceAddress;
import org.batfish.datamodel.InterfaceType;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.IpSpace;
import org.batfish.datamodel.SwitchportMode;
import org.batfish.datamodel.Topology;
import org.batfish.datamodel.Vrf;
import org.batfish.datamodel.collections.NodeInterfacePair;
public final class TopologyUtil {
/** Returns true iff the given trunk interface allows its own native vlan. */
private static boolean trunkWithNativeVlanAllowed(Interface i) {
return i.getSwitchportMode() == SwitchportMode.TRUNK
&& i.getAllowedVlans().contains(i.getNativeVlan());
}
// Precondition: at least one of i1 and i2 is a trunk
private static void addLayer2TrunkEdges(
Interface i1,
Interface i2,
ImmutableSet.Builder<Layer2Edge> edges,
Layer1Node node1,
Layer1Node node2) {
if (i1.getSwitchportMode() == SwitchportMode.TRUNK
&& i2.getSwitchportMode() == SwitchportMode.TRUNK) {
// Both sides are trunks, so add edges from n1,v to n2,v for all shared VLANs.
i1.getAllowedVlans()
.stream()
.forEach(
vlan -> {
if (i1.getNativeVlan() == vlan && trunkWithNativeVlanAllowed(i2)) {
// This frame will not be tagged by i1, and i2 accepts untagged frames.
edges.add(new Layer2Edge(node1, vlan, node2, vlan, null /* untagged */));
} else if (i2.getAllowedVlans().contains(vlan)) {
// This frame will be tagged by i1 and we can directly check whether i2 allows.
edges.add(new Layer2Edge(node1, vlan, node2, vlan, vlan));
}
});
} else if (trunkWithNativeVlanAllowed(i1)) {
// i1 is a trunk, but the other side is not. The only edge that will come up is i2 receiving
// untagged packets.
Integer node2VlanId =
i2.getSwitchportMode() == SwitchportMode.ACCESS ? i2.getAccessVlan() : null;
edges.add(new Layer2Edge(node1, i1.getNativeVlan(), node2, node2VlanId, null));
} else if (trunkWithNativeVlanAllowed(i2)) {
// i1 is not a trunk, but the other side is. The only edge that will come up is the other
// side receiving untagged packets and treating them as native VLAN.
Integer node1VlanId =
i1.getSwitchportMode() == SwitchportMode.ACCESS ? i1.getAccessVlan() : null;
edges.add(new Layer2Edge(node1, node1VlanId, node2, i2.getNativeVlan(), null));
}
}
private static void computeAugmentedLayer2SelfEdges(
@Nonnull String hostname, @Nonnull Vrf vrf, @Nonnull ImmutableSet.Builder<Layer2Edge> edges) {
Map<Integer, ImmutableList.Builder<String>> switchportsByVlan = new HashMap<>();
vrf.getInterfaces()
.values()
.stream()
.filter(Interface::getActive)
.forEach(
i -> {
if (i.getSwitchportMode() == SwitchportMode.TRUNK) {
i.getAllowedVlans()
.stream()
.forEach(
vlan ->
switchportsByVlan
.computeIfAbsent(vlan, n -> ImmutableList.builder())
.add(i.getName()));
}
if (i.getSwitchportMode() == SwitchportMode.ACCESS) {
switchportsByVlan
.computeIfAbsent(i.getAccessVlan(), n -> ImmutableList.builder())
.add(i.getName());
}
if (i.getInterfaceType() == InterfaceType.VLAN) {
switchportsByVlan
.computeIfAbsent(i.getVlan(), n -> ImmutableList.builder())
.add(i.getName());
}
});
switchportsByVlan.forEach(
(vlanId, interfaceNamesBuilder) -> {
List<String> interfaceNames = interfaceNamesBuilder.build();
forEachWithIndex(
interfaceNames,
(i, i1Name) -> {
for (int j = i + 1; j < interfaceNames.size(); j++) {
String i2Name = interfaceNames.get(j);
edges.add(
new Layer2Edge(hostname, i1Name, vlanId, hostname, i2Name, vlanId, null));
edges.add(
new Layer2Edge(hostname, i2Name, vlanId, hostname, i1Name, vlanId, null));
}
});
});
}
private static Layer2Topology computeAugmentedLayer2Topology(
Layer2Topology layer2Topology, Map<String, Configuration> configurations) {
ImmutableSet.Builder<Layer2Edge> augmentedEdges = ImmutableSet.builder();
augmentedEdges.addAll(layer2Topology.getGraph().edges());
configurations
.values()
.forEach(
c -> {
c.getVrfs()
.values()
.forEach(
vrf -> computeAugmentedLayer2SelfEdges(c.getHostname(), vrf, augmentedEdges));
});
// Now compute the transitive closure to connect interfaces across devices
Layer2Topology initial = new Layer2Topology(augmentedEdges.build());
Graph<Layer2Node> initialGraph = initial.getGraph().asGraph();
Graph<Layer2Node> closure = Graphs.transitiveClosure(initialGraph);
/*
* We must remove edges connecting existing endpoint pairs since they may clash due to missing
* encapsulation vlan id. Also, we remove self-edges on the same interfaces by convention.
*/
Set<EndpointPair<Layer2Node>> newEndpoints =
Sets.difference(closure.edges(), initialGraph.edges());
newEndpoints
.stream()
.filter(ne -> !ne.source().equals(ne.target()))
.forEach(
newEndpoint ->
augmentedEdges.add(
new Layer2Edge(newEndpoint.source(), newEndpoint.target(), null)));
return new Layer2Topology(augmentedEdges.build());
}
public static @Nonnull Layer1Topology computeLayer1Topology(
@Nonnull Layer1Topology rawLayer1Topology,
@Nonnull Map<String, Configuration> configurations) {
/* Filter out inactive interfaces */
return new Layer1Topology(
rawLayer1Topology
.getGraph()
.edges()
.stream()
.filter(
edge -> {
Interface i1 = getInterface(edge.getNode1(), configurations);
Interface i2 = getInterface(edge.getNode2(), configurations);
return i1 != null && i2 != null && i1.getActive() && i2.getActive();
})
.collect(ImmutableSet.toImmutableSet()));
}
private static void computeLayer2EdgesForLayer1Edge(
@Nonnull Layer1Edge layer1Edge,
@Nonnull Map<String, Configuration> configurations,
@Nonnull ImmutableSet.Builder<Layer2Edge> edges) {
Layer1Node node1 = layer1Edge.getNode1();
Layer1Node node2 = layer1Edge.getNode2();
Interface i1 = getInterface(node1, configurations);
Interface i2 = getInterface(node2, configurations);
if (i1 == null || i2 == null) {
return;
}
if (i1.getSwitchportMode() == SwitchportMode.TRUNK
|| i2.getSwitchportMode() == SwitchportMode.TRUNK) {
addLayer2TrunkEdges(i1, i2, edges, node1, node2);
} else {
Integer node1VlanId =
i1.getSwitchportMode() == SwitchportMode.ACCESS ? i1.getAccessVlan() : null;
Integer node2VlanId =
i2.getSwitchportMode() == SwitchportMode.ACCESS ? i2.getAccessVlan() : null;
edges.add(new Layer2Edge(node1, node1VlanId, node2, node2VlanId, null));
}
}
private static void computeLayer2SelfEdges(
@Nonnull String hostname, @Nonnull Vrf vrf, @Nonnull ImmutableSet.Builder<Layer2Edge> edges) {
Map<Integer, ImmutableList.Builder<String>> switchportsByVlan = new HashMap<>();
vrf.getInterfaces()
.values()
.stream()
.filter(Interface::getActive)
.forEach(
i -> {
if (i.getSwitchportMode() == SwitchportMode.TRUNK) {
i.getAllowedVlans()
.stream()
.forEach(
vlan ->
switchportsByVlan
.computeIfAbsent(vlan, n -> ImmutableList.builder())
.add(i.getName()));
}
if (i.getSwitchportMode() == SwitchportMode.ACCESS) {
switchportsByVlan
.computeIfAbsent(i.getAccessVlan(), n -> ImmutableList.builder())
.add(i.getName());
}
});
switchportsByVlan.forEach(
(vlanId, interfaceNamesBuilder) -> {
List<String> interfaceNames = interfaceNamesBuilder.build();
CommonUtil.forEachWithIndex(
interfaceNames,
(i, i1Name) -> {
for (int j = i + 1; j < interfaceNames.size(); j++) {
String i2Name = interfaceNames.get(j);
edges.add(
new Layer2Edge(hostname, i1Name, vlanId, hostname, i2Name, vlanId, null));
edges.add(
new Layer2Edge(hostname, i2Name, vlanId, hostname, i1Name, vlanId, null));
}
});
});
}
/**
* Compute the layer-2 topology via the {@code level1Topology} and switching information contained
* in the {@code configurations}.
*/
public static @Nonnull Layer2Topology computeLayer2Topology(
@Nonnull Layer1Topology layer1Topology, @Nonnull Map<String, Configuration> configurations) {
ImmutableSet.Builder<Layer2Edge> edges = ImmutableSet.builder();
// First add layer2 edges for physical links.
layer1Topology
.getGraph()
.edges()
.stream()
.forEach(layer1Edge -> computeLayer2EdgesForLayer1Edge(layer1Edge, configurations, edges));
// Then add edges within each node to connect switchports on the same VLAN(s).
configurations
.values()
.forEach(
c -> {
c.getVrfs()
.values()
.forEach(vrf -> computeLayer2SelfEdges(c.getHostname(), vrf, edges));
});
// Now compute the transitive closure to connect interfaces across devices
Layer2Topology initial = new Layer2Topology(edges.build());
Graph<Layer2Node> initialGraph = initial.getGraph().asGraph();
Graph<Layer2Node> closure = Graphs.transitiveClosure(initialGraph);
/*
* We must remove edges connecting existing endpoint pairs since they may clash due to missing
* encapsulation vlan id. Also, we remove self-edges on the same interfaces since our network
* type does not allow them.
*/
Set<EndpointPair<Layer2Node>> newEndpoints =
Sets.difference(closure.edges(), initialGraph.edges());
newEndpoints
.stream()
.filter(ne -> !ne.source().equals(ne.target()))
.forEach(
newEndpoint ->
edges.add(new Layer2Edge(newEndpoint.source(), newEndpoint.target(), null)));
return new Layer2Topology(edges.build());
}
/**
* Compute the layer 3 topology from the layer-2 topology and layer-3 information contained in the
* configurations.
*/
public static @Nonnull Layer3Topology computeLayer3Topology(
@Nonnull Layer2Topology layer2Topology, @Nonnull Map<String, Configuration> configurations) {
/*
* The computation proceeds by augmenting the layer-2 topology with self-edges between Vlan/IRB
* interfaces and switchports on those VLANs.
* Then transitive closure and filtering are done as in layer-2 topology computation.
* Finally, the resulting edges are filtered down to those with proper layer-3 addressing,
* and transformed to only contain layer-2 relevant information.
*/
ImmutableSet.Builder<Layer3Edge> layer3Edges = ImmutableSet.builder();
Layer2Topology vlanInterfaceAugmentedLayer2Topology =
computeAugmentedLayer2Topology(layer2Topology, configurations);
vlanInterfaceAugmentedLayer2Topology
.getGraph()
.edges()
.forEach(
layer2Edge -> {
Interface i1 = getInterface(layer2Edge.getNode1(), configurations);
Interface i2 = getInterface(layer2Edge.getNode2(), configurations);
if (i1 == null
|| i2 == null
|| (i1.getOwner().equals(i2.getOwner())
&& i1.getVrfName().equals(i2.getVrfName()))) {
return;
}
if (!i1.getAllAddresses().isEmpty() || !i2.getAllAddresses().isEmpty()) {
assert Boolean.TRUE;
}
if (!matchingSubnet(i1.getAllAddresses(), i2.getAllAddresses())) {
return;
}
layer3Edges.add(toLayer3Edge(layer2Edge));
});
return new Layer3Topology(layer3Edges.build());
}
private static @Nullable Configuration getConfiguration(
Layer1Node layer1Node, Map<String, Configuration> configurations) {
return configurations.get(layer1Node.getHostname());
}
private static @Nullable Configuration getConfiguration(
Layer2Node layer2Node, Map<String, Configuration> configurations) {
return configurations.get(layer2Node.getHostname());
}
public static @Nullable Interface getInterface(
@Nonnull Layer1Node layer1Node, @Nonnull Map<String, Configuration> configurations) {
Configuration c = getConfiguration(layer1Node, configurations);
if (c == null) {
return null;
}
return c.getAllInterfaces().get(layer1Node.getInterfaceName());
}
public static @Nullable Interface getInterface(
@Nonnull Layer2Node layer2Node, @Nonnull Map<String, Configuration> configurations) {
Configuration c = getConfiguration(layer2Node, configurations);
if (c == null) {
return null;
}
return c.getAllInterfaces().get(layer2Node.getInterfaceName());
}
private static boolean matchingSubnet(
@Nonnull InterfaceAddress address1, @Nonnull InterfaceAddress address2) {
return address1.getPrefix().equals(address2.getPrefix())
&& !address1.getIp().equals(address2.getIp());
}
private static boolean matchingSubnet(
@Nonnull Set<InterfaceAddress> addresses1, @Nonnull Set<InterfaceAddress> addresses2) {
return addresses1
.stream()
.anyMatch(
address1 ->
addresses2.stream().anyMatch(address2 -> matchingSubnet(address1, address2)));
}
public static @Nonnull Edge toEdge(@Nonnull Layer3Edge layer3Edge) {
return new Edge(
toNodeInterfacePair(layer3Edge.getNode1()), toNodeInterfacePair(layer3Edge.getNode2()));
}
public static @Nonnull Layer2Node toLayer2Node(Layer1Node layer1Node, int vlanId) {
return new Layer2Node(layer1Node.getHostname(), layer1Node.getInterfaceName(), vlanId);
}
private static @Nonnull Layer3Edge toLayer3Edge(@Nonnull Layer2Edge layer2Edge) {
return new Layer3Edge(toLayer3Node(layer2Edge.getNode1()), toLayer3Node(layer2Edge.getNode2()));
}
private static @Nonnull Layer3Node toLayer3Node(@Nonnull Layer2Node node) {
return new Layer3Node(node.getHostname(), node.getInterfaceName());
}
private static @Nonnull NodeInterfacePair toNodeInterfacePair(@Nonnull Layer3Node node) {
return new NodeInterfacePair(node.getHostname(), node.getInterfaceName());
}
public static @Nonnull Topology toTopology(Layer3Topology layer3Topology) {
return new Topology(
layer3Topology
.getGraph()
.edges()
.stream()
.map(TopologyUtil::toEdge)
.collect(ImmutableSortedSet.toImmutableSortedSet(Comparator.naturalOrder())));
}
private TopologyUtil() {}
/**
* Compute the {@link Ip}s owned by each interface. hostname -> interface name -> {@link
* Ip}s.
*/
public static Map<String, Map<String, Set<Ip>>> computeInterfaceOwnedIps(
Map<String, Configuration> configurations, boolean excludeInactive) {
return computeInterfaceOwnedIps(
computeIpInterfaceOwners(computeNodeInterfaces(configurations), excludeInactive));
}
/**
* Invert a mapping from {@link Ip} to owner interfaces (Ip -> hostname -> interface name)
* to (hostname -> interface name -> Ip).
*/
private static Map<String, Map<String, Set<Ip>>> computeInterfaceOwnedIps(
Map<Ip, Map<String, Set<String>>> ipInterfaceOwners) {
Map<String, Map<String, Set<Ip>>> ownedIps = new HashMap<>();
ipInterfaceOwners.forEach(
(ip, owners) ->
owners.forEach(
(host, ifaces) ->
ifaces.forEach(
iface ->
ownedIps
.computeIfAbsent(host, k -> new HashMap<>())
.computeIfAbsent(iface, k -> new HashSet<>())
.add(ip))));
// freeze
return CommonUtil.toImmutableMap(
ownedIps,
Entry::getKey, /* host */
hostEntry ->
CommonUtil.toImmutableMap(
hostEntry.getValue(),
Entry::getKey, /* interface */
ifaceEntry -> ImmutableSet.copyOf(ifaceEntry.getValue())));
}
/**
* Invert a mapping from {@link Ip} to owner interfaces (Ip -> hostname -> interface name)
* and convert the set of owned Ips into an IpSpace.
*/
public static Map<String, Map<String, IpSpace>> computeInterfaceOwnedIpSpaces(
Map<Ip, Map<String, Set<String>>> ipInterfaceOwners) {
return CommonUtil.toImmutableMap(
computeInterfaceOwnedIps(ipInterfaceOwners),
Entry::getKey, /* host */
hostEntry ->
CommonUtil.toImmutableMap(
hostEntry.getValue(),
Entry::getKey, /* interface */
ifaceEntry ->
AclIpSpace.union(
ifaceEntry
.getValue()
.stream()
.map(Ip::toIpSpace)
.collect(Collectors.toList()))));
}
/**
* Compute a mapping of IP addresses to a set of hostnames that "own" this IP (e.g., as a network
* interface address)
*
* @param configurations {@link Configurations} keyed by hostname
* @param excludeInactive Whether to exclude inactive interfaces
* @return A map of {@link Ip}s to a set of hostnames that own this IP
*/
public static Map<Ip, Set<String>> computeIpNodeOwners(
Map<String, Configuration> configurations, boolean excludeInactive) {
return CommonUtil.toImmutableMap(
computeIpInterfaceOwners(computeNodeInterfaces(configurations), excludeInactive),
Entry::getKey, /* Ip */
ipInterfaceOwnersEntry ->
/* project away interfaces */
ipInterfaceOwnersEntry.getValue().keySet());
}
/**
* Compute a mapping from IP address to the interfaces that "own" that IP (e.g., as an network
* interface address)
*
* @param enabledInterfaces A mapping of enabled interfaces hostname -> interface name ->
* {@link Interface}
* @param excludeInactive whether to ignore inactive interfaces
* @return A map from {@link Ip}s to the {@link Interface}s that own them
*/
public static Map<Ip, Map<String, Set<String>>> computeIpInterfaceOwners(
Map<String, Set<Interface>> enabledInterfaces, boolean excludeInactive) {
Map<Ip, Map<String, Set<String>>> ipOwners = new HashMap<>();
Map<Pair<InterfaceAddress, Integer>, Set<Interface>> vrrpGroups = new HashMap<>();
enabledInterfaces.forEach(
(hostname, interfaces) ->
interfaces.forEach(
i -> {
if ((!i.getActive() || i.getBlacklisted()) && excludeInactive) {
return;
}
// collect vrrp info
i.getVrrpGroups()
.forEach(
(groupNum, vrrpGroup) -> {
InterfaceAddress address = vrrpGroup.getVirtualAddress();
if (address == null) {
/*
* Invalid VRRP configuration. The VRRP has no source IP address that
* would be used for VRRP election. This interface could never win the
* election, so is not a candidate.
*/
return;
}
Pair<InterfaceAddress, Integer> key = new Pair<>(address, groupNum);
Set<Interface> candidates =
vrrpGroups.computeIfAbsent(
key, k -> Collections.newSetFromMap(new IdentityHashMap<>()));
candidates.add(i);
});
// collect prefixes
i.getAllAddresses()
.stream()
.map(InterfaceAddress::getIp)
.forEach(
ip ->
ipOwners
.computeIfAbsent(ip, k -> new HashMap<>())
.computeIfAbsent(hostname, k -> new HashSet<>())
.add(i.getName()));
}));
vrrpGroups.forEach(
(p, candidates) -> {
InterfaceAddress address = p.getFirst();
int groupNum = p.getSecond();
/*
* Compare priorities first. If tied, break tie based on highest interface IP.
*/
Interface vrrpMaster =
Collections.max(
candidates,
Comparator.comparingInt(
(Interface o) -> o.getVrrpGroups().get(groupNum).getPriority())
.thenComparing(o -> o.getAddress().getIp()));
ipOwners
.computeIfAbsent(address.getIp(), k -> new HashMap<>())
.computeIfAbsent(vrrpMaster.getOwner().getHostname(), k -> new HashSet<>())
.add(vrrpMaster.getName());
});
// freeze
return CommonUtil.toImmutableMap(
ipOwners,
Entry::getKey,
ipOwnersEntry ->
CommonUtil.toImmutableMap(
ipOwnersEntry.getValue(),
Entry::getKey, // hostname
hostIpOwnersEntry -> ImmutableSet.copyOf(hostIpOwnersEntry.getValue())));
}
/**
* Compute a mapping of IP addresses to the VRFs that "own" this IP (e.g., as a network interface
* address).
*
* @param excludeInactive whether to ignore inactive interfaces
* @param enabledInterfaces A mapping of enabled interfaces hostname -> interface name ->
* {@link Interface}
* @return A map of {@link Ip}s to a map of hostnames to vrfs that own the Ip.
*/
public static Map<Ip, Map<String, Set<String>>> computeIpVrfOwners(
boolean excludeInactive, Map<String, Set<Interface>> enabledInterfaces) {
Map<String, Map<String, String>> interfaceVrfs =
CommonUtil.toImmutableMap(
enabledInterfaces,
Entry::getKey, /* hostname */
nodeInterfaces ->
nodeInterfaces
.getValue()
.stream()
.collect(
ImmutableMap.toImmutableMap(Interface::getName, Interface::getVrfName)));
return CommonUtil.toImmutableMap(
computeIpInterfaceOwners(enabledInterfaces, excludeInactive),
Entry::getKey, /* Ip */
ipInterfaceOwnersEntry ->
CommonUtil.toImmutableMap(
ipInterfaceOwnersEntry.getValue(),
Entry::getKey, /* Hostname */
ipNodeInterfaceOwnersEntry ->
ipNodeInterfaceOwnersEntry
.getValue()
.stream()
.map(interfaceVrfs.get(ipNodeInterfaceOwnersEntry.getKey())::get)
.collect(ImmutableSet.toImmutableSet())));
}
/**
* Aggregate a mapping (Ip -> host name -> interface name) to (Ip -> host name -> vrf
* name)
*/
public static Map<Ip, Map<String, Set<String>>> computeIpVrfOwners(
Map<Ip, Map<String, Set<String>>> ipInterfaceOwners, Map<String, Configuration> configs) {
return CommonUtil.toImmutableMap(
ipInterfaceOwners,
Entry::getKey, /* ip */
ipEntry ->
CommonUtil.toImmutableMap(
ipEntry.getValue(),
Entry::getKey, /* node */
nodeEntry ->
ImmutableSet.copyOf(
nodeEntry
.getValue()
.stream()
.map(
iface ->
configs
.get(nodeEntry.getKey())
.getAllInterfaces()
.get(iface)
.getVrfName())
.collect(Collectors.toList()))));
}
/**
* Invert a mapping from Ip to VRF owners (Ip -> host name -> VRF name) and combine all IPs
* owned by each VRF into an IpSpace.
*/
public static Map<String, Map<String, IpSpace>> computeVrfOwnedIpSpaces(
Map<Ip, Map<String, Set<String>>> ipVrfOwners) {
Map<String, Map<String, AclIpSpace.Builder>> builders = new HashMap<>();
ipVrfOwners.forEach(
(ip, ipNodeVrfs) ->
ipNodeVrfs.forEach(
(node, vrfs) ->
vrfs.forEach(
vrf ->
builders
.computeIfAbsent(node, k -> new HashMap<>())
.computeIfAbsent(vrf, k -> AclIpSpace.builder())
.thenPermitting(ip.toIpSpace()))));
return CommonUtil.toImmutableMap(
builders,
Entry::getKey, /* node */
nodeEntry ->
CommonUtil.toImmutableMap(
nodeEntry.getValue(),
Entry::getKey, /* vrf */
vrfEntry -> vrfEntry.getValue().build()));
}
/**
* Compute the interfaces of each node.
*
* @param configurations The {@link Configuration}s for the network
* @return A map from hostname to the interfaces of that node.
*/
public static Map<String, Set<Interface>> computeNodeInterfaces(
Map<String, Configuration> configurations) {
return CommonUtil.toImmutableMap(
configurations,
Entry::getKey,
e -> ImmutableSet.copyOf(e.getValue().getAllInterfaces().values()));
}
}
|
projects/batfish-common-protocol/src/main/java/org/batfish/common/topology/TopologyUtil.java
|
package org.batfish.common.topology;
import static org.batfish.common.util.CommonUtil.forEachWithIndex;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import com.google.common.graph.EndpointPair;
import com.google.common.graph.Graph;
import com.google.common.graph.Graphs;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.batfish.common.Pair;
import org.batfish.common.util.CommonUtil;
import org.batfish.datamodel.AclIpSpace;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.Edge;
import org.batfish.datamodel.Interface;
import org.batfish.datamodel.InterfaceAddress;
import org.batfish.datamodel.InterfaceType;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.IpSpace;
import org.batfish.datamodel.Route;
import org.batfish.datamodel.SwitchportMode;
import org.batfish.datamodel.Topology;
import org.batfish.datamodel.Vrf;
import org.batfish.datamodel.collections.NodeInterfacePair;
public final class TopologyUtil {
/** Returns true iff the given trunk interface allows its own native vlan. */
private static boolean trunkWithNativeVlanAllowed(Interface i) {
return i.getSwitchportMode() == SwitchportMode.TRUNK
&& i.getAllowedVlans().contains(i.getNativeVlan());
}
// Precondition: at least one of i1 and i2 is a trunk
private static void addLayer2TrunkEdges(
Interface i1,
Interface i2,
ImmutableSet.Builder<Layer2Edge> edges,
Layer1Node node1,
Layer1Node node2) {
if (i1.getSwitchportMode() == SwitchportMode.TRUNK
&& i2.getSwitchportMode() == SwitchportMode.TRUNK) {
// Both sides are trunks, so add edges from n1,v to n2,v for all shared VLANs.
i1.getAllowedVlans()
.stream()
.forEach(
vlan -> {
if (i1.getNativeVlan() == vlan && trunkWithNativeVlanAllowed(i2)) {
// This frame will not be tagged by i1, and i2 accepts untagged frames.
edges.add(new Layer2Edge(node1, vlan, node2, vlan, null /* untagged */));
} else if (i2.getAllowedVlans().contains(vlan)) {
// This frame will be tagged by i1 and we can directly check whether i2 allows.
edges.add(new Layer2Edge(node1, vlan, node2, vlan, vlan));
}
});
} else if (trunkWithNativeVlanAllowed(i1)) {
// i1 is a trunk, but the other side is not. The only edge that will come up is i2 receiving
// untagged packets.
Integer node2VlanId =
i2.getSwitchportMode() == SwitchportMode.ACCESS ? i2.getAccessVlan() : null;
edges.add(new Layer2Edge(node1, i1.getNativeVlan(), node2, node2VlanId, null));
} else if (trunkWithNativeVlanAllowed(i2)) {
// i1 is not a trunk, but the other side is. The only edge that will come up is the other
// side receiving untagged packets and treating them as native VLAN.
Integer node1VlanId =
i1.getSwitchportMode() == SwitchportMode.ACCESS ? i1.getAccessVlan() : null;
edges.add(new Layer2Edge(node1, node1VlanId, node2, i2.getNativeVlan(), null));
}
}
private static void computeAugmentedLayer2SelfEdges(
@Nonnull String hostname, @Nonnull Vrf vrf, @Nonnull ImmutableSet.Builder<Layer2Edge> edges) {
Map<Integer, ImmutableList.Builder<String>> switchportsByVlan = new HashMap<>();
vrf.getInterfaces()
.values()
.stream()
.filter(Interface::getActive)
.forEach(
i -> {
if (i.getSwitchportMode() == SwitchportMode.TRUNK) {
i.getAllowedVlans()
.stream()
.forEach(
vlan ->
switchportsByVlan
.computeIfAbsent(vlan, n -> ImmutableList.builder())
.add(i.getName()));
}
if (i.getSwitchportMode() == SwitchportMode.ACCESS) {
switchportsByVlan
.computeIfAbsent(i.getAccessVlan(), n -> ImmutableList.builder())
.add(i.getName());
}
if (i.getInterfaceType() == InterfaceType.VLAN) {
switchportsByVlan
.computeIfAbsent(i.getVlan(), n -> ImmutableList.builder())
.add(i.getName());
}
});
switchportsByVlan.forEach(
(vlanId, interfaceNamesBuilder) -> {
List<String> interfaceNames = interfaceNamesBuilder.build();
forEachWithIndex(
interfaceNames,
(i, i1Name) -> {
for (int j = i + 1; j < interfaceNames.size(); j++) {
String i2Name = interfaceNames.get(j);
edges.add(
new Layer2Edge(hostname, i1Name, vlanId, hostname, i2Name, vlanId, null));
edges.add(
new Layer2Edge(hostname, i2Name, vlanId, hostname, i1Name, vlanId, null));
}
});
});
}
private static Layer2Topology computeAugmentedLayer2Topology(
Layer2Topology layer2Topology, Map<String, Configuration> configurations) {
ImmutableSet.Builder<Layer2Edge> augmentedEdges = ImmutableSet.builder();
augmentedEdges.addAll(layer2Topology.getGraph().edges());
configurations
.values()
.forEach(
c -> {
c.getVrfs()
.values()
.forEach(
vrf -> computeAugmentedLayer2SelfEdges(c.getHostname(), vrf, augmentedEdges));
});
// Now compute the transitive closure to connect interfaces across devices
Layer2Topology initial = new Layer2Topology(augmentedEdges.build());
Graph<Layer2Node> initialGraph = initial.getGraph().asGraph();
Graph<Layer2Node> closure = Graphs.transitiveClosure(initialGraph);
/*
* We must remove edges connecting existing endpoint pairs since they may clash due to missing
* encapsulation vlan id. Also, we remove self-edges on the same interfaces by convention.
*/
Set<EndpointPair<Layer2Node>> newEndpoints =
Sets.difference(closure.edges(), initialGraph.edges());
newEndpoints
.stream()
.filter(ne -> !ne.source().equals(ne.target()))
.forEach(
newEndpoint ->
augmentedEdges.add(
new Layer2Edge(newEndpoint.source(), newEndpoint.target(), null)));
return new Layer2Topology(augmentedEdges.build());
}
public static @Nonnull Layer1Topology computeLayer1Topology(
@Nonnull Layer1Topology rawLayer1Topology,
@Nonnull Map<String, Configuration> configurations) {
/* Filter out inactive interfaces */
return new Layer1Topology(
rawLayer1Topology
.getGraph()
.edges()
.stream()
.filter(
edge -> {
Interface i1 = getInterface(edge.getNode1(), configurations);
Interface i2 = getInterface(edge.getNode2(), configurations);
return i1 != null && i2 != null && i1.getActive() && i2.getActive();
})
.collect(ImmutableSet.toImmutableSet()));
}
private static void computeLayer2EdgesForLayer1Edge(
@Nonnull Layer1Edge layer1Edge,
@Nonnull Map<String, Configuration> configurations,
@Nonnull ImmutableSet.Builder<Layer2Edge> edges) {
Layer1Node node1 = layer1Edge.getNode1();
Layer1Node node2 = layer1Edge.getNode2();
Interface i1 = getInterface(node1, configurations);
Interface i2 = getInterface(node2, configurations);
if (i1 == null || i2 == null) {
return;
}
if (i1.getSwitchportMode() == SwitchportMode.TRUNK
|| i2.getSwitchportMode() == SwitchportMode.TRUNK) {
addLayer2TrunkEdges(i1, i2, edges, node1, node2);
} else {
Integer node1VlanId =
i1.getSwitchportMode() == SwitchportMode.ACCESS ? i1.getAccessVlan() : null;
Integer node2VlanId =
i2.getSwitchportMode() == SwitchportMode.ACCESS ? i2.getAccessVlan() : null;
edges.add(new Layer2Edge(node1, node1VlanId, node2, node2VlanId, null));
}
}
private static void computeLayer2SelfEdges(
@Nonnull String hostname, @Nonnull Vrf vrf, @Nonnull ImmutableSet.Builder<Layer2Edge> edges) {
Map<Integer, ImmutableList.Builder<String>> switchportsByVlan = new HashMap<>();
vrf.getInterfaces()
.values()
.stream()
.filter(Interface::getActive)
.forEach(
i -> {
if (i.getSwitchportMode() == SwitchportMode.TRUNK) {
i.getAllowedVlans()
.stream()
.forEach(
vlan ->
switchportsByVlan
.computeIfAbsent(vlan, n -> ImmutableList.builder())
.add(i.getName()));
}
if (i.getSwitchportMode() == SwitchportMode.ACCESS) {
switchportsByVlan
.computeIfAbsent(i.getAccessVlan(), n -> ImmutableList.builder())
.add(i.getName());
}
});
switchportsByVlan.forEach(
(vlanId, interfaceNamesBuilder) -> {
List<String> interfaceNames = interfaceNamesBuilder.build();
CommonUtil.forEachWithIndex(
interfaceNames,
(i, i1Name) -> {
for (int j = i + 1; j < interfaceNames.size(); j++) {
String i2Name = interfaceNames.get(j);
edges.add(
new Layer2Edge(hostname, i1Name, vlanId, hostname, i2Name, vlanId, null));
edges.add(
new Layer2Edge(hostname, i2Name, vlanId, hostname, i1Name, vlanId, null));
}
});
});
}
/**
* Compute the layer-2 topology via the {@code level1Topology} and switching information contained
* in the {@code configurations}.
*/
public static @Nonnull Layer2Topology computeLayer2Topology(
@Nonnull Layer1Topology layer1Topology, @Nonnull Map<String, Configuration> configurations) {
ImmutableSet.Builder<Layer2Edge> edges = ImmutableSet.builder();
// First add layer2 edges for physical links.
layer1Topology
.getGraph()
.edges()
.stream()
.forEach(layer1Edge -> computeLayer2EdgesForLayer1Edge(layer1Edge, configurations, edges));
// Then add edges within each node to connect switchports on the same VLAN(s).
configurations
.values()
.forEach(
c -> {
c.getVrfs()
.values()
.forEach(vrf -> computeLayer2SelfEdges(c.getHostname(), vrf, edges));
});
// Now compute the transitive closure to connect interfaces across devices
Layer2Topology initial = new Layer2Topology(edges.build());
Graph<Layer2Node> initialGraph = initial.getGraph().asGraph();
Graph<Layer2Node> closure = Graphs.transitiveClosure(initialGraph);
/*
* We must remove edges connecting existing endpoint pairs since they may clash due to missing
* encapsulation vlan id. Also, we remove self-edges on the same interfaces since our network
* type does not allow them.
*/
Set<EndpointPair<Layer2Node>> newEndpoints =
Sets.difference(closure.edges(), initialGraph.edges());
newEndpoints
.stream()
.filter(ne -> !ne.source().equals(ne.target()))
.forEach(
newEndpoint ->
edges.add(new Layer2Edge(newEndpoint.source(), newEndpoint.target(), null)));
return new Layer2Topology(edges.build());
}
/**
* Compute the layer 3 topology from the layer-2 topology and layer-3 information contained in the
* configurations.
*/
public static @Nonnull Layer3Topology computeLayer3Topology(
@Nonnull Layer2Topology layer2Topology, @Nonnull Map<String, Configuration> configurations) {
/*
* The computation proceeds by augmenting the layer-2 topology with self-edges between Vlan/IRB
* interfaces and switchports on those VLANs.
* Then transitive closure and filtering are done as in layer-2 topology computation.
* Finally, the resulting edges are filtered down to those with proper layer-3 addressing,
* and transformed to only contain layer-2 relevant information.
*/
ImmutableSet.Builder<Layer3Edge> layer3Edges = ImmutableSet.builder();
Layer2Topology vlanInterfaceAugmentedLayer2Topology =
computeAugmentedLayer2Topology(layer2Topology, configurations);
vlanInterfaceAugmentedLayer2Topology
.getGraph()
.edges()
.forEach(
layer2Edge -> {
Interface i1 = getInterface(layer2Edge.getNode1(), configurations);
Interface i2 = getInterface(layer2Edge.getNode2(), configurations);
if (i1 == null
|| i2 == null
|| (i1.getOwner().equals(i2.getOwner())
&& i1.getVrfName().equals(i2.getVrfName()))) {
return;
}
if (!i1.getAllAddresses().isEmpty() || !i2.getAllAddresses().isEmpty()) {
assert Boolean.TRUE;
}
if (!matchingSubnet(i1.getAllAddresses(), i2.getAllAddresses())) {
return;
}
layer3Edges.add(toLayer3Edge(layer2Edge));
});
return new Layer3Topology(layer3Edges.build());
}
private static @Nullable Configuration getConfiguration(
Layer1Node layer1Node, Map<String, Configuration> configurations) {
return configurations.get(layer1Node.getHostname());
}
private static @Nullable Configuration getConfiguration(
Layer2Node layer2Node, Map<String, Configuration> configurations) {
return configurations.get(layer2Node.getHostname());
}
public static @Nullable Interface getInterface(
@Nonnull Layer1Node layer1Node, @Nonnull Map<String, Configuration> configurations) {
Configuration c = getConfiguration(layer1Node, configurations);
if (c == null) {
return null;
}
return c.getAllInterfaces().get(layer1Node.getInterfaceName());
}
public static @Nullable Interface getInterface(
@Nonnull Layer2Node layer2Node, @Nonnull Map<String, Configuration> configurations) {
Configuration c = getConfiguration(layer2Node, configurations);
if (c == null) {
return null;
}
return c.getAllInterfaces().get(layer2Node.getInterfaceName());
}
private static boolean matchingSubnet(
@Nonnull InterfaceAddress address1, @Nonnull InterfaceAddress address2) {
return address1.getPrefix().equals(address2.getPrefix())
&& !address1.getIp().equals(address2.getIp());
}
private static boolean matchingSubnet(
@Nonnull Set<InterfaceAddress> addresses1, @Nonnull Set<InterfaceAddress> addresses2) {
return addresses1
.stream()
.anyMatch(
address1 ->
addresses2.stream().anyMatch(address2 -> matchingSubnet(address1, address2)));
}
public static @Nonnull Edge toEdge(@Nonnull Layer3Edge layer3Edge) {
return new Edge(
toNodeInterfacePair(layer3Edge.getNode1()), toNodeInterfacePair(layer3Edge.getNode2()));
}
public static @Nonnull Layer2Node toLayer2Node(Layer1Node layer1Node, int vlanId) {
return new Layer2Node(layer1Node.getHostname(), layer1Node.getInterfaceName(), vlanId);
}
private static @Nonnull Layer3Edge toLayer3Edge(@Nonnull Layer2Edge layer2Edge) {
return new Layer3Edge(toLayer3Node(layer2Edge.getNode1()), toLayer3Node(layer2Edge.getNode2()));
}
private static @Nonnull Layer3Node toLayer3Node(@Nonnull Layer2Node node) {
return new Layer3Node(node.getHostname(), node.getInterfaceName());
}
private static @Nonnull NodeInterfacePair toNodeInterfacePair(@Nonnull Layer3Node node) {
return new NodeInterfacePair(node.getHostname(), node.getInterfaceName());
}
public static @Nonnull Topology toTopology(Layer3Topology layer3Topology) {
return new Topology(
layer3Topology
.getGraph()
.edges()
.stream()
.map(TopologyUtil::toEdge)
.collect(ImmutableSortedSet.toImmutableSortedSet(Comparator.naturalOrder())));
}
private TopologyUtil() {}
/**
* Compute the {@link Ip}s owned by each interface. hostname -> interface name -> {@link
* Ip}s.
*/
public static Map<String, Map<String, Set<Ip>>> computeInterfaceOwnedIps(
Map<String, Configuration> configurations, boolean excludeInactive) {
return computeInterfaceOwnedIps(
computeIpInterfaceOwners(computeNodeInterfaces(configurations), excludeInactive));
}
/**
* Invert a mapping from {@link Ip} to owner interfaces (Ip -> hostname -> interface name)
* to (hostname -> interface name -> Ip).
*/
private static Map<String, Map<String, Set<Ip>>> computeInterfaceOwnedIps(
Map<Ip, Map<String, Set<String>>> ipInterfaceOwners) {
Map<String, Map<String, Set<Ip>>> ownedIps = new HashMap<>();
ipInterfaceOwners.forEach(
(ip, owners) ->
owners.forEach(
(host, ifaces) ->
ifaces.forEach(
iface ->
ownedIps
.computeIfAbsent(host, k -> new HashMap<>())
.computeIfAbsent(iface, k -> new HashSet<>())
.add(ip))));
// freeze
return CommonUtil.toImmutableMap(
ownedIps,
Entry::getKey, /* host */
hostEntry ->
CommonUtil.toImmutableMap(
hostEntry.getValue(),
Entry::getKey, /* interface */
ifaceEntry -> ImmutableSet.copyOf(ifaceEntry.getValue())));
}
/**
* Invert a mapping from {@link Ip} to owner interfaces (Ip -> hostname -> interface name)
* and convert the set of owned Ips into an IpSpace.
*/
public static Map<String, Map<String, IpSpace>> computeInterfaceOwnedIpSpaces(
Map<Ip, Map<String, Set<String>>> ipInterfaceOwners) {
return CommonUtil.toImmutableMap(
computeInterfaceOwnedIps(ipInterfaceOwners),
Entry::getKey, /* host */
hostEntry ->
CommonUtil.toImmutableMap(
hostEntry.getValue(),
Entry::getKey, /* interface */
ifaceEntry ->
AclIpSpace.union(
ifaceEntry
.getValue()
.stream()
.map(Ip::toIpSpace)
.collect(Collectors.toList()))));
}
/**
* Compute a mapping of IP addresses to a set of hostnames that "own" this IP (e.g., as a network
* interface address)
*
* @param configurations {@link Configurations} keyed by hostname
* @param excludeInactive Whether to exclude inactive interfaces
* @return A map of {@link Ip}s to a set of hostnames that own this IP
*/
public static Map<Ip, Set<String>> computeIpNodeOwners(
Map<String, Configuration> configurations, boolean excludeInactive) {
return CommonUtil.toImmutableMap(
computeIpInterfaceOwners(computeNodeInterfaces(configurations), excludeInactive),
Entry::getKey, /* Ip */
ipInterfaceOwnersEntry ->
/* project away interfaces */
ipInterfaceOwnersEntry.getValue().keySet());
}
/**
* Compute a mapping from IP address to the interfaces that "own" that IP (e.g., as an network
* interface address)
*
* @param enabledInterfaces A mapping of enabled interfaces hostname -> interface name ->
* {@link Interface}
* @param excludeInactive whether to ignore inactive interfaces
* @return A map from {@link Ip}s to the {@link Interface}s that own them
*/
public static Map<Ip, Map<String, Set<String>>> computeIpInterfaceOwners(
Map<String, Set<Interface>> enabledInterfaces, boolean excludeInactive) {
Map<Ip, Map<String, Set<String>>> ipOwners = new HashMap<>();
Map<Pair<InterfaceAddress, Integer>, Set<Interface>> vrrpGroups = new HashMap<>();
enabledInterfaces.forEach(
(hostname, interfaces) ->
interfaces.forEach(
i -> {
if ((!i.getActive() || i.getBlacklisted()) && excludeInactive) {
return;
}
// collect vrrp info
i.getVrrpGroups()
.forEach(
(groupNum, vrrpGroup) -> {
InterfaceAddress address = vrrpGroup.getVirtualAddress();
if (address == null) {
/*
* Invalid VRRP configuration. The VRRP has no source IP address that
* would be used for VRRP election. This interface could never win the
* election, so is not a candidate.
*/
return;
}
Pair<InterfaceAddress, Integer> key = new Pair<>(address, groupNum);
Set<Interface> candidates =
vrrpGroups.computeIfAbsent(
key, k -> Collections.newSetFromMap(new IdentityHashMap<>()));
candidates.add(i);
});
// collect prefixes
i.getAllAddresses()
.stream()
.map(InterfaceAddress::getIp)
.forEach(
ip ->
ipOwners
.computeIfAbsent(ip, k -> new HashMap<>())
.computeIfAbsent(hostname, k -> new HashSet<>())
.add(i.getName()));
}));
vrrpGroups.forEach(
(p, candidates) -> {
InterfaceAddress address = p.getFirst();
int groupNum = p.getSecond();
/*
* Compare priorities first. If tied, break tie based on highest interface IP.
*/
Interface vrrpMaster =
Collections.max(
candidates,
Comparator.comparingInt(
(Interface o) -> o.getVrrpGroups().get(groupNum).getPriority())
.thenComparing(o -> o.getAddress().getIp()));
ipOwners
.computeIfAbsent(address.getIp(), k -> new HashMap<>())
.computeIfAbsent(vrrpMaster.getOwner().getHostname(), k -> new HashSet<>())
.add(vrrpMaster.getName());
});
// freeze
return CommonUtil.toImmutableMap(
ipOwners,
Entry::getKey,
ipOwnersEntry ->
CommonUtil.toImmutableMap(
ipOwnersEntry.getValue(),
Entry::getKey, // hostname
hostIpOwnersEntry -> ImmutableSet.copyOf(hostIpOwnersEntry.getValue())));
}
/**
* Compute a mapping of IP addresses to the VRFs that "own" this IP (e.g., as a network interface
* address).
*
* @param excludeInactive whether to ignore inactive interfaces
* @param enabledInterfaces A mapping of enabled interfaces hostname -> interface name ->
* {@link Interface}
* @return A map of {@link Ip}s to a map of hostnames to vrfs that own the Ip.
*/
public static Map<Ip, Map<String, Set<String>>> computeIpVrfOwners(
boolean excludeInactive, Map<String, Set<Interface>> enabledInterfaces) {
Map<String, Map<String, String>> interfaceVrfs =
CommonUtil.toImmutableMap(
enabledInterfaces,
Entry::getKey, /* hostname */
nodeInterfaces ->
nodeInterfaces
.getValue()
.stream()
.collect(
ImmutableMap.toImmutableMap(Interface::getName, Interface::getVrfName)));
return CommonUtil.toImmutableMap(
computeIpInterfaceOwners(enabledInterfaces, excludeInactive),
Entry::getKey, /* Ip */
ipInterfaceOwnersEntry ->
CommonUtil.toImmutableMap(
ipInterfaceOwnersEntry.getValue(),
Entry::getKey, /* Hostname */
ipNodeInterfaceOwnersEntry ->
ipNodeInterfaceOwnersEntry
.getValue()
.stream()
.map(interfaceVrfs.get(ipNodeInterfaceOwnersEntry.getKey())::get)
.collect(ImmutableSet.toImmutableSet())));
}
/**
* Aggregate a mapping (Ip -> host name -> interface name) to (Ip -> host name -> vrf
* name)
*/
public static Map<Ip, Map<String, Set<String>>> computeIpVrfOwners(
Map<Ip, Map<String, Set<String>>> ipInterfaceOwners, Map<String, Configuration> configs) {
return CommonUtil.toImmutableMap(
ipInterfaceOwners,
Entry::getKey, /* ip */
ipEntry ->
CommonUtil.toImmutableMap(
ipEntry.getValue(),
Entry::getKey, /* node */
nodeEntry ->
ImmutableSet.copyOf(
nodeEntry
.getValue()
.stream()
.map(
iface ->
configs
.get(nodeEntry.getKey())
.getAllInterfaces()
.get(iface)
.getVrfName())
.collect(Collectors.toList()))));
}
/**
* Invert a mapping from Ip to VRF owners (Ip -> host name -> VRF name) and combine all IPs
* owned by each VRF into an IpSpace.
*/
public static Map<String, Map<String, IpSpace>> computeVrfOwnedIpSpaces(
Map<Ip, Map<String, Set<String>>> ipVrfOwners) {
Map<String, Map<String, AclIpSpace.Builder>> builders = new HashMap<>();
ipVrfOwners.forEach(
(ip, ipNodeVrfs) ->
ipNodeVrfs.forEach(
(node, vrfs) ->
vrfs.forEach(
vrf ->
builders
.computeIfAbsent(node, k -> new HashMap<>())
.computeIfAbsent(vrf, k -> AclIpSpace.builder())
.thenPermitting(ip.toIpSpace()))));
return CommonUtil.toImmutableMap(
builders,
Entry::getKey, /* node */
nodeEntry ->
CommonUtil.toImmutableMap(
nodeEntry.getValue(),
Entry::getKey, /* vrf */
vrfEntry -> vrfEntry.getValue().build()));
}
public static Map<Ip, String> computeIpOwnersSimple(Map<Ip, Set<String>> ipOwners) {
Map<Ip, String> ipOwnersSimple = new HashMap<>();
ipOwners.forEach(
(ip, owners) -> {
String hostname =
owners.size() == 1 ? owners.iterator().next() : Route.AMBIGUOUS_NEXT_HOP;
ipOwnersSimple.put(ip, hostname);
});
return ipOwnersSimple;
}
public static Map<Ip, String> computeIpOwnersSimple(
Map<String, Configuration> configurations, boolean excludeInactive) {
return computeIpOwnersSimple(computeIpNodeOwners(configurations, excludeInactive));
}
/**
* Compute the interfaces of each node.
*
* @param configurations The {@link Configuration}s for the network
* @return A map from hostname to the interfaces of that node.
*/
public static Map<String, Set<Interface>> computeNodeInterfaces(
Map<String, Configuration> configurations) {
return CommonUtil.toImmutableMap(
configurations,
Entry::getKey,
e -> ImmutableSet.copyOf(e.getValue().getAllInterfaces().values()));
}
}
|
remove computeIpOwnersSimple (#2695)
* remove computeIpOwnersSimple
|
projects/batfish-common-protocol/src/main/java/org/batfish/common/topology/TopologyUtil.java
|
remove computeIpOwnersSimple (#2695)
|
<ide><path>rojects/batfish-common-protocol/src/main/java/org/batfish/common/topology/TopologyUtil.java
<ide> import org.batfish.datamodel.InterfaceType;
<ide> import org.batfish.datamodel.Ip;
<ide> import org.batfish.datamodel.IpSpace;
<del>import org.batfish.datamodel.Route;
<ide> import org.batfish.datamodel.SwitchportMode;
<ide> import org.batfish.datamodel.Topology;
<ide> import org.batfish.datamodel.Vrf;
<ide> vrfEntry -> vrfEntry.getValue().build()));
<ide> }
<ide>
<del> public static Map<Ip, String> computeIpOwnersSimple(Map<Ip, Set<String>> ipOwners) {
<del> Map<Ip, String> ipOwnersSimple = new HashMap<>();
<del> ipOwners.forEach(
<del> (ip, owners) -> {
<del> String hostname =
<del> owners.size() == 1 ? owners.iterator().next() : Route.AMBIGUOUS_NEXT_HOP;
<del> ipOwnersSimple.put(ip, hostname);
<del> });
<del> return ipOwnersSimple;
<del> }
<del>
<del> public static Map<Ip, String> computeIpOwnersSimple(
<del> Map<String, Configuration> configurations, boolean excludeInactive) {
<del> return computeIpOwnersSimple(computeIpNodeOwners(configurations, excludeInactive));
<del> }
<del>
<ide> /**
<ide> * Compute the interfaces of each node.
<ide> *
|
|
Java
|
apache-2.0
|
8043cf6df3678aa88505a47db12aa3ff699f9d06
| 0 |
PantherCode/arctic-core
|
/*
* Copyright 2016 PantherCode
*
* 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.panthercode.arctic.core.identity;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.panthercode.arctic.core.helper.Freezable;
import java.util.Random;
/**
* The identity class is used to manage objects in a much better way. The class offers the possibility to representing
* an object by a name. It's also possible to group more the one object in the same set of instances that belongs
* together.
* <p>
* Each object has an identifier which represents in a (pseudo) unique manner. But it's no guaranteed at all. For
* generating a new identifier a hash code consisting of name and group name is calculated and multiplied with a random
* number. Therefore the result of <code>new Identity("name","group").equals(new Identity("name","group"))</code>
* returns always false.
* <p>
* To create an new instance of the identity class use the generate() function:
* <code>Identity identity = Identity.generate(...);</code>
*/
public final class Identity implements Freezable {
/**
* unique identifier of object
*/
private long id;
/**
* name of object
*/
private String name;
/**
* name of group the object belongs to
*/
private String group;
/**
* flag to allow modifications
*/
private boolean canModify = true;
/**
* private constructor
*
* @param id unique identifier
* @param name name of object
* @param group name of group the object belongs to
*/
private Identity(long id, String name, String group) {
this.setId(id);
this.setName(name);
this.setGroup(group);
}
/**
* Returns the identifier of the object.
*
* @return Returns the identifier of the object.
*/
public long id() {
return this.id;
}
/**
* Set a new identifier. If the new identifier is less than zero the absolute value is used. This function is
* <code>synchronized</code>.
*
* @param id new identifier
*/
private synchronized void setId(long id) {
this.id = Math.abs(id);
}
/**
* Returns the name of the object.
*
* @return Returns the name of the object.
*/
public String getName() {
return this.name;
}
/**
* Set a new name if the object can be modified. If the value is null the name is set to 'unknown'.
* This function is <code>synchronized</code>.
*
* @param name new object name
* @throws RuntimeException Is thrown if the name is tried to modify, but it's not allowed.
*/
public synchronized void setName(String name)
throws RuntimeException {
if (this.canModify) {
this.name = (name == null) ? "unknown" : name;
} else {
throw new RuntimeException("The object is frozen and can't be modified.");
}
}
/**
* Returns the group name the object belongs to.
*
* @return Returns the group name the object belongs to.
*/
public String getGroup() {
return this.group;
}
/**
* Set a new group name if the object can be modified. If the value is null the group name is set to 'default'.
* This function is <code>synchronized</code>.
*
* @param group new group name
* @throws RuntimeException Is thrown if the group name is tried to modify, but it's not allowed.
*/
public synchronized void setGroup(String group)
throws RuntimeException {
if (this.canModify) {
this.group = (group == null) ? "default" : group;
} else {
throw new RuntimeException("The object is frozen and can't be modified.");
}
}
/**
* Returns a string representation of the object. The representation contains the id, name and group name.
*
* @return Returns a string representation of the object.
*/
@Override
public String toString() {
return "id = " + this.id + ", name = " + this.name + ", group = " + this.group;
}
/**
* Creates and returns a copy of this object. The identifier of the copied object will be generated again.
* If you try <code>identity.equals(identity.clone())</code> the result always is <code>false</code>. This is done
* to prevent objects with different content but same id.
*
* @return Return a copy of this object.
*/
@Override
public Identity clone() {
return Identity.generate(this.name, this.group);
}
/**
* Freeze this object. The object can't be modified. This function is <code>synchronized</code>.
*/
@Override
public synchronized void freeze() {
this.canModify = false;
}
/**
* Unfreeze this object. The object can be modified. This function is <code>synchronized</code>.
*/
@Override
public synchronized void unfreeze() {
this.canModify = true;
}
/**
* Returns a flag representing the object can be modified or not.
*
* @return Returns a boolean flag representing the object can be modified or not.
*/
@Override
public boolean canModify() {
return this.canModify;
}
/**
* Checks if an object offers an IdentityInfo annotation.
*
* @param object object to check
* @return Returns <code>true</code> if the object offers an IdentityInfo annotation; Otherwise <code>false</code>.
*/
public static boolean isAnnotated(Object object) {
return object != null && object.getClass().getAnnotation(IdentityInfo.class) != null;
}
/**
* Create a new identity from the annotation information given by an object. If the annotation is empty or the
* object has no annotation at all a default identity object is returned.
*
* @return Returns an identity made of annotation information.
*/
public static Identity fromAnnotation(Object object) {
if (object != null) {
IdentityInfo info = object.getClass().getAnnotation(IdentityInfo.class);
if (info != null) {
return Identity.generate(info.name(), info.group());
}
}
return Identity.generate();
}
/**
* Returns a hash code value of this object.
*
* @return Returns a hash code value of this object.
*/
@Override
public int hashCode() {
return Math.abs(new HashCodeBuilder()
.append(this.id)
.append(this.name)
.append(this.group)
.toHashCode());
}
/**
* Checks if this object is equals to another one. Two identity objects are equal if they have the same name and
* the same group name. The identifier is ignored.
*
* @param obj other object to check
* @return Returns <code>true</code> if two identity objects have the same name and group name.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Identity)) {
return false;
}
Identity identity = (Identity) obj;
return this.getName().equals(identity.getName())
&& this.getGroup().equals(identity.getGroup());
}
/**
* Generates a new identity object. The name is set to 'unknown' and group name to 'default'.
*
* @return Returns a new identity object.
*/
public static Identity generate() {
return Identity.generate(null);
}
/**
* Generates a new identity object. The group name is set to 'default'.
*
* @param name new object name
* @return Returns a new identity object.
*/
public static Identity generate(String name) {
return Identity.generate(name, null);
}
/**
* Generates a new identity object with given object and group name.
* This function is <code>synchronized</code>.
*
* @param name new object name
* @param group new group name
* @return Returns a new identity object.
*/
public static Identity generate(String name, String group) {
Random seed = new Random(System.currentTimeMillis());
HashCodeBuilder builder = new HashCodeBuilder();
long id = builder.append(name)
.append(group).toHashCode();
id = Math.abs(id * seed.nextLong());
return new Identity(id, name, group);
}
}
|
src/main/java/org/panthercode/arctic/core/identity/Identity.java
|
/*
* Copyright 2016 PantherCode
*
* 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.panthercode.arctic.core.identity;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.panthercode.arctic.core.helper.Freezable;
import java.util.Random;
/**
* The identity class is used to manage objects in a much better way. The class offers the possibility to representing
* an object by a name. It's also possible to group more the one object in the same set of instances that belongs
* together.
* <p>
* Each object has an identifier which represents in a (pseudo) unique manner. But it's no guaranteed at all. For
* generating a new identifier a hash code consisting of name and group name is calculated and multiplied with a random
* number. Therefore the result of <code>new Identity("name","group").equals(new Identity("name","group"))</code>
* returns always false.
*/
public final class Identity implements Freezable {
/**
* unique identifier of object
*/
private long id;
/**
* name of object
*/
private String name;
/**
* name of group the object belongs to
*/
private String group;
/**
* flag to allow modifications
*/
private boolean canModify = true;
/**
* private constructor
*
* @param id unique identifier
* @param name name of object
* @param group name of group the object belongs to
*/
private Identity(long id, String name, String group) {
this.setId(id);
this.setName(name);
this.setGroup(group);
}
/**
* Returns the identifier of the object.
*
* @return Returns the identifier of the object.
*/
public long id() {
return this.id;
}
/**
* Set a new identifier. If the new identifier is less than zero the absolute value is used. This function is
* <code>synchronized</code>.
*
* @param id new identifier
*/
private synchronized void setId(long id) {
this.id = Math.abs(id);
}
/**
* Returns the name of the object.
*
* @return Returns the name of the object.
*/
public String getName() {
return this.name;
}
/**
* Set a new name if the object can be modified. If the value is null the name is set to 'unknown'.
* This function is <code>synchronized</code>.
*
* @param name new object name
* @throws RuntimeException Is thrown if the name is tried to modify, but it's not allowed.
*/
public synchronized void setName(String name)
throws RuntimeException {
if (this.canModify) {
this.name = (name == null) ? "unknown" : name;
} else {
throw new RuntimeException("The object is frozen and can't be modified.");
}
}
/**
* Returns the group name the object belongs to.
*
* @return Returns the group name the object belongs to.
*/
public String getGroup() {
return this.group;
}
/**
* Set a new group name if the object can be modified. If the value is null the group name is set to 'default'.
* This function is <code>synchronized</code>.
*
* @param group new group name
* @throws RuntimeException Is thrown if the group name is tried to modify, but it's not allowed.
*/
public synchronized void setGroup(String group)
throws RuntimeException {
if (this.canModify) {
this.group = (group == null) ? "default" : group;
} else {
throw new RuntimeException("The object is frozen and can't be modified.");
}
}
/**
* Returns a string representation of the object. The representation contains the id, name and group name.
*
* @return Returns a string representation of the object.
*/
@Override
public String toString() {
return "id = " + this.id + ", name = " + this.name + ", group = " + this.group;
}
/**
* Creates and returns a copy of this object. The identifier of the copied object will be generated again.
* If you try <code>identity.equals(identity.clone())</code> the result always is <code>false</code>. This is done
* to prevent objects with different content but same id.
*
* @return Return a copy of this object.
*/
@Override
public Identity clone() {
return Identity.generate(this.name, this.group);
}
/**
* Freeze this object. The object can't be modified. This function is <code>synchronized</code>.
*/
@Override
public synchronized void freeze() {
this.canModify = false;
}
/**
* Unfreeze this object. The object can be modified. This function is <code>synchronized</code>.
*/
@Override
public synchronized void unfreeze() {
this.canModify = true;
}
/**
* Returns a flag representing the object can be modified or not.
*
* @return Returns a boolean flag representing the object can be modified or not.
*/
@Override
public boolean canModify() {
return this.canModify;
}
/**
* Checks if an object offers an IdentityInfo annotation.
*
* @param object object to check
* @return Returns <code>true</code> if the object offers an IdentityInfo annotation; Otherwise <code>false</code>.
*/
public static boolean isAnnotated(Object object) {
if (object != null) {
return object.getClass().getAnnotation(IdentityInfo.class) != null;
}
return false;
}
/**
* Create a new identity from the annotation information given by an object. If the annotation is empty or the
* object has no annotation at all a default identity object is returned.
*
* @return Returns an identity made of annotation information.
*/
public static Identity fromAnnotation(Object object) {
if (object != null) {
IdentityInfo info = object.getClass().getAnnotation(IdentityInfo.class);
if (info != null) {
return Identity.generate(info.name(), info.group());
}
}
return Identity.generate();
}
/**
* Returns a hash code value of this object.
*
* @return Returns a hash code value of this object.
*/
@Override
public int hashCode() {
return Math.abs(new HashCodeBuilder()
.append(this.id)
.append(this.name)
.append(this.group)
.toHashCode());
}
/**
* Checks if this object is equals to another one. Two identity objects are equal if they have the same name and
* the same group name. The identifier is ignored.
*
* @param obj other object to check
* @return Returns <code>true</code> if two identity objects have the same name and group name.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Identity)) {
return false;
}
Identity identity = (Identity) obj;
return this.getName().equals(identity.getName())
&& this.getGroup().equals(identity.getGroup());
}
/**
* Generates a new identity object. The name is set to 'unknown' and group name to 'default'.
*
* @return Returns a new identity object.
*/
public static Identity generate() {
return Identity.generate(null);
}
/**
* Generates a new identity object. The group name is set to 'default'.
*
* @param name new object name
* @return Returns a new identity object.
*/
public static Identity generate(String name) {
return Identity.generate(name, null);
}
/**
* Generates a new identity object with given object and group name.
* This function is <code>synchronized</code>.
*
* @param name new object name
* @param group new group name
* @return Returns a new identity object.
*/
public static Identity generate(String name, String group) {
Random seed = new Random(System.currentTimeMillis());
HashCodeBuilder builder = new HashCodeBuilder();
long id = builder.append(name)
.append(group).toHashCode();
id = Math.abs(id * seed.nextLong());
return new Identity(id, name, group);
}
}
|
modify Identetiy class
|
src/main/java/org/panthercode/arctic/core/identity/Identity.java
|
modify Identetiy class
|
<ide><path>rc/main/java/org/panthercode/arctic/core/identity/Identity.java
<ide> * generating a new identifier a hash code consisting of name and group name is calculated and multiplied with a random
<ide> * number. Therefore the result of <code>new Identity("name","group").equals(new Identity("name","group"))</code>
<ide> * returns always false.
<add> * <p>
<add> * To create an new instance of the identity class use the generate() function:
<add> * <code>Identity identity = Identity.generate(...);</code>
<ide> */
<ide> public final class Identity implements Freezable {
<ide>
<ide> * @return Returns <code>true</code> if the object offers an IdentityInfo annotation; Otherwise <code>false</code>.
<ide> */
<ide> public static boolean isAnnotated(Object object) {
<del> if (object != null) {
<del> return object.getClass().getAnnotation(IdentityInfo.class) != null;
<del> }
<del>
<del> return false;
<add> return object != null && object.getClass().getAnnotation(IdentityInfo.class) != null;
<add>
<ide> }
<ide>
<ide> /**
|
|
Java
|
mit
|
bebb9bb30c1345f0cc4c75c5edbe7b3ddf67ce1f
| 0 |
lelloman/android-lousyaudiolibrary,lelloman/android-lousyaudiolibrary,lelloman/android-lousyaudiolibrary
|
package com.lelloman.lousyaudiolibrary.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import com.lelloman.lousyaudiolibrary.R;
import com.lelloman.lousyaudiolibrary.reader.volume.IVolumeReader;
public class VolumeView extends View{
public interface VolumeViewListener {
void onSingleTap(VolumeView volumeView, float percentX);
void onDoubleTap(VolumeView volumeView, float percentX);
void onWindowSelected(VolumeView volumeView, float start, float end);
}
public static final int K = 4;
private static final Object BITMAP_LOCK = 0xb00b5;
private static final int DEFAULT_BG_COLOR = 0xffbbbbbb;
private static final int DEFAULT_PAINT_COLOR = 0xff000000;
private static final int DEFAULT_CURSOR_COLOR = 0xffffff00;
private static final ColorMatrix INVERT_COLOR_MATRIX = new ColorMatrix(new float[]{
-1, 0, 0, 0, 255,
0, -1, 0, 0, 255,
0, 0, -1, 0, 255,
0, 0, 0, 1, 0
});
private Paint paint = new Paint();
private Paint cursorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint invertedPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint draggingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int bgColor = DEFAULT_BG_COLOR;
private Bitmap bitmap;
private Canvas canvas;
private Rect srcRect, dstRect;
private Rect subWindowSrcRect, subWindowDstRect;
private boolean dragging;
private float draggingX;
private boolean hasSecondCursor;
private float cursor = 0;
protected VolumeViewListener listener;
private IVolumeReader volumeReader;
private int minHeight, maxHeight;
private int zoomLevel;
private GestureDetector gestureDetector;
private boolean canDrag = true;
private boolean hasSubWindow = false;
private float subWindowStart, subWindowEnd;
public VolumeView(Context context) {
this(context, null);
}
public VolumeView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setStyle(Paint.Style.STROKE);
invertedPaint.setStyle(Paint.Style.FILL);
invertedPaint.setColorFilter(new ColorMatrixColorFilter(INVERT_COLOR_MATRIX));
cursorPaint.setStyle(Paint.Style.STROKE);
cursorPaint.setStrokeWidth(2 * getResources().getDisplayMetrics().density);
dstRect = new Rect(0, 0, 1, 1);
subWindowSrcRect = new Rect(0, 0, 1, 1);
subWindowDstRect = new Rect(0, 0, 1, 1);
draggingPaint.setStyle(Paint.Style.STROKE);
draggingPaint.setAlpha(155);
setupColors();
gestureDetector = new GestureDetector(context, new GestureDetecotr());
}
private void setupColors(){
TypedValue typedValue = new TypedValue();
TypedArray a = getContext().obtainStyledAttributes(typedValue.data, new int[] {
R.attr.colorPrimary,
R.attr.colorPrimaryDark,
R.attr.colorAccent,
android.R.attr.windowBackground
});
int paintColor = a.getColor(1, DEFAULT_PAINT_COLOR);
int cursorColor = a.getColor(2, DEFAULT_CURSOR_COLOR);
bgColor = a.getColor(3, DEFAULT_BG_COLOR);
a.recycle();
paint.setColor(paintColor);
cursorPaint.setColor(cursorColor);
draggingPaint.setColor(cursorColor);
}
public void setVolumeReader(IVolumeReader volumeReader) {
this.volumeReader = volumeReader;
selectZoomLevel(getWidth(), getHeight());
if (bitmap != null) {
drawBitmap();
}
}
public void setSubWindow(float start, float end) {
hasSubWindow = true;
subWindowStart = start;
subWindowEnd = end;
}
public void unSetSubWindow() {
hasSubWindow = false;
}
public void setListener(VolumeViewListener l) {
this.listener = l;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w == 0 || h == 0) return;
int height = getHeight();
minHeight = (int) (height * .05f);
maxHeight = (int) (height * .95f);
selectZoomLevel(w, h);
drawBitmap();
}
private void selectZoomLevel(int width, int height) {
if (volumeReader == null || width < 1 || height < 1) return;
width /= K;
int[] levels = volumeReader.getZoomLevels();
zoomLevel = levels.length - 1;
for (int i = 0; i < levels.length; i++) {
if (levels[i] >= width) {
this.zoomLevel = i;
break;
}
}
synchronized (BITMAP_LOCK) {
if (bitmap != null) {
bitmap.recycle();
}
bitmap = Bitmap.createBitmap(levels[zoomLevel], height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawColor(bgColor);
srcRect = new Rect(0, 0, levels[zoomLevel], height);
}
}
private void drawBitmap() {
if (volumeReader == null) return;
synchronized (BITMAP_LOCK) {
int i = 0;
double value = volumeReader.getVolume(zoomLevel, i);
while (value != Double.POSITIVE_INFINITY) {
drawFrame(i++, value);
value = volumeReader.getVolume(zoomLevel, i);
}
}
}
public void resetDrag() {
dragging = false;
postInvalidate();
}
/*@Override
public void onNewFrame(int zoomLevel, int frameIndex, int totFrames, double value) {
if (canvas == null || zoomLevel != this.zoomLevel) return;
drawFrame(frameIndex, value);
postInvalidate();
}
@Override
public void onFrameReadingEnd() {
drawBitmap();
postInvalidate();
}*/
private void drawFrame(int i1, double value0) {
synchronized (BITMAP_LOCK) {
if(canvas != null) {
if (value0 == Double.POSITIVE_INFINITY) return;
int height = getHeight();
int barLength0 = minHeight + (int) (value0 * maxHeight);
int y0up = (height - barLength0) / 2;
int y0down = height - y0up;
float x0 = i1;
canvas.drawLine(x0, y0up, x0, y0down, paint);
}
}
}
public void setCursor(float d) {
this.cursor = d;
postInvalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(bgColor);
int width = canvas.getWidth();
int height = canvas.getHeight();
synchronized (BITMAP_LOCK) {
if (bitmap != null) {
dstRect.set(0, 0, width, height);
canvas.drawBitmap(bitmap, srcRect, dstRect, null);// hasSubWindow ? invertedPaint : null);
}
}
if (hasSubWindow) {
int left = (int) (width * subWindowStart);
int right = (int) (width * subWindowEnd);
subWindowDstRect.set(left, 0, right, height);
left = (int) (bitmap.getWidth() * subWindowStart);
right = (int) (bitmap.getWidth() * subWindowEnd);
subWindowSrcRect.set(left, 0, right, bitmap.getHeight());
//canvas.drawBitmap(bitmap, subWindowSrcRect, subWindowDstRect, null);
canvas.drawRect(subWindowDstRect, cursorPaint);
}
int x = (int) (width * cursor);
canvas.drawLine(x, height, x, 0, cursorPaint);
if (dragging || hasSecondCursor) {
canvas.drawLine(draggingX, 0, draggingX, canvas.getHeight(), draggingPaint);
}
}
protected void onSingleTup(MotionEvent event) {
dragging = false;
if (listener != null) {
float x = event.getX() / getWidth();
listener.onSingleTap(this, x);
}
}
protected void onDoubleTap(MotionEvent event) {
dragging = false;
if (listener != null) {
float x = event.getX() / getWidth();
listener.onDoubleTap(this, x);
}
}
protected void onLongPress(MotionEvent event) {
if (canDrag) {
dragging = true;
draggingX = event.getX();
postInvalidate();
}
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
gestureDetector.onTouchEvent(motionEvent);
int action = motionEvent.getAction();
if (dragging && action == motionEvent.ACTION_MOVE) {
draggingX = motionEvent.getX();
} else if (dragging && action == motionEvent.ACTION_UP) {
draggingX = motionEvent.getX();
dragging = false;
hasSecondCursor = true;
if (listener != null) {
float secondCursor = draggingX / getWidth();
listener.onWindowSelected(this, Math.min(getCursor(), secondCursor), Math.max(getCursor(), secondCursor));
}
}
postInvalidate();
return true;
}
protected Rect getDstRect() {
return dstRect;
}
public float getCursor() {
return cursor;
}
public IVolumeReader getVolumeReader() {
return volumeReader;
}
public void setCanDrag(boolean b) {
canDrag = b;
if (!canDrag) {
hasSecondCursor = false;
dragging = false;
}
}
private class GestureDetecotr extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap(MotionEvent event) {
VolumeView.this.onDoubleTap(event);
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent event) {
VolumeView.this.onSingleTup(event);
return true;
}
@Override
public void onLongPress(MotionEvent event) {
VolumeView.this.onLongPress(event);
}
}
}
|
library/src/main/java/com/lelloman/lousyaudiolibrary/view/VolumeView.java
|
package com.lelloman.lousyaudiolibrary.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import com.lelloman.lousyaudiolibrary.R;
import com.lelloman.lousyaudiolibrary.reader.volume.IVolumeReader;
import com.lelloman.lousyaudiolibrary.reader.volume.VolumeReader;
public class VolumeView extends View implements VolumeReader.OnVolumeReadListener {
public interface VolumeViewListener {
void onSingleTap(VolumeView volumeView, float percentX);
void onDoubleTap(VolumeView volumeView, float percentX);
void onWindowSelected(VolumeView volumeView, float start, float end);
}
public static final int K = 4;
private static final Object BITMAP_LOCK = 0xb00b5;
private static final int DEFAULT_BG_COLOR = 0xffbbbbbb;
private static final int DEFAULT_PAINT_COLOR = 0xff000000;
private static final int DEFAULT_CURSOR_COLOR = 0xffffff00;
private static final ColorMatrix INVERT_COLOR_MATRIX = new ColorMatrix(new float[]{
-1, 0, 0, 0, 255,
0, -1, 0, 0, 255,
0, 0, -1, 0, 255,
0, 0, 0, 1, 0
});
private Paint paint = new Paint();
private Paint cursorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint invertedPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint draggingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private int bgColor = DEFAULT_BG_COLOR;
private Bitmap bitmap;
private Canvas canvas;
private Rect srcRect, dstRect;
private Rect subWindowSrcRect, subWindowDstRect;
private boolean dragging;
private float draggingX;
private boolean hasSecondCursor;
private float cursor = 0;
protected VolumeViewListener listener;
private IVolumeReader volumeReader;
private int minHeight, maxHeight;
private int zoomLevel;
private GestureDetector gestureDetector;
private boolean canDrag = true;
private boolean hasSubWindow = false;
private float subWindowStart, subWindowEnd;
public VolumeView(Context context) {
this(context, null);
}
public VolumeView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setStyle(Paint.Style.STROKE);
invertedPaint.setStyle(Paint.Style.FILL);
invertedPaint.setColorFilter(new ColorMatrixColorFilter(INVERT_COLOR_MATRIX));
cursorPaint.setStyle(Paint.Style.STROKE);
cursorPaint.setStrokeWidth(2 * getResources().getDisplayMetrics().density);
dstRect = new Rect(0, 0, 1, 1);
subWindowSrcRect = new Rect(0, 0, 1, 1);
subWindowDstRect = new Rect(0, 0, 1, 1);
draggingPaint.setStyle(Paint.Style.STROKE);
draggingPaint.setAlpha(155);
setupColors();
gestureDetector = new GestureDetector(context, new GestureDetecotr());
}
private void setupColors(){
TypedValue typedValue = new TypedValue();
TypedArray a = getContext().obtainStyledAttributes(typedValue.data, new int[] {
R.attr.colorPrimary,
R.attr.colorPrimaryDark,
R.attr.colorAccent,
android.R.attr.windowBackground
});
int paintColor = a.getColor(1, DEFAULT_PAINT_COLOR);
int cursorColor = a.getColor(2, DEFAULT_CURSOR_COLOR);
bgColor = a.getColor(3, DEFAULT_BG_COLOR);
a.recycle();
paint.setColor(paintColor);
cursorPaint.setColor(cursorColor);
draggingPaint.setColor(cursorColor);
}
public void setVolumeReader(IVolumeReader volumeReader) {
this.volumeReader = volumeReader;
volumeReader.setOnVolumeReadListener(this);
selectZoomLevel(getWidth(), getHeight());
if (bitmap != null) {
drawBitmap();
}
}
public void setSubWindow(float start, float end) {
hasSubWindow = true;
subWindowStart = start;
subWindowEnd = end;
}
public void unSetSubWindow() {
hasSubWindow = false;
}
public void setListener(VolumeViewListener l) {
this.listener = l;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w == 0 || h == 0) return;
int height = getHeight();
minHeight = (int) (height * .05f);
maxHeight = (int) (height * .95f);
selectZoomLevel(w, h);
drawBitmap();
}
private void selectZoomLevel(int width, int height) {
if (volumeReader == null || width < 1 || height < 1) return;
width /= K;
int[] levels = volumeReader.getZoomLevels();
zoomLevel = levels.length - 1;
for (int i = 0; i < levels.length; i++) {
if (levels[i] >= width) {
this.zoomLevel = i;
break;
}
}
synchronized (BITMAP_LOCK) {
if (bitmap != null) {
bitmap.recycle();
}
bitmap = Bitmap.createBitmap(levels[zoomLevel], height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
canvas.drawColor(bgColor);
srcRect = new Rect(0, 0, levels[zoomLevel], height);
}
}
private void drawBitmap() {
if (volumeReader == null) return;
synchronized (BITMAP_LOCK) {
int i = 0;
double value = volumeReader.getVolume(zoomLevel, i);
while (value != Double.POSITIVE_INFINITY) {
drawFrame(i++, value);
value = volumeReader.getVolume(zoomLevel, i);
}
}
}
public void resetDrag() {
dragging = false;
postInvalidate();
}
@Override
public void onNewFrame(int zoomLevel, int frameIndex, int totFrames, double value) {
if (canvas == null || zoomLevel != this.zoomLevel) return;
drawFrame(frameIndex, value);
postInvalidate();
}
@Override
public void onFrameReadingEnd() {
drawBitmap();
postInvalidate();
}
private void drawFrame(int i1, double value0) {
synchronized (BITMAP_LOCK) {
if(canvas != null) {
if (value0 == Double.POSITIVE_INFINITY) return;
int height = getHeight();
int barLength0 = minHeight + (int) (value0 * maxHeight);
int y0up = (height - barLength0) / 2;
int y0down = height - y0up;
float x0 = i1;
canvas.drawLine(x0, y0up, x0, y0down, paint);
}
}
}
public void setCursor(float d) {
this.cursor = d;
postInvalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(bgColor);
int width = canvas.getWidth();
int height = canvas.getHeight();
synchronized (BITMAP_LOCK) {
if (bitmap != null) {
dstRect.set(0, 0, width, height);
canvas.drawBitmap(bitmap, srcRect, dstRect, null);// hasSubWindow ? invertedPaint : null);
}
}
if (hasSubWindow) {
int left = (int) (width * subWindowStart);
int right = (int) (width * subWindowEnd);
subWindowDstRect.set(left, 0, right, height);
left = (int) (bitmap.getWidth() * subWindowStart);
right = (int) (bitmap.getWidth() * subWindowEnd);
subWindowSrcRect.set(left, 0, right, bitmap.getHeight());
//canvas.drawBitmap(bitmap, subWindowSrcRect, subWindowDstRect, null);
canvas.drawRect(subWindowDstRect, cursorPaint);
}
int x = (int) (width * cursor);
canvas.drawLine(x, height, x, 0, cursorPaint);
if (dragging || hasSecondCursor) {
canvas.drawLine(draggingX, 0, draggingX, canvas.getHeight(), draggingPaint);
}
}
protected void onSingleTup(MotionEvent event) {
dragging = false;
if (listener != null) {
float x = event.getX() / getWidth();
listener.onSingleTap(this, x);
}
}
protected void onDoubleTap(MotionEvent event) {
dragging = false;
if (listener != null) {
float x = event.getX() / getWidth();
listener.onDoubleTap(this, x);
}
}
protected void onLongPress(MotionEvent event) {
if (canDrag) {
dragging = true;
draggingX = event.getX();
postInvalidate();
}
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
gestureDetector.onTouchEvent(motionEvent);
int action = motionEvent.getAction();
if (dragging && action == motionEvent.ACTION_MOVE) {
draggingX = motionEvent.getX();
} else if (dragging && action == motionEvent.ACTION_UP) {
draggingX = motionEvent.getX();
dragging = false;
hasSecondCursor = true;
if (listener != null) {
float secondCursor = draggingX / getWidth();
listener.onWindowSelected(this, Math.min(getCursor(), secondCursor), Math.max(getCursor(), secondCursor));
}
}
postInvalidate();
return true;
}
protected Rect getDstRect() {
return dstRect;
}
public float getCursor() {
return cursor;
}
public IVolumeReader getVolumeReader() {
return volumeReader;
}
public void setCanDrag(boolean b) {
canDrag = b;
if (!canDrag) {
hasSecondCursor = false;
dragging = false;
}
}
private class GestureDetecotr extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDoubleTap(MotionEvent event) {
VolumeView.this.onDoubleTap(event);
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent event) {
VolumeView.this.onSingleTup(event);
return true;
}
@Override
public void onLongPress(MotionEvent event) {
VolumeView.this.onLongPress(event);
}
}
}
|
removed OnVolumeReadListener from VolumeView
|
library/src/main/java/com/lelloman/lousyaudiolibrary/view/VolumeView.java
|
removed OnVolumeReadListener from VolumeView
|
<ide><path>ibrary/src/main/java/com/lelloman/lousyaudiolibrary/view/VolumeView.java
<ide>
<ide> import com.lelloman.lousyaudiolibrary.R;
<ide> import com.lelloman.lousyaudiolibrary.reader.volume.IVolumeReader;
<del>import com.lelloman.lousyaudiolibrary.reader.volume.VolumeReader;
<del>
<del>
<del>public class VolumeView extends View implements VolumeReader.OnVolumeReadListener {
<add>
<add>public class VolumeView extends View{
<ide>
<ide> public interface VolumeViewListener {
<ide> void onSingleTap(VolumeView volumeView, float percentX);
<ide>
<ide> public void setVolumeReader(IVolumeReader volumeReader) {
<ide> this.volumeReader = volumeReader;
<del> volumeReader.setOnVolumeReadListener(this);
<ide> selectZoomLevel(getWidth(), getHeight());
<ide> if (bitmap != null) {
<ide> drawBitmap();
<ide> postInvalidate();
<ide> }
<ide>
<del> @Override
<add> /*@Override
<ide> public void onNewFrame(int zoomLevel, int frameIndex, int totFrames, double value) {
<ide>
<ide> if (canvas == null || zoomLevel != this.zoomLevel) return;
<ide> public void onFrameReadingEnd() {
<ide> drawBitmap();
<ide> postInvalidate();
<del> }
<add> }*/
<ide>
<ide> private void drawFrame(int i1, double value0) {
<ide> synchronized (BITMAP_LOCK) {
|
|
Java
|
bsd-3-clause
|
7ed6299ccdc3f6ae062abd80b433eb4b2d06e09f
| 0 |
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
|
package gov.nih.nci.calab.ui.submit;
/**
* This class creates nanoparticle general information and assigns visibility
*
* @author pansu
*/
/* CVS $Id: AddParticlePropertiesAction.java,v 1.6 2006-08-14 17:59:23 pansu Exp $ */
import gov.nih.nci.calab.dto.particle.BuckeyballBean;
import gov.nih.nci.calab.dto.particle.DendrimerBean;
import gov.nih.nci.calab.dto.particle.FullereneBean;
import gov.nih.nci.calab.dto.particle.LiposomeBean;
import gov.nih.nci.calab.dto.particle.MetalParticleBean;
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.dto.particle.PolymerBean;
import gov.nih.nci.calab.dto.particle.QuantumDotBean;
import gov.nih.nci.calab.dto.particle.SurfaceGroupBean;
import gov.nih.nci.calab.service.submit.AddParticlePropertiesService;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class AddParticlePropertiesAction extends AbstractDispatchAction {
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
// TODO fill in details for sample information */
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
ParticleBean particle = null;
if (particleType.equalsIgnoreCase("dendrimer")) {
particle = (DendrimerBean) theForm.get("dendrimer");
} else if (particleType.equalsIgnoreCase("polymer")) {
particle = (PolymerBean) theForm.get("polymer");
} else if (particleType.equalsIgnoreCase("liposome")) {
particle = (LiposomeBean) theForm.get("liposome");
} else if (particleType.equalsIgnoreCase("buckeyball")) {
particle = (BuckeyballBean) theForm.get("buckyball");
} else if (particleType.equalsIgnoreCase("fullerene")) {
particle = (FullereneBean) theForm.get("fullerene");
} else if (particleType.equalsIgnoreCase("quantum dot")) {
particle = (QuantumDotBean) theForm.get("quantumDot");
} else if (particleType.equalsIgnoreCase("metal particle")) {
particle = (MetalParticleBean) theForm.get("metalParticle");
}
AddParticlePropertiesService service = new AddParticlePropertiesService();
service.addParticleProperties(particleType, particle);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.addParticleProperties");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.findForward("success");
return forward;
}
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
HttpSession session=request.getSession();
if (particleType.equalsIgnoreCase("dendrimer")) {
InitSessionSetup.getInstance().setAllDendrimerCores(session);
InitSessionSetup.getInstance().setAllDendrimerSurfaceGroupNames(session);
}
theForm.set("particlePage", mapping.findForward(
particleType.toLowerCase()).getPath());
return mapping.getInputForward();
}
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
// update surface group info for dendrimers
if (particleType.equalsIgnoreCase("dendrimer")) {
DendrimerBean particle = (DendrimerBean) theForm.get("dendrimer");
updateSurfaceGroups(particle);
theForm.set("dendrimer", particle);
theForm.set("particlePage", mapping.findForward(
particleType.toLowerCase()).getPath());
}
return mapping.getInputForward();
}
private void updateSurfaceGroups(DendrimerBean particle) {
String numberOfSurfaceGroups = particle.getNumberOfSurfaceGroups();
int surfaceGroupNum = Integer.parseInt(numberOfSurfaceGroups);
List<SurfaceGroupBean> origSurfaceGroups = particle.getSurfaceGroups();
int origNum = (origSurfaceGroups == null) ? 0 : origSurfaceGroups
.size();
List<SurfaceGroupBean> surfaceGroups = new ArrayList<SurfaceGroupBean>();
// create new ones
if (origNum == 0) {
for (int i = 0; i < surfaceGroupNum; i++) {
SurfaceGroupBean surfaceGroup = new SurfaceGroupBean();
surfaceGroups.add(surfaceGroup);
}
}
// use keep original surface group info
else if (surfaceGroupNum <= origNum) {
for (int i = 0; i < surfaceGroupNum; i++) {
surfaceGroups.add((SurfaceGroupBean) origSurfaceGroups.get(i));
}
} else {
for (int i = 0; i < origNum; i++) {
surfaceGroups.add((SurfaceGroupBean) origSurfaceGroups.get(i));
}
for (int i = origNum; i < surfaceGroupNum; i++) {
surfaceGroups.add(new SurfaceGroupBean());
}
}
particle.setSurfaceGroups(surfaceGroups);
}
public boolean loginRequired() {
return true;
}
}
|
src/gov/nih/nci/calab/ui/submit/AddParticlePropertiesAction.java
|
package gov.nih.nci.calab.ui.submit;
/**
* This class creates nanoparticle general information and assigns visibility
*
* @author pansu
*/
/* CVS $Id: AddParticlePropertiesAction.java,v 1.5 2006-08-14 13:48:52 zengje Exp $ */
import gov.nih.nci.calab.dto.particle.BuckeyballBean;
import gov.nih.nci.calab.dto.particle.DendrimerBean;
import gov.nih.nci.calab.dto.particle.FullereneBean;
import gov.nih.nci.calab.dto.particle.LiposomeBean;
import gov.nih.nci.calab.dto.particle.MetalParticleBean;
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.dto.particle.PolymerBean;
import gov.nih.nci.calab.dto.particle.QuantumDotBean;
import gov.nih.nci.calab.service.submit.AddParticlePropertiesService;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class AddParticlePropertiesAction extends AbstractDispatchAction {
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
// TODO fill in details for sample information */
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
ParticleBean particle = null;
if (particleType.equalsIgnoreCase("dendrimer")) {
particle = (DendrimerBean) theForm.get("dendrimer");
} else if (particleType.equalsIgnoreCase("polymer")) {
particle = (PolymerBean) theForm.get("polymer");
} else if (particleType.equalsIgnoreCase("liposome")) {
particle = (LiposomeBean) theForm.get("liposome");
} else if (particleType.equalsIgnoreCase("buckeyball")) {
particle = (BuckeyballBean) theForm.get("buckyball");
} else if (particleType.equalsIgnoreCase("fullerene")) {
particle = (FullereneBean) theForm.get("fullerene");
} else if (particleType.equalsIgnoreCase("quantum dot")) {
particle = (QuantumDotBean) theForm.get("quantumDot");
} else if (particleType.equalsIgnoreCase("metal particle")) {
particle = (MetalParticleBean) theForm.get("metal particle");
}
AddParticlePropertiesService service = new AddParticlePropertiesService();
service.addParticleProperties(particleType, particle);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.addParticleProperties");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.findForward("success");
return forward;
}
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleType = (String) theForm.get("particleType");
theForm.set("particlePage", mapping.findForward(
particleType.toLowerCase()).getPath());
return mapping.getInputForward();
}
public boolean loginRequired() {
return true;
}
}
|
updated dendrimer with surfaceGroup info
SVN-Revision: 8320
|
src/gov/nih/nci/calab/ui/submit/AddParticlePropertiesAction.java
|
updated dendrimer with surfaceGroup info
|
<ide><path>rc/gov/nih/nci/calab/ui/submit/AddParticlePropertiesAction.java
<ide> * @author pansu
<ide> */
<ide>
<del>/* CVS $Id: AddParticlePropertiesAction.java,v 1.5 2006-08-14 13:48:52 zengje Exp $ */
<add>/* CVS $Id: AddParticlePropertiesAction.java,v 1.6 2006-08-14 17:59:23 pansu Exp $ */
<ide>
<ide> import gov.nih.nci.calab.dto.particle.BuckeyballBean;
<ide> import gov.nih.nci.calab.dto.particle.DendrimerBean;
<ide> import gov.nih.nci.calab.dto.particle.ParticleBean;
<ide> import gov.nih.nci.calab.dto.particle.PolymerBean;
<ide> import gov.nih.nci.calab.dto.particle.QuantumDotBean;
<add>import gov.nih.nci.calab.dto.particle.SurfaceGroupBean;
<ide> import gov.nih.nci.calab.service.submit.AddParticlePropertiesService;
<ide> import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
<add>import gov.nih.nci.calab.ui.core.InitSessionSetup;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<add>import javax.servlet.http.HttpSession;
<ide>
<ide> import org.apache.struts.action.ActionForm;
<ide> import org.apache.struts.action.ActionForward;
<ide> particle = (PolymerBean) theForm.get("polymer");
<ide> } else if (particleType.equalsIgnoreCase("liposome")) {
<ide> particle = (LiposomeBean) theForm.get("liposome");
<del> } else if (particleType.equalsIgnoreCase("buckeyball")) {
<add> } else if (particleType.equalsIgnoreCase("buckeyball")) {
<ide> particle = (BuckeyballBean) theForm.get("buckyball");
<del> } else if (particleType.equalsIgnoreCase("fullerene")) {
<add> } else if (particleType.equalsIgnoreCase("fullerene")) {
<ide> particle = (FullereneBean) theForm.get("fullerene");
<del> } else if (particleType.equalsIgnoreCase("quantum dot")) {
<add> } else if (particleType.equalsIgnoreCase("quantum dot")) {
<ide> particle = (QuantumDotBean) theForm.get("quantumDot");
<ide> } else if (particleType.equalsIgnoreCase("metal particle")) {
<del> particle = (MetalParticleBean) theForm.get("metal particle");
<add> particle = (MetalParticleBean) theForm.get("metalParticle");
<ide> }
<ide> AddParticlePropertiesService service = new AddParticlePropertiesService();
<ide> service.addParticleProperties(particleType, particle);
<ide> throws Exception {
<ide> DynaValidatorForm theForm = (DynaValidatorForm) form;
<ide> String particleType = (String) theForm.get("particleType");
<add> HttpSession session=request.getSession();
<add> if (particleType.equalsIgnoreCase("dendrimer")) {
<add> InitSessionSetup.getInstance().setAllDendrimerCores(session);
<add> InitSessionSetup.getInstance().setAllDendrimerSurfaceGroupNames(session);
<add> }
<ide> theForm.set("particlePage", mapping.findForward(
<ide> particleType.toLowerCase()).getPath());
<ide> return mapping.getInputForward();
<add> }
<add>
<add> public ActionForward update(ActionMapping mapping, ActionForm form,
<add> HttpServletRequest request, HttpServletResponse response)
<add> throws Exception {
<add> DynaValidatorForm theForm = (DynaValidatorForm) form;
<add> String particleType = (String) theForm.get("particleType");
<add>
<add> // update surface group info for dendrimers
<add> if (particleType.equalsIgnoreCase("dendrimer")) {
<add> DendrimerBean particle = (DendrimerBean) theForm.get("dendrimer");
<add> updateSurfaceGroups(particle);
<add> theForm.set("dendrimer", particle);
<add> theForm.set("particlePage", mapping.findForward(
<add> particleType.toLowerCase()).getPath());
<add> }
<add> return mapping.getInputForward();
<add> }
<add>
<add> private void updateSurfaceGroups(DendrimerBean particle) {
<add> String numberOfSurfaceGroups = particle.getNumberOfSurfaceGroups();
<add> int surfaceGroupNum = Integer.parseInt(numberOfSurfaceGroups);
<add> List<SurfaceGroupBean> origSurfaceGroups = particle.getSurfaceGroups();
<add> int origNum = (origSurfaceGroups == null) ? 0 : origSurfaceGroups
<add> .size();
<add> List<SurfaceGroupBean> surfaceGroups = new ArrayList<SurfaceGroupBean>();
<add> // create new ones
<add> if (origNum == 0) {
<add>
<add> for (int i = 0; i < surfaceGroupNum; i++) {
<add> SurfaceGroupBean surfaceGroup = new SurfaceGroupBean();
<add> surfaceGroups.add(surfaceGroup);
<add> }
<add> }
<add> // use keep original surface group info
<add> else if (surfaceGroupNum <= origNum) {
<add> for (int i = 0; i < surfaceGroupNum; i++) {
<add> surfaceGroups.add((SurfaceGroupBean) origSurfaceGroups.get(i));
<add> }
<add> } else {
<add> for (int i = 0; i < origNum; i++) {
<add> surfaceGroups.add((SurfaceGroupBean) origSurfaceGroups.get(i));
<add> }
<add> for (int i = origNum; i < surfaceGroupNum; i++) {
<add> surfaceGroups.add(new SurfaceGroupBean());
<add> }
<add> }
<add> particle.setSurfaceGroups(surfaceGroups);
<ide> }
<ide>
<ide> public boolean loginRequired() {
|
|
Java
|
apache-2.0
|
e4c341c8e8da59321c1a4ef2d6c691e523d15805
| 0 |
misterflud/aoleynikov,misterflud/aoleynikov,misterflud/aoleynikov
|
package ru.generator;
import ru.generator.Parsers.TsvPars;
import ru.generator.Parsers.XmlParameters;
import ru.generator.out.WriteInFile;
/**
* Created by Anton on 11.07.2017.
*
*/
public class Generator {
/**
* Start.
* @param args paths
*/
public static void main(String[] args) {
Generator generator = new Generator();
generator.start(args[0], args[1], args[2]);
}
/**
* Start Generator.
* @param path1 xml file
* @param path2 tsv file
* @param path3 txt file
*/
public void start(String path1, String path2, String path3) {
try (WriteInFile writeInFile = new WriteInFile(path3)) {
XmlParameters xmlParameters = new XmlParameters(path1);
TsvPars tsvPars = new TsvPars(path2);
FormatterRow formatterRow = new FormatterRow(xmlParameters);
final String[] top = {"Номер", "Дата", "ФИО"};
final Row rowTop = formatterRow.formatter(top);
FormatterTable formatterTable = new FormatterTable(xmlParameters, rowTop, writeInFile);
while (tsvPars.hasLine()) {
formatterTable.addRow(formatterRow.formatter(tsvPars.getDataNext()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
tasks/texuna/src/main/java/ru/generator/Generator.java
|
package ru.generator;
import ru.generator.Parsers.TsvPars;
import ru.generator.Parsers.XmlParameters;
import ru.generator.out.WriteInFile;
/**
* Created by Anton on 11.07.2017.
*
*/
public class Generator {
/**
* Start.
* @param args paths
*/
public static void main(String[] args) {
Generator generator = new Generator();
//generator.start("C:\\java\\testsTask\\1\\settings.xml", "C:\\java\\testsTask\\1\\source-data.tsv", "C:\\java\\testsTask\\1\\out.txt");
generator.start(args[0], args[1], args[2]);
}
/**
* Start Generator.
* @param path1 xml file
* @param path2 tsv file
* @param path3 txt file
*/
public void start(String path1, String path2, String path3) {
try (WriteInFile writeInFile = new WriteInFile(path3)) {
XmlParameters xmlParameters = new XmlParameters(path1);
TsvPars tsvPars = new TsvPars(path2);
FormatterRow formatterRow = new FormatterRow(xmlParameters);
final String[] top = {"Номер", "Дата", "ФИО"};
final Row rowTop = formatterRow.formatter(top);
FormatterTable formatterTable = new FormatterTable(xmlParameters, rowTop, writeInFile);
while (tsvPars.hasLine()) {
formatterTable.addRow(formatterRow.formatter(tsvPars.getDataNext()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
update
|
tasks/texuna/src/main/java/ru/generator/Generator.java
|
update
|
<ide><path>asks/texuna/src/main/java/ru/generator/Generator.java
<ide> */
<ide> public static void main(String[] args) {
<ide> Generator generator = new Generator();
<del> //generator.start("C:\\java\\testsTask\\1\\settings.xml", "C:\\java\\testsTask\\1\\source-data.tsv", "C:\\java\\testsTask\\1\\out.txt");
<ide> generator.start(args[0], args[1], args[2]);
<ide> }
<ide>
|
|
Java
|
apache-2.0
|
9905fb4f7ac93efe0a5706da7cfd5d473a7bb6f2
| 0 |
jboss-switchyard/switchyard,bfitzpat/switchyard,cunningt/switchyard,bfitzpat/switchyard,tadayosi/switchyard,tadayosi/switchyard,igarashitm/switchyard,igarashitm/switchyard,cunningt/switchyard,jboss-switchyard/switchyard,bfitzpat/switchyard,igarashitm/switchyard,igarashitm/switchyard,tadayosi/switchyard,jboss-switchyard/switchyard,cunningt/switchyard
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.switchyard.test.quickstarts;
import java.io.IOException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.test.ArquillianUtil;
import org.switchyard.test.mixins.HornetQMixIn;
import org.switchyard.test.quickstarts.util.ResourceDeployer;
@RunWith(Arquillian.class)
public class JCAInflowHornetQQuickstartTest {
private static final String QUEUE = "JCAInflowGreetingServiceQueue";
private static final String USER = "guest";
private static final String PASSWD = "guestp";
@Deployment(testable = false)
public static JavaArchive createDeployment() throws IOException {
ResourceDeployer.addQueue(QUEUE);
ResourceDeployer.addPropertiesUser(USER, PASSWD);
return ArquillianUtil.createJarQSDeployment("switchyard-quickstart-jca-inflow-hornetq");
}
@Test
public void testDeployment() throws Exception {
HornetQMixIn hqMixIn = new HornetQMixIn(false)
.setUser(USER)
.setPassword(PASSWD);
hqMixIn.initialize();
try {
Session session = hqMixIn.getJMSSession();
MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE));
TextMessage message = session.createTextMessage();
message.setText(PAYLOAD);
producer.send(message);
Thread.sleep(1000);
} finally {
hqMixIn.uninitialize();
ResourceDeployer.removeQueue(QUEUE);
}
}
private static final String PAYLOAD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<qs:person xmlns:qs=\"urn:switchyard-quickstart:jca-inflow-hornetq:0.1.0\">\n"
+ " <name>Fernando</name>\n"
+ " <language>spanish</language>\n"
+ "</qs:person>\n";
}
|
jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAInflowHornetQQuickstartTest.java
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.switchyard.test.quickstarts;
import java.io.IOException;
import javax.jms.BytesMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.test.ArquillianUtil;
import org.switchyard.test.mixins.HornetQMixIn;
import org.switchyard.test.quickstarts.util.ResourceDeployer;
@RunWith(Arquillian.class)
public class JCAInflowHornetQQuickstartTest {
private static final String QUEUE = "GreetingServiceQueue";
private static final String USER = "guest";
private static final String PASSWD = "guestp";
@Deployment(testable = false)
public static JavaArchive createDeployment() throws IOException {
ResourceDeployer.addQueue(QUEUE);
ResourceDeployer.addPropertiesUser(USER, PASSWD);
return ArquillianUtil.createJarQSDeployment("switchyard-quickstart-jca-inflow-hornetq");
}
@Test
public void testDeployment() throws Exception {
HornetQMixIn hqMixIn = new HornetQMixIn(false)
.setUser(USER)
.setPassword(PASSWD);
hqMixIn.initialize();
try {
Session session = hqMixIn.getJMSSession();
MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE));
BytesMessage message = session.createBytesMessage();
message.writeBytes("Awoniyoshi".getBytes());
producer.send(message);
Thread.sleep(1000);
} finally {
hqMixIn.uninitialize();
ResourceDeployer.removeQueue(QUEUE);
}
}
}
|
SWITCHYARD-1089 Add quickstart which demonstrates dynamic OperationSelector(XPath, Regex, Java)
Added operationSelector.xpath to jca-inflow-hornetq quickstart
|
jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAInflowHornetQQuickstartTest.java
|
SWITCHYARD-1089 Add quickstart which demonstrates dynamic OperationSelector(XPath, Regex, Java)
|
<ide><path>boss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAInflowHornetQQuickstartTest.java
<ide>
<ide> import java.io.IOException;
<ide>
<del>import javax.jms.BytesMessage;
<ide> import javax.jms.MessageProducer;
<ide> import javax.jms.Session;
<add>import javax.jms.TextMessage;
<ide>
<ide> import org.jboss.arquillian.container.test.api.Deployment;
<ide> import org.jboss.arquillian.junit.Arquillian;
<ide> @RunWith(Arquillian.class)
<ide> public class JCAInflowHornetQQuickstartTest {
<ide>
<del> private static final String QUEUE = "GreetingServiceQueue";
<add> private static final String QUEUE = "JCAInflowGreetingServiceQueue";
<ide> private static final String USER = "guest";
<ide> private static final String PASSWD = "guestp";
<ide>
<ide> try {
<ide> Session session = hqMixIn.getJMSSession();
<ide> MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE));
<del> BytesMessage message = session.createBytesMessage();
<del> message.writeBytes("Awoniyoshi".getBytes());
<add> TextMessage message = session.createTextMessage();
<add> message.setText(PAYLOAD);
<ide> producer.send(message);
<ide> Thread.sleep(1000);
<ide> } finally {
<ide> }
<ide> }
<ide>
<add> private static final String PAYLOAD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
<add> + "<qs:person xmlns:qs=\"urn:switchyard-quickstart:jca-inflow-hornetq:0.1.0\">\n"
<add> + " <name>Fernando</name>\n"
<add> + " <language>spanish</language>\n"
<add> + "</qs:person>\n";
<add>
<ide> }
|
|
JavaScript
|
bsd-3-clause
|
ef699a7a649c759da2dedfb1023f74f5d6f54f92
| 0 |
mozilla/galaxy
|
define('views/feature',
['l10n', 'log', 'notification', 'templates', 'requests', 'urls', 'z'],
function(l10n, log, notification, nunjucks, requests, urls, z) {
var gettext = l10n.gettext;
function controlSpinner($button, addSpinner, newText) {
var $textSpan = $button.children('span');
if (addSpinner) {
$textSpan.hide();
$button.append('<div class="spinner btn-replace"></div>');
} else {
$textSpan.text(newText ? newText : $textSpan.text());
$textSpan.show();
$button.children('.spinner').remove();
}
}
// Send request to featured endpoint to unfeature.
function unfeatureGame() {
var $this = $(this);
var gameSlug = $this.parent().data('slug');
controlSpinner($this, true);
requests.del(urls.api.url('game.featured', [], {
game: gameSlug
})).done(function(data) {
notification.notification({message: gettext('Game unfeatured')});
removeGameRow(gameSlug);
}).fail(function() {
notification.notification({message: gettext('Error: A problem occured while unfeaturing this game. Please try again.')});
controlSpinner($this, false);
});
}
// TODO: Hook up with curation modal (#126).
function featureGame(gameSlug) {
return requests.post(urls.api.url('game.featured'), {
game: gameSlug
}).then(function(data) {
notification.notification({message: gettext('Game featured')});
}, function(data) {
notification.notification({message: gettext('Error: A problem occured while featuring this game. Please try again.')});
console.error(data);
}).promise();
}
// Send request to moderate endpoint for deletion.
function deleteGame() {
var $this = $(this);
var gameSlug = $this.parent().data('slug');
controlSpinner($this, true);
notification.confirmation({message: gettext('Are you sure you want to delete this game?')}).done(function() {
requests.post(urls.api.url('game.moderate', [gameSlug, 'delete'])).done(function(data) {
notification.notification({message: gettext('Game deleted')});
removeGameRow(gameSlug);
}).fail(function() {
notification.notification({message: gettext('Error: A problem occured while deleting this game. Please try again.')});
controlSpinner($this, false);
});
}).fail(function() {
// Add back text.
controlSpinner($this, false);
});
}
// Send request to moderate endpoint.
function moderateGame($this, action) {
var gameSlug = $this.parent().data('slug');
controlSpinner($this, true);
requests.post(urls.api.url('game.moderate', [gameSlug, action])).done(function(data) {
notification.notification({message: gettext('Game status successfully changed')});
if (action === 'disable') {
var $statusSpan = $('.game-status[data-slug='+ gameSlug +']');
var previousStatus = $statusSpan.text().toLowerCase();
// Change status to disabled.
$statusSpan.text(gettext('Disabled')).removeClass('status-' + previousStatus).addClass('status-disabled');
// Change button.
$this.removeClass('curation-disable btn-disable').addClass('btn-enable curation-enable');
controlSpinner($this, false, gettext('Enable'));
} else if (action === 'approve') {
var $statusSpan = $('.game-status[data-slug='+ gameSlug +']');
var previousStatus = $statusSpan.text().toLowerCase();
// Change status to enabled.
$statusSpan.text('Public').removeClass('status-'+ previousStatus).addClass('status-approved');
// Change button.
$this.removeClass('curation-enable btn-enable').addClass('btn-disable curation-disable');
controlSpinner($this, false, gettext('Disable'));
}
}).fail(function() {
notification.notification({message: gettext('Error: A problem occured while changing the game status. Please try again.')});
controlSpinner($this, false);
});
}
// Remove table representing game with specified slug.
function removeGameRow(slug) {
var $row = $('tr[data-slug=' + slug + ']');
$row.remove();
// If no more games, hide table and show message.
if (!$('.curation-table tr').length) {
$('#empty-message').show();
$('.curation-table').hide();
}
}
function addGameRow(slug) {
// Get Game Details
// TODO: Maybe modify /featured endpoint to return newly featured game's game object so as to not make two requests
requests.get(urls.api.url('game', [slug]))
.done(function(gameData) {
var rowToAdd = nunjucks.env.render('admin/_curation-row.html', {game: gameData});
$('.curation-table tbody').append(rowToAdd);
$('.curation-table').show();
$('#empty-message').hide();
});
}
function showSearchResults(games) {
$('.game-results').html(
nunjucks.env.render('admin/game-results.html', {games: games})
);
}
z.body.on('click', '.curation-unfeature', unfeatureGame)
.on('click', '.curation-delete', deleteGame)
.on('click', '.curation-disable', function() {
moderateGame($(this), 'disable');
}).on('click', '.curation-enable', function() {
moderateGame($(this), 'approve');
}).on('click', '.curation-feature', function() {
$('.modal').addClass('show');
$(this).addClass('show');
z.body.trigger('decloak');
}).on('mouseover', '.game-results li', function() {
var $button = $(this).children('.feature-btn');
$button.addClass('show');
}).on('mouseout', '.game-results li', function() {
var $button = $(this).children('.feature-btn');
$button.removeClass('show');
}).on('change keyup', 'input[name=game-search]', function(e) {
// TODO: hook this up with local game searching index
}).on('click', '.feature-btn', function() {
var $this = $(this);
var $game = $this.closest('li');
var gameSlug = $game.data('gameSlug');
featureGame(gameSlug).then(function() {
z.body.trigger('cloak');
addGameRow(gameSlug);
}, function() {});
});
return function(builder, args) {
builder.start('admin/feature.html');
builder.z('type', 'leaf curation');
builder.z('title', gettext('Curation Dashboard'));
builder.onload('featured-games', function(data) {
data.forEach(function(game) {
var rowToAdd = nunjucks.env.render('admin/_curation-row.html', {game: game});
$('.curation-table tbody').append(rowToAdd);
});
});
};
});
|
src/media/js/views/feature.js
|
define('views/feature',
['l10n', 'log', 'notification', 'templates', 'requests', 'urls', 'z'],
function(l10n, log, notification, nunjucks, requests, urls, z) {
var gettext = l10n.gettext;
function controlSpinner($button, addSpinner, newText) {
var $textSpan = $button.children('span');
if (addSpinner) {
$textSpan.hide();
$button.append('<div class="spinner btn-replace"></div>');
} else {
$textSpan.text(newText ? newText : $textSpan.text());
$textSpan.show();
$button.children('.spinner').remove();
}
}
// Send request to featured endpoint to unfeature.
function unfeatureGame() {
var $this = $(this);
var gameSlug = $this.parent().data('slug');
controlSpinner($this, true);
requests.del(urls.api.url('game.featured', [], {
game: gameSlug
})).done(function(data) {
notification.notification({message: gettext('Game unfeatured')});
removeGameRow(gameSlug);
}).fail(function() {
notification.notification({message: gettext('Error: A problem occured while unfeaturing this game. Please try again.')});
controlSpinner($this, false);
});
}
// TODO: Hook up with curation modal (#126).
function featureGame(gameSlug) {
return requests.post(urls.api.url('game.featured'), {
game: gameSlug
}).then(function(data) {
notification.notification({message: gettext('Game featured')});
}, function(data) {
notification.notification({message: gettext('Error: A problem occured while featuring this game. Please try again.')});
console.error(data);
}).promise();
}
// Send request to moderate endpoint for deletion.
function deleteGame() {
var $this = $(this);
var gameSlug = $this.parent().data('slug');
controlSpinner($this, true);
notification.confirmation({message: gettext('Are you sure you want to delete this game?')}).done(function() {
requests.post(urls.api.url('game.moderate', [gameSlug, 'delete'])).done(function(data) {
notification.notification({message: gettext('Game deleted')});
removeGameRow(gameSlug);
}).fail(function() {
notification.notification({message: gettext('Error: A problem occured while deleting this game. Please try again.')});
controlSpinner($this, false);
});
}).fail(function() {
// Add back text.
controlSpinner($this, false);
});
}
// Send request to moderate endpoint.
function moderateGame($this, action) {
var gameSlug = $this.parent().data('slug');
controlSpinner($this, true);
requests.post(urls.api.url('game.moderate', [gameSlug, action])).done(function(data) {
notification.notification({message: gettext('Game status successfully changed')});
if (action === 'disable') {
var $statusSpan = $('.game-status[data-slug='+ gameSlug +']');
var previousStatus = $statusSpan.text().toLowerCase();
// Change status to disabled.
$statusSpan.text(gettext('Disabled')).removeClass('status-' + previousStatus).addClass('status-disabled');
// Change button.
$this.removeClass('curation-disable btn-disable').addClass('btn-enable curation-enable');
controlSpinner($this, false, gettext('Enable'));
} else if (action === 'approve') {
var $statusSpan = $('.game-status[data-slug='+ gameSlug +']');
var previousStatus = $statusSpan.text().toLowerCase();
// Change status to enabled.
$statusSpan.text('Public').removeClass('status-'+ previousStatus).addClass('status-approved');
// Change button.
$this.removeClass('curation-enable btn-enable').addClass('btn-disable curation-disable');
controlSpinner($this, false, gettext('Disable'));
}
}).fail(function() {
notification.notification({message: gettext('Error: A problem occured while changing the game status. Please try again.')});
controlSpinner($this, false);
});
}
// Remove table representing game with specified slug.
function removeGameRow(slug) {
var $row = $('tr[data-slug=' + slug + ']');
$row.remove();
// If no more games, hide table and show message.
if (!$('.curation-table tr').length) {
$('#empty-message').show();
$('.curation-table').hide();
}
}
function addGameRow(slug) {
// Get Game Details
// TODO: Maybe modify /featured endpoint to return newly featured game's game object so as to not make two requests
requests.get(urls.api.url('game', [slug]))
.done(function(gameData) {
var rowToAdd = nunjucks.env.render('admin/_curation-row.html', {game: gameData});
$('.curation-table tbody').append(rowToAdd);
$('.curation-table').show();
$('#empty-message').hide();
});
}
function showSearchResults(games) {
$('.game-results').html(
nunjucks.env.render('admin/game-results.html', {games: games})
);
}
z.body.on('click', '.curation-unfeature', unfeatureGame)
.on('click', '.curation-delete', deleteGame)
.on('click', '.curation-disable', function() {
moderateGame($(this), 'disable');
}).on('click', '.curation-enable', function() {
moderateGame($(this), 'approve');
}).on('click', '.curation-feature', function() {
$('.modal').addClass('show');
$(this).addClass('show');
z.body.trigger('decloak');
}).on('mouseover', '.game-results li', function() {
var $button = $(this).children('.feature-btn');
$button.addClass('show');
}).on('mouseout', '.game-results li', function() {
var $button = $(this).children('.feature-btn');
$button.removeClass('show');
}).on('change keyup', 'input[name=game-search]', function(e) {
// TODO: hook this up with local game searching index
setTimeout(function() {
requests.get(urls.api.url('game.list')).done(function(data) {
if (data.error) {
$('.game-results').html('');
return;
}
showSearchResults(data);
}).fail(function() {
$('.game-results').html('');
});
}, 500);
}).on('click', '.feature-btn', function() {
var $this = $(this);
var $game = $this.closest('li');
var gameSlug = $game.data('gameSlug');
featureGame(gameSlug).then(function() {
z.body.trigger('cloak');
addGameRow(gameSlug);
}, function() {});
});
return function(builder, args) {
builder.start('admin/feature.html');
builder.z('type', 'leaf curation');
builder.z('title', gettext('Curation Dashboard'));
builder.onload('featured-games', function(data) {
data.forEach(function(game) {
var rowToAdd = nunjucks.env.render('admin/_curation-row.html', {game: game});
$('.curation-table tbody').append(rowToAdd);
});
});
};
});
|
remove testing code
|
src/media/js/views/feature.js
|
remove testing code
|
<ide><path>rc/media/js/views/feature.js
<ide> $button.removeClass('show');
<ide> }).on('change keyup', 'input[name=game-search]', function(e) {
<ide> // TODO: hook this up with local game searching index
<del> setTimeout(function() {
<del> requests.get(urls.api.url('game.list')).done(function(data) {
<del> if (data.error) {
<del> $('.game-results').html('');
<del> return;
<del> }
<del> showSearchResults(data);
<del> }).fail(function() {
<del> $('.game-results').html('');
<del> });
<del> }, 500);
<ide> }).on('click', '.feature-btn', function() {
<ide> var $this = $(this);
<ide> var $game = $this.closest('li');
|
|
Java
|
apache-2.0
|
beaf90877a9456eaab3311396cb9ed904c4b412f
| 0 |
sedulam/CASSANDRA-12201,sedulam/CASSANDRA-12201,sedulam/CASSANDRA-12201
|
/*
* 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.cassandra.db.compaction;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.partitions.Partition;
import org.apache.cassandra.exceptions.CompactionException;
import org.apache.cassandra.exceptions.ExceptionCode;
import org.apache.cassandra.io.sstable.KeyIterator;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.utils.Pair;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import static com.google.common.collect.Iterables.filter;
/**
* This strategy tries to take advantage of periods of the day where there's less I/O.
* Full description can be found at CASSANDRA-12201.
*/
//
public class BurstHourCompactionStrategy extends AbstractCompactionStrategy
{
private volatile int estimatedRemainingTasks;
private int referenced_sstable_limit = 3;
//TODO do we really need this variable?
private final Set<SSTableReader> sstables = new HashSet<>();
//TODO add logging
private static final Logger logger = LoggerFactory.getLogger(BurstHourCompactionStrategy.class);
public BurstHourCompactionStrategy(ColumnFamilyStore cfs, Map<String, String> options)
{
super(cfs, options);
estimatedRemainingTasks = 0;
}
private Map<DecoratedKey, Pair<String, Set<SSTableReader>>> getAllKeyReferences()
{
Iterable<SSTableReader> candidates = filterSuspectSSTables(cfs.getUncompactingSSTables());
// Get all the keys and the corresponding SSTables in which they exist
Map<DecoratedKey, Pair<String, Set<SSTableReader>>> keyToTablesMap = new HashMap<>();
for(SSTableReader ssTable : candidates){
try(KeyIterator keyIterator = new KeyIterator(ssTable.descriptor, cfs.metadata))
{
while (keyIterator.hasNext())
{
DecoratedKey partitionKey = keyIterator.next();
Pair<String, Set<SSTableReader>> references;
Set<SSTableReader> ssTablesWithThisKey;
if (keyToTablesMap.containsKey(partitionKey))
{
references = keyToTablesMap.get(partitionKey);
ssTablesWithThisKey = references.right;
}
else
{
ssTablesWithThisKey = new HashSet<>();
references = Pair.create(ssTable.getColumnFamilyName(), ssTablesWithThisKey);
keyToTablesMap.put(partitionKey, references);
}
if (ssTablesWithThisKey != null)
{
ssTablesWithThisKey.add(ssTable);
}
else
{
throw new CompactionException(ExceptionCode.SERVER_ERROR, "SSTables reference set cannot be null at this point");
}
}
}
}
return keyToTablesMap;
}
/**
* Filter out the keys that are in less than referenced_sstable_limit SSTables
* @return map with SSTables that share the same partition key more than referenced_sstable_limit amount
*/
private Map<String, Set<SSTableReader>> removeColdBuckets(Map<DecoratedKey, Pair<String, Set<SSTableReader>>> allReferences)
{
Map<String, Set<SSTableReader>> keyCountAboveThreshold = new HashMap<>();
for(Map.Entry<DecoratedKey, Pair<String, Set<SSTableReader>>> entry : allReferences.entrySet())
{
Pair<String, Set<SSTableReader>> keyReferences = entry.getValue();
if (keyReferences.right.size() >= referenced_sstable_limit)
{
String tableName = keyReferences.left;
if (keyCountAboveThreshold.containsKey(tableName))
{
// Because we're using a set, duplicates won't be an issue
keyCountAboveThreshold.get(tableName).addAll(keyReferences.right);
}
else
{
Set<SSTableReader> ssTablesSet = new HashSet<>();
ssTablesSet.addAll(keyReferences.right);
keyCountAboveThreshold.put(tableName, ssTablesSet);
}
}
}
return keyCountAboveThreshold;
}
private Set<SSTableReader> selectHottestBucket(Map<String, Set<SSTableReader>> allBuckets)
{
long maxReferences = 0;
Set<SSTableReader> hottestSet = null;
for(Set<SSTableReader> set: allBuckets.values())
{
long setReferences = set.size();
if (setReferences > maxReferences)
{
maxReferences = setReferences;
hottestSet = set;
}
}
return hottestSet;
}
private Set<SSTableReader> gatherSSTablesToCompact(){
Map<DecoratedKey, Pair<String, Set<SSTableReader>>> allReferences = getAllKeyReferences();
Map<String, Set<SSTableReader>> hotBuckets = removeColdBuckets(allReferences);
estimatedRemainingTasks = hotBuckets.size();
return selectHottestBucket(hotBuckets);
}
/**
* @param gcBefore throw away tombstones older than this
* @return the next background/minor compaction task to run; null if nothing to do.
* <p>
* TODO does the following line still applies? If not, change the superclass doc. Repeat for other methods.
* Is responsible for marking its sstables as compaction-pending.
*/
public AbstractCompactionTask getNextBackgroundTask(int gcBefore)
{
Set<SSTableReader> ssTablesToCompact = gatherSSTablesToCompact();
return createBhcsCompactionTask(ssTablesToCompact, gcBefore);
}
/**
* Creates the compaction task object.
* @param tables the tables we want to compact
* @param gcBefore throw away tombstones older than this
* @return a compaction task object which will be later used to run the compaction per se
*/
private AbstractCompactionTask createBhcsCompactionTask(Set<SSTableReader> tables, int gcBefore)
{
if (tables.size() == 0){
return null;
}
else {
LifecycleTransaction transaction = cfs.getTracker().tryModify(tables, OperationType.COMPACTION);
return new CompactionTask(cfs, transaction, gcBefore);
}
}
/**
* @param gcBefore throw away tombstones older than this
* @param splitOutput it's not relevant for this strategy because the strategy whole purpose to is always get a compaction as big as possible
* @return a compaction task that should be run to compact this columnfamilystore
* as much as possible. Null if nothing to do.
* <p>
* Is responsible for marking its sstables as compaction-pending.
*/
public Collection<AbstractCompactionTask> getMaximalTask(int gcBefore, boolean splitOutput)
{
Map<DecoratedKey, Pair<String, Set<SSTableReader>>> keyReferences = getAllKeyReferences();
Map<String, Set<SSTableReader>> hotBuckets = removeColdBuckets(keyReferences);
Set<AbstractCompactionTask> allTasks = new HashSet<>();
for(Set<SSTableReader> ssTables : hotBuckets.values())
{
AbstractCompactionTask task = createBhcsCompactionTask(ssTables, gcBefore);
allTasks.add(task);
}
return allTasks;
}
/**
* @param sstables SSTables to compact. Must be marked as compacting.
* @param gcBefore throw away tombstones older than this
* @return a compaction task corresponding to the requested sstables.
* Will not be null. (Will throw if user requests an invalid compaction.)
* <p>
* Is responsible for marking its sstables as compaction-pending.
*/
public AbstractCompactionTask getUserDefinedTask(Collection<SSTableReader> sstables, int gcBefore)
{
throw new NotImplementedException();
}
/**
* @return the number of background tasks estimated to still be needed for this columnfamilystore
*/
public int getEstimatedRemainingTasks()
{
return estimatedRemainingTasks;
}
/**
* @return size in bytes of the largest sstables for this strategy
*/
public long getMaxSSTableBytes()
{
//TODO why is every strategy, except for LCS, returing this value?
return Long.MAX_VALUE;
}
public void addSSTable(SSTableReader added)
{
sstables.add(added);
}
public void removeSSTable(SSTableReader sstable)
{
sstables.remove(sstable);
}
}
|
src/java/org/apache/cassandra/db/compaction/BurstHourCompactionStrategy.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.cassandra.db.compaction;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.partitions.Partition;
import org.apache.cassandra.exceptions.CompactionException;
import org.apache.cassandra.exceptions.ExceptionCode;
import org.apache.cassandra.io.sstable.KeyIterator;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.utils.Pair;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import static com.google.common.collect.Iterables.filter;
/**
* This strategy tries to take advantage of periods of the day where there's less I/O.
* Full description can be found at CASSANDRA-12201.
*/
public class BurstHourCompactionStrategy extends AbstractCompactionStrategy
{
private volatile int estimatedRemainingTasks;
private int referenced_sstable_limit = 3;
private final Set<SSTableReader> sstables = new HashSet<>();
private static final Logger logger = LoggerFactory.getLogger(BurstHourCompactionStrategy.class);
public BurstHourCompactionStrategy(ColumnFamilyStore cfs, Map<String, String> options)
{
super(cfs, options);
estimatedRemainingTasks = 0;
}
private Map<DecoratedKey, Pair<String, Set<SSTableReader>>> getAllKeyReferences()
{
Iterable<SSTableReader> candidates = filterSuspectSSTables(cfs.getUncompactingSSTables());
// Get all the keys and the corresponding SSTables in which they exist
Map<DecoratedKey, Pair<String, Set<SSTableReader>>> keyToTablesMap = new HashMap<>();
for(SSTableReader ssTable : candidates){
try(KeyIterator keyIterator = new KeyIterator(ssTable.descriptor, cfs.metadata))
{
while (keyIterator.hasNext())
{
DecoratedKey partitionKey = keyIterator.next();
Pair<String, Set<SSTableReader>> references;
Set<SSTableReader> ssTablesWithThisKey;
if (keyToTablesMap.containsKey(partitionKey))
{
references = keyToTablesMap.get(partitionKey);
ssTablesWithThisKey = references.right;
}
else
{
ssTablesWithThisKey = new HashSet<>();
references = Pair.create(ssTable.getColumnFamilyName(), ssTablesWithThisKey);
keyToTablesMap.put(partitionKey, references);
}
if (ssTablesWithThisKey != null)
{
ssTablesWithThisKey.add(ssTable);
}
else
{
throw new CompactionException(ExceptionCode.SERVER_ERROR, "SSTables reference set cannot be null at this point");
}
}
}
}
return keyToTablesMap;
}
/**
* Filter out the keys that are in less than referenced_sstable_limit SSTables
* @return map with SSTables that share the same partition key more than referenced_sstable_limit amount
*/
private Map<String, Set<SSTableReader>> removeColdBuckets(Map<DecoratedKey, Pair<String, Set<SSTableReader>>> allReferences)
{
Map<String, Set<SSTableReader>> keyCountAboveThreshold = new HashMap<>();
for(Map.Entry<DecoratedKey, Pair<String, Set<SSTableReader>>> entry : allReferences.entrySet())
{
Pair<String, Set<SSTableReader>> keyReferences = entry.getValue();
if (keyReferences.right.size() >= referenced_sstable_limit)
{
String tableName = keyReferences.left;
if (keyCountAboveThreshold.containsKey(tableName))
{
// Because we're using a set, duplicates won't be an issue
keyCountAboveThreshold.get(tableName).addAll(keyReferences.right);
}
else
{
Set<SSTableReader> ssTablesSet = new HashSet<>();
ssTablesSet.addAll(keyReferences.right);
keyCountAboveThreshold.put(tableName, ssTablesSet);
}
}
}
return keyCountAboveThreshold;
}
private Set<SSTableReader> selectHottestBucket(Map<String, Set<SSTableReader>> allBuckets)
{
long maxReferences = 0;
Set<SSTableReader> hottestSet = null;
for(Set<SSTableReader> set: allBuckets.values())
{
long setReferences = set.size();
if (setReferences > maxReferences)
{
maxReferences = setReferences;
hottestSet = set;
}
}
return hottestSet;
}
private Set<SSTableReader> gatherSSTablesToCompact(){
Map<DecoratedKey, Pair<String, Set<SSTableReader>>> allReferences = getAllKeyReferences();
Map<String, Set<SSTableReader>> hotBuckets = removeColdBuckets(allReferences);
estimatedRemainingTasks = hotBuckets.size();
return selectHottestBucket(hotBuckets);
}
/**
* @param gcBefore throw away tombstones older than this
* @return the next background/minor compaction task to run; null if nothing to do.
* <p>
* TODO does the following line still applies? If not, change the superclass doc
* Is responsible for marking its sstables as compaction-pending.
*/
public AbstractCompactionTask getNextBackgroundTask(int gcBefore)
{
Set<SSTableReader> ssTablesToCompact = gatherSSTablesToCompact();
if (ssTablesToCompact.size() == 0){
return null;
}
else {
LifecycleTransaction transaction = cfs.getTracker().tryModify(ssTablesToCompact, OperationType.COMPACTION);
return new CompactionTask(cfs, transaction, gcBefore);
}
}
/**
* @param gcBefore throw away tombstones older than this
* @param splitOutput it's not relevant for this strategy
* @return a compaction task that should be run to compact this columnfamilystore
* as much as possible. Null if nothing to do.
* <p>
* Is responsible for marking its sstables as compaction-pending.
*/
public Collection<AbstractCompactionTask> getMaximalTask(int gcBefore, boolean splitOutput)
{
throw new NotImplementedException();
}
/**
* @param sstables SSTables to compact. Must be marked as compacting.
* @param gcBefore throw away tombstones older than this
* @return a compaction task corresponding to the requested sstables.
* Will not be null. (Will throw if user requests an invalid compaction.)
* <p>
* Is responsible for marking its sstables as compaction-pending.
*/
public AbstractCompactionTask getUserDefinedTask(Collection<SSTableReader> sstables, int gcBefore)
{
throw new NotImplementedException();
}
/**
* @return the number of background tasks estimated to still be needed for this columnfamilystore
*/
public int getEstimatedRemainingTasks()
{
return estimatedRemainingTasks;
}
/**
* @return size in bytes of the largest sstables for this strategy
*/
public long getMaxSSTableBytes()
{
return Long.MAX_VALUE;
}
public void addSSTable(SSTableReader added)
{
sstables.add(added);
}
public void removeSSTable(SSTableReader sstable)
{
sstables.remove(sstable);
}
}
|
Implemented getMaximalTask for BHCS.
|
src/java/org/apache/cassandra/db/compaction/BurstHourCompactionStrategy.java
|
Implemented getMaximalTask for BHCS.
|
<ide><path>rc/java/org/apache/cassandra/db/compaction/BurstHourCompactionStrategy.java
<ide> * This strategy tries to take advantage of periods of the day where there's less I/O.
<ide> * Full description can be found at CASSANDRA-12201.
<ide> */
<add>//
<ide> public class BurstHourCompactionStrategy extends AbstractCompactionStrategy
<ide> {
<ide> private volatile int estimatedRemainingTasks;
<ide> private int referenced_sstable_limit = 3;
<add> //TODO do we really need this variable?
<ide> private final Set<SSTableReader> sstables = new HashSet<>();
<add> //TODO add logging
<ide> private static final Logger logger = LoggerFactory.getLogger(BurstHourCompactionStrategy.class);
<ide>
<ide> public BurstHourCompactionStrategy(ColumnFamilyStore cfs, Map<String, String> options)
<ide> * @param gcBefore throw away tombstones older than this
<ide> * @return the next background/minor compaction task to run; null if nothing to do.
<ide> * <p>
<del> * TODO does the following line still applies? If not, change the superclass doc
<add> * TODO does the following line still applies? If not, change the superclass doc. Repeat for other methods.
<ide> * Is responsible for marking its sstables as compaction-pending.
<ide> */
<ide> public AbstractCompactionTask getNextBackgroundTask(int gcBefore)
<ide> {
<ide> Set<SSTableReader> ssTablesToCompact = gatherSSTablesToCompact();
<del>
<del> if (ssTablesToCompact.size() == 0){
<add> return createBhcsCompactionTask(ssTablesToCompact, gcBefore);
<add> }
<add>
<add> /**
<add> * Creates the compaction task object.
<add> * @param tables the tables we want to compact
<add> * @param gcBefore throw away tombstones older than this
<add> * @return a compaction task object which will be later used to run the compaction per se
<add> */
<add> private AbstractCompactionTask createBhcsCompactionTask(Set<SSTableReader> tables, int gcBefore)
<add> {
<add> if (tables.size() == 0){
<ide> return null;
<ide> }
<ide> else {
<del> LifecycleTransaction transaction = cfs.getTracker().tryModify(ssTablesToCompact, OperationType.COMPACTION);
<add> LifecycleTransaction transaction = cfs.getTracker().tryModify(tables, OperationType.COMPACTION);
<ide> return new CompactionTask(cfs, transaction, gcBefore);
<ide> }
<ide> }
<ide>
<ide> /**
<ide> * @param gcBefore throw away tombstones older than this
<del> * @param splitOutput it's not relevant for this strategy
<add> * @param splitOutput it's not relevant for this strategy because the strategy whole purpose to is always get a compaction as big as possible
<ide> * @return a compaction task that should be run to compact this columnfamilystore
<ide> * as much as possible. Null if nothing to do.
<ide> * <p>
<ide> */
<ide> public Collection<AbstractCompactionTask> getMaximalTask(int gcBefore, boolean splitOutput)
<ide> {
<del> throw new NotImplementedException();
<add> Map<DecoratedKey, Pair<String, Set<SSTableReader>>> keyReferences = getAllKeyReferences();
<add>
<add> Map<String, Set<SSTableReader>> hotBuckets = removeColdBuckets(keyReferences);
<add>
<add> Set<AbstractCompactionTask> allTasks = new HashSet<>();
<add>
<add> for(Set<SSTableReader> ssTables : hotBuckets.values())
<add> {
<add> AbstractCompactionTask task = createBhcsCompactionTask(ssTables, gcBefore);
<add> allTasks.add(task);
<add> }
<add>
<add> return allTasks;
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public long getMaxSSTableBytes()
<ide> {
<add> //TODO why is every strategy, except for LCS, returing this value?
<ide> return Long.MAX_VALUE;
<ide> }
<ide>
|
|
JavaScript
|
apache-2.0
|
bdfddaf15c9b4ea87815efd1212a77d654f3eebb
| 0 |
masaryk/techradar,ChrisPlease/techradar,bdargan/techradar,masaryk/techradar,twofour/techradar,twofour/techradar,bdargan/techradar
|
function init(h,w) {
$('#title').text(document.title);
var radar = new pv.Panel()
.width(w)
.height(h)
.canvas('radar')
// arcs
radar.add(pv.Dot)
.data(radar_arcs)
.left(w/2)
.bottom(h/2)
.radius(function(d){return d.r;})
.strokeStyle("#ccc")
.anchor("top")
.add(pv.Label).text(function(d) { return d.name;});
//quadrant lines -- vertical
radar.add(pv.Line)
.data([(h/2-radar_arcs[radar_arcs.length-1].r),h-(h/2-radar_arcs[radar_arcs.length-1].r)])
.lineWidth(1)
.left(w/2)
.bottom(function(d) {return d;})
.strokeStyle("#bbb");
//quadrant lines -- horizontal
radar.add(pv.Line)
.data([(w/2-radar_arcs[radar_arcs.length-1].r),w-(w/2-radar_arcs[radar_arcs.length-1].r)])
.lineWidth(1)
.bottom(h/2)
.left(function(d) {return d;})
.strokeStyle("#bbb");
// blips
// var total_index=1;
// for (var i = 0; i < radar_data.length; i++) {
// radar.add(pv.Dot)
// .def("active", false)
// .data(radar_data[i].items)
// .size( function(d) { return ( d.blipSize !== undefined ? d.blipSize : 70 ); })
// .left(function(d) { var x = polar_to_raster(d.pc.r, d.pc.t)[0];
// //console.log("name:" + d.name + ", x:" + x);
// return x;})
// .bottom(function(d) { var y = polar_to_raster(d.pc.r, d.pc.t)[1];
// //console.log("name:" + d.name + ", y:" + y);
// return y;})
// .title(function(d) { return d.name;})
// .cursor( function(d) { return ( d.url !== undefined ? "pointer" : "auto" ); })
// .event("click", function(d) { if ( d.url !== undefined ){self.location = d.url}})
// .angle(Math.PI) // 180 degrees in radians !
// .strokeStyle(radar_data[i].color)
// .fillStyle(radar_data[i].color)
// .shape(function(d) {return (d.movement === 't' ? "triangle" : "circle");})
// .anchor("center")
// .add(pv.Label)
// .text(function(d) {return total_index++;})
// .textBaseline("middle")
// .textStyle("white");
// }
//Quadrant Ledgends
var radar_quadrant_ctr=1;
var quadrantFontSize = 18;
var headingFontSize = 14;
var stageHeadingCount = 0;
var lastRadius = 0;
var lastQuadrant='';
var spacer = 6;
var fontSize = 10;
var total_index = 1;
//TODO: Super fragile: re-order the items, by radius, in order to logically group by the rings.
for (var i = 0; i < radar_data.length; i++) {
//adjust top by the number of headings.
if (lastQuadrant != radar_data[i].quadrant) {
radar.add(pv.Label)
.left( radar_data[i].left )
.top( radar_data[i].top )
.text( radar_data[i].quadrant )
.strokeStyle( radar_data[i].color )
.fillStyle( radar_data[i].color )
.font(quadrantFontSize + "px sans-serif");
lastQuadrant = radar_data[i].quadrant;
}
// group items by stage based on how far they are from each arc
var itemsByStage = _.groupBy(radar_data[i].items, function(item) {
for(var arc_i = 0; arc_i < radar_arcs.length; arc_i++) {
if (item.pc.r < radar_arcs[arc_i].r)
{
return arc_i;
}
}
return 0;
});
var offsetIndex = 0;
for (var stageIdx in _(itemsByStage).keys()) {
if (stageIdx > 0) {
offsetIndex = offsetIndex + itemsByStage[stageIdx-1].length + 1;
console.log("offsetIndex = " + itemsByStage[stageIdx-1].length, offsetIndex );
}
radar.add(pv.Label)
.left( radar_data[i].left + headingFontSize )
.top( radar_data[i].top + quadrantFontSize + spacer + (stageIdx * headingFontSize) + (offsetIndex * fontSize) )
.text( radar_arcs[stageIdx].name)
.strokeStyle( '#cccccc' )
.fillStyle( '#cccccc')
.font(headingFontSize + "px Courier New");
radar.add(pv.Label)
.left( radar_data[i].left )
.top( radar_data[i].top + quadrantFontSize + spacer + (stageIdx * headingFontSize) + (offsetIndex * fontSize) )
.strokeStyle( radar_data[i].color )
.fillStyle( radar_data[i].color )
.add( pv.Dot )
.def("i", radar_data[i].top + quadrantFontSize + spacer + (stageIdx * headingFontSize) + spacer + (offsetIndex * fontSize) )
.data(itemsByStage[stageIdx])
.top( function() { return ( this.i() + (this.index * fontSize) );} )
.shape( function(d) {return (d.movement === 't' ? "triangle" : "circle");})
.cursor( function(d) { return ( d.url !== undefined ? "pointer" : "auto" ); })
.event("click", function(d) { if ( d.url !== undefined ){self.location = d.url}})
.size(fontSize)
.angle(45)
.anchor("right")
.add(pv.Label)
.text(function(d) {return radar_quadrant_ctr++ + ". " + d.name;} );
radar.add(pv.Dot)
.def("active", false)
.data(itemsByStage[stageIdx])
.size( function(d) { return ( d.blipSize !== undefined ? d.blipSize : 70 ); })
.left(function(d) { var x = polar_to_raster(d.pc.r, d.pc.t)[0];
//console.log("name:" + d.name + ", x:" + x);
return x;})
.bottom(function(d) { var y = polar_to_raster(d.pc.r, d.pc.t)[1];
//console.log("name:" + d.name + ", y:" + y);
return y;})
.title(function(d) { return d.name;})
.cursor( function(d) { return ( d.url !== undefined ? "pointer" : "auto" ); })
.event("click", function(d) { if ( d.url !== undefined ){self.location = d.url}})
.angle(Math.PI) // 180 degrees in radians !
.strokeStyle(radar_data[i].color)
.fillStyle(radar_data[i].color)
.shape(function(d) {return (d.movement === 't' ? "triangle" : "circle");})
.anchor("center")
.add(pv.Label)
.text(function(d) {return total_index++;})
.textBaseline("middle")
.textStyle("white");
}
}
radar.anchor('radar');
radar.render();
};
|
radar.js
|
function init(h,w) {
$('#title').text(document.title);
var radar = new pv.Panel()
.width(w)
.height(h)
.canvas('radar')
// arcs
radar.add(pv.Dot)
.data(radar_arcs)
.left(w/2)
.bottom(h/2)
.radius(function(d){return d.r;})
.strokeStyle("#ccc")
.anchor("top")
.add(pv.Label).text(function(d) { return d.name;});
//quadrant lines -- vertical
radar.add(pv.Line)
.data([(h/2-radar_arcs[radar_arcs.length-1].r),h-(h/2-radar_arcs[radar_arcs.length-1].r)])
.lineWidth(1)
.left(w/2)
.bottom(function(d) {return d;})
.strokeStyle("#bbb");
//quadrant lines -- horizontal
radar.add(pv.Line)
.data([(w/2-radar_arcs[radar_arcs.length-1].r),w-(w/2-radar_arcs[radar_arcs.length-1].r)])
.lineWidth(1)
.bottom(h/2)
.left(function(d) {return d;})
.strokeStyle("#bbb");
// blips
// var total_index=1;
// for (var i = 0; i < radar_data.length; i++) {
// radar.add(pv.Dot)
// .def("active", false)
// .data(radar_data[i].items)
// .size( function(d) { return ( d.blipSize !== undefined ? d.blipSize : 70 ); })
// .left(function(d) { var x = polar_to_raster(d.pc.r, d.pc.t)[0];
// //console.log("name:" + d.name + ", x:" + x);
// return x;})
// .bottom(function(d) { var y = polar_to_raster(d.pc.r, d.pc.t)[1];
// //console.log("name:" + d.name + ", y:" + y);
// return y;})
// .title(function(d) { return d.name;})
// .cursor( function(d) { return ( d.url !== undefined ? "pointer" : "auto" ); })
// .event("click", function(d) { if ( d.url !== undefined ){self.location = d.url}})
// .angle(Math.PI) // 180 degrees in radians !
// .strokeStyle(radar_data[i].color)
// .fillStyle(radar_data[i].color)
// .shape(function(d) {return (d.movement === 't' ? "triangle" : "circle");})
// .anchor("center")
// .add(pv.Label)
// .text(function(d) {return total_index++;})
// .textBaseline("middle")
// .textStyle("white");
// }
//Quadrant Ledgends
var radar_quadrant_ctr=1;
var quadrantFontSize = 18;
var headingFontSize = 14;
var stageHeadingCount = 0;
var lastRadius = 0;
var lastQuadrant='';
var spacer = 6;
var fontSize = 10;
var total_index = 1;
//TODO: Super fragile: re-order the items, by radius, in order to logically group by the rings.
for (var i = 0; i < radar_data.length; i++) {
//adjust top by the number of headings.
if (lastQuadrant != radar_data[i].quadrant) {
radar.add(pv.Label)
.left( radar_data[i].left )
.top( radar_data[i].top )
.text( radar_data[i].quadrant )
.strokeStyle( radar_data[i].color )
.fillStyle( radar_data[i].color )
.font(quadrantFontSize + "px sans-serif");
lastQuadrant = radar_data[i].quadrant;
}
var itemsByStage = _.groupBy(radar_data[i].items, function(item) {return Math.floor(item.pc.r / 100)});
var offsetIndex = 0;
for (var stageIdx in _(itemsByStage).keys()) {
if (stageIdx > 0) {
offsetIndex = offsetIndex + itemsByStage[stageIdx-1].length + 1;
console.log("offsetIndex = " + itemsByStage[stageIdx-1].length, offsetIndex );
}
radar.add(pv.Label)
.left( radar_data[i].left + headingFontSize )
.top( radar_data[i].top + quadrantFontSize + spacer + (stageIdx * headingFontSize) + (offsetIndex * fontSize) )
.text( radar_arcs[stageIdx].name)
.strokeStyle( '#cccccc' )
.fillStyle( '#cccccc')
.font(headingFontSize + "px Courier New");
radar.add(pv.Label)
.left( radar_data[i].left )
.top( radar_data[i].top + quadrantFontSize + spacer + (stageIdx * headingFontSize) + (offsetIndex * fontSize) )
.strokeStyle( radar_data[i].color )
.fillStyle( radar_data[i].color )
.add( pv.Dot )
.def("i", radar_data[i].top + quadrantFontSize + spacer + (stageIdx * headingFontSize) + spacer + (offsetIndex * fontSize) )
.data(itemsByStage[stageIdx])
.top( function() { return ( this.i() + (this.index * fontSize) );} )
.shape( function(d) {return (d.movement === 't' ? "triangle" : "circle");})
.cursor( function(d) { return ( d.url !== undefined ? "pointer" : "auto" ); })
.event("click", function(d) { if ( d.url !== undefined ){self.location = d.url}})
.size(fontSize)
.angle(45)
.anchor("right")
.add(pv.Label)
.text(function(d) {return radar_quadrant_ctr++ + ". " + d.name;} );
radar.add(pv.Dot)
.def("active", false)
.data(itemsByStage[stageIdx])
.size( function(d) { return ( d.blipSize !== undefined ? d.blipSize : 70 ); })
.left(function(d) { var x = polar_to_raster(d.pc.r, d.pc.t)[0];
//console.log("name:" + d.name + ", x:" + x);
return x;})
.bottom(function(d) { var y = polar_to_raster(d.pc.r, d.pc.t)[1];
//console.log("name:" + d.name + ", y:" + y);
return y;})
.title(function(d) { return d.name;})
.cursor( function(d) { return ( d.url !== undefined ? "pointer" : "auto" ); })
.event("click", function(d) { if ( d.url !== undefined ){self.location = d.url}})
.angle(Math.PI) // 180 degrees in radians !
.strokeStyle(radar_data[i].color)
.fillStyle(radar_data[i].color)
.shape(function(d) {return (d.movement === 't' ? "triangle" : "circle");})
.anchor("center")
.add(pv.Label)
.text(function(d) {return total_index++;})
.textBaseline("middle")
.textStyle("white");
}
}
radar.anchor('radar');
radar.render();
};
|
Group items by stage
|
radar.js
|
Group items by stage
|
<ide><path>adar.js
<ide>
<ide> }
<ide>
<del> var itemsByStage = _.groupBy(radar_data[i].items, function(item) {return Math.floor(item.pc.r / 100)});
<add> // group items by stage based on how far they are from each arc
<add> var itemsByStage = _.groupBy(radar_data[i].items, function(item) {
<add> for(var arc_i = 0; arc_i < radar_arcs.length; arc_i++) {
<add> if (item.pc.r < radar_arcs[arc_i].r)
<add> {
<add> return arc_i;
<add> }
<add> }
<add> return 0;
<add> });
<add>
<ide> var offsetIndex = 0;
<ide> for (var stageIdx in _(itemsByStage).keys()) {
<ide>
|
|
Java
|
apache-2.0
|
c2b9285435db2b08a1a9ef5ed340f38652b9fa9a
| 0 |
arx-deidentifier/arx,jgaupp/arx,kentoa/arx,RaffaelBild/arx,RaffaelBild/arx,fstahnke/arx,fstahnke/arx,kbabioch/arx,bitraten/arx,kentoa/arx,kbabioch/arx,bitraten/arx,arx-deidentifier/arx,jgaupp/arx
|
package org.deidentifier.arx.gui;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.deidentifier.arx.gui.view.SWTUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.DeviceData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
/**
* Code based on: https://www.eclipse.org/articles/swt-design-2/sleak.htm
*
*/
public class DebugResourceLeaks {
class Resource {
Object resource;
Error error;
int occurrences;
@Override
protected Resource clone() {
Resource resource = new Resource();
resource.error = error;
resource.resource = this.resource;
resource.occurrences = occurrences;
return resource;
}
}
public static void main(String[] args) {
DebugResourceLeaks sleak = new DebugResourceLeaks();
Display display = sleak.open();
Main.main(display, new String[0]);
}
private Display display;
private Shell shell;
private Label resourceStatistics;
private Label resourceStackTrace;
private List listResources;
private List listResourcesSameStackTrace;
private Resource[] resources;
private Resource[] resourcesSameStackTrace;
private void collectAll() {
DeviceData info = display.getDeviceData();
if (!info.tracking) {
MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
dialog.setText(shell.getText());
dialog.setMessage("Warning: Device is not tracking resource allocation");
dialog.open();
}
Object[] objects = info.objects;
Error[] errors = info.errors;
resources = new Resource[objects.length];
for (int i = 0; i < resources.length; i++) {
Resource resource = new Resource();
resource.error = errors[i];
resource.resource = objects[i];
resource.occurrences = 1;
resources[i] = resource;
}
Map<String, Integer> objectTypesTimes = new TreeMap<String, Integer>();
Map<String, Resource> objectSameStackTrace = new HashMap<String, Resource>();
for (int i = 0; i < resources.length; i++) {
String className = resources[i].resource.getClass().getSimpleName();
Integer count = objectTypesTimes.get(className);
if (count == null) {
objectTypesTimes.put(className, 1);
} else {
objectTypesTimes.put(className, count + 1);
}
String stackTrace = getStackTrace(resources[i].error);
if (!objectSameStackTrace.containsKey(stackTrace)) {
Resource resource = resources[i].clone();
resource.occurrences = 1;
objectSameStackTrace.put(stackTrace, resource);
} else {
Resource resource = objectSameStackTrace.get(stackTrace);
resource.occurrences++;
}
}
resourcesSameStackTrace = new Resource[objectSameStackTrace.size()];
int idx = 0;
for (Entry<String, Resource> entry : objectSameStackTrace.entrySet()) {
resourcesSameStackTrace[idx] = entry.getValue();
idx++;
}
Arrays.sort(resourcesSameStackTrace, new Comparator<Resource>() {
@Override
public int compare(Resource o1, Resource o2) {
return o2.occurrences - o1.occurrences;
}
});
StringBuilder statistics = new StringBuilder();
for (Entry<String, Integer> entry : objectTypesTimes.entrySet()) {
statistics.append(entry.getKey());
statistics.append(": ");
statistics.append(entry.getValue());
statistics.append("\n");
}
statistics.append("Total: ");
statistics.append(resources.length);
statistics.append("\n");
// Display
listResources.removeAll();
for (int i = 0; i < resources.length; i++) {
listResources.add(resources[i].resource.getClass().getSimpleName() + "(" + resources[i].resource.hashCode() + ")");
}
listResourcesSameStackTrace.removeAll();
for (int i = 0; i < resourcesSameStackTrace.length; i++) {
listResourcesSameStackTrace.add(resourcesSameStackTrace[i].resource.getClass().getSimpleName() + "(" + resourcesSameStackTrace[i].resource.hashCode() + ")" + "[" + resourcesSameStackTrace[i].occurrences + "x]");
}
resourceStatistics.setText(statistics.toString());
}
private String getStackTrace(Error error) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
PrintStream s = new PrintStream(stream);
error.printStackTrace(s);
return stream.toString();
}
private Display open() {
DeviceData data = new DeviceData();
data.tracking = true;
Display display = new Display(data);
this.display = display;
shell = new Shell(display);
shell.setText("Resources");
shell.setLayout(SWTUtil.createGridLayout(2));
Button collect = new Button(shell, SWT.PUSH);
collect.setText("Collect data");
collect.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
collectAll();
}
});
final GridData d = new GridData();
d.grabExcessHorizontalSpace = true;
d.horizontalSpan = 2;
collect.setLayoutData(d);
listResources = new List(shell, SWT.BORDER | SWT.V_SCROLL);
listResources.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
selectObject();
}
});
listResources.setLayoutData(SWTUtil.createFillGridData());
listResourcesSameStackTrace = new List(shell, SWT.BORDER | SWT.V_SCROLL);
listResourcesSameStackTrace.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
selectEqualObject();
}
});
listResourcesSameStackTrace.setLayoutData(SWTUtil.createFillGridData());
resourceStackTrace = new Label(shell, SWT.BORDER);
resourceStackTrace.setText("");
resourceStackTrace.setLayoutData(SWTUtil.createFillGridData());
resourceStatistics = new Label(shell, SWT.BORDER);
resourceStatistics.setText("0 object(s)");
resourceStatistics.setLayoutData(SWTUtil.createFillGridData());
shell.open();
return display;
}
private void selectEqualObject() {
int index = listResourcesSameStackTrace.getSelectionIndex();
if (index == -1) {
return;
}
resourceStackTrace.setText(getStackTrace(resourcesSameStackTrace[index].error));
resourceStackTrace.setVisible(true);
}
private void selectObject() {
int index = listResources.getSelectionIndex();
if (index == -1) {
return;
}
resourceStackTrace.setText(getStackTrace(resources[index].error));
resourceStackTrace.setVisible(true);
}
}
|
src/gui/org/deidentifier/arx/gui/DebugResourceLeaks.java
|
package org.deidentifier.arx.gui;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.deidentifier.arx.gui.view.SWTUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.DeviceData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
/**
* Code based on: https://www.eclipse.org/articles/swt-design-2/sleak.htm
*
*/
public class DebugResourceLeaks {
class Resource {
Object resource;
Error error;
int occurrences;
@Override
protected Resource clone() {
Resource resource = new Resource();
resource.error = error;
resource.resource = this.resource;
resource.occurrences = occurrences;
return resource;
}
}
public static void main(String[] args) {
DebugResourceLeaks sleak = new DebugResourceLeaks();
Display display = sleak.open();
Main.main(display, new String[0]);
}
private Display display;
private Shell shell;
private Label objectStatistics;
private Label objectStackTrace;
private List listNewObjects;
private List listEqualObjects;
private Resource[] resources;
private Resource[] resourcesSameStackTrace;
private void collectAll() {
DeviceData info = display.getDeviceData();
if (!info.tracking) {
MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
dialog.setText(shell.getText());
dialog.setMessage("Warning: Device is not tracking resource allocation");
dialog.open();
}
Object[] objects = info.objects;
Error[] errors = info.errors;
resources = new Resource[objects.length];
for (int i = 0; i < resources.length; i++) {
Resource resource = new Resource();
resource.error = errors[i];
resource.resource = objects[i];
resource.occurrences = 1;
resources[i] = resource;
}
Map<String, Integer> objectTypesTimes = new TreeMap<String, Integer>();
Map<String, Resource> objectSameStackTrace = new HashMap<String, Resource>();
for (int i = 0; i < resources.length; i++) {
String className = resources[i].resource.getClass().getSimpleName();
Integer count = objectTypesTimes.get(className);
if (count == null) {
objectTypesTimes.put(className, 1);
} else {
objectTypesTimes.put(className, count + 1);
}
String stackTrace = getStackTrace(resources[i].error);
if (!objectSameStackTrace.containsKey(stackTrace)) {
Resource resource = resources[i].clone();
resource.occurrences = 1;
objectSameStackTrace.put(stackTrace, resource);
} else {
Resource resource = objectSameStackTrace.get(stackTrace);
resource.occurrences++;
}
}
resourcesSameStackTrace = new Resource[objectSameStackTrace.size()];
int idx = 0;
for (Entry<String, Resource> entry : objectSameStackTrace.entrySet()) {
resourcesSameStackTrace[idx] = entry.getValue();
idx++;
}
Arrays.sort(resourcesSameStackTrace, new Comparator<Resource>() {
@Override
public int compare(Resource o1, Resource o2) {
return o2.occurrences - o1.occurrences;
}
});
StringBuilder statistics = new StringBuilder();
for (Entry<String, Integer> entry : objectTypesTimes.entrySet()) {
statistics.append(entry.getKey());
statistics.append(": ");
statistics.append(entry.getValue());
statistics.append("\n");
}
statistics.append("Total: ");
statistics.append(resources.length);
statistics.append("\n");
// Display
listNewObjects.removeAll();
for (int i = 0; i < resources.length; i++) {
listNewObjects.add(resources[i].resource.getClass().getSimpleName() + "(" + resources[i].resource.hashCode() + ")");
}
listEqualObjects.removeAll();
for (int i = 0; i < resourcesSameStackTrace.length; i++) {
listEqualObjects.add(resourcesSameStackTrace[i].resource.getClass().getSimpleName() + "(" + resourcesSameStackTrace[i].resource.hashCode() + ")" + "[" + resourcesSameStackTrace[i].occurrences + "x]");
}
objectStatistics.setText(statistics.toString());
}
private String getStackTrace(Error error) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
PrintStream s = new PrintStream(stream);
error.printStackTrace(s);
return stream.toString();
}
private Display open() {
DeviceData data = new DeviceData();
data.tracking = true;
Display display = new Display(data);
this.display = display;
shell = new Shell(display);
shell.setText("Resources");
shell.setLayout(SWTUtil.createGridLayout(2));
Button collect = new Button(shell, SWT.PUSH);
collect.setText("Collect data");
collect.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
collectAll();
}
});
final GridData d = new GridData();
d.grabExcessHorizontalSpace = true;
d.horizontalSpan = 2;
collect.setLayoutData(d);
listNewObjects = new List(shell, SWT.BORDER | SWT.V_SCROLL);
listNewObjects.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
selectObject();
}
});
listNewObjects.setLayoutData(SWTUtil.createFillGridData());
listEqualObjects = new List(shell, SWT.BORDER | SWT.V_SCROLL);
listEqualObjects.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
selectEqualObject();
}
});
listEqualObjects.setLayoutData(SWTUtil.createFillGridData());
objectStackTrace = new Label(shell, SWT.BORDER);
objectStackTrace.setText("");
objectStackTrace.setLayoutData(SWTUtil.createFillGridData());
objectStatistics = new Label(shell, SWT.BORDER);
objectStatistics.setText("0 object(s)");
objectStatistics.setLayoutData(SWTUtil.createFillGridData());
shell.open();
return display;
}
private void selectEqualObject() {
int index = listEqualObjects.getSelectionIndex();
if (index == -1) {
return;
}
objectStackTrace.setText(getStackTrace(resourcesSameStackTrace[index].error));
objectStackTrace.setVisible(true);
}
private void selectObject() {
int index = listNewObjects.getSelectionIndex();
if (index == -1) {
return;
}
objectStackTrace.setText(getStackTrace(resources[index].error));
objectStackTrace.setVisible(true);
}
}
|
Refactor
|
src/gui/org/deidentifier/arx/gui/DebugResourceLeaks.java
|
Refactor
|
<ide><path>rc/gui/org/deidentifier/arx/gui/DebugResourceLeaks.java
<ide>
<ide> private Shell shell;
<ide>
<del> private Label objectStatistics;
<del> private Label objectStackTrace;
<del>
<del> private List listNewObjects;
<del> private List listEqualObjects;
<add> private Label resourceStatistics;
<add> private Label resourceStackTrace;
<add>
<add> private List listResources;
<add> private List listResourcesSameStackTrace;
<ide>
<ide> private Resource[] resources;
<ide> private Resource[] resourcesSameStackTrace;
<ide> statistics.append("\n");
<ide>
<ide> // Display
<del> listNewObjects.removeAll();
<add> listResources.removeAll();
<ide> for (int i = 0; i < resources.length; i++) {
<del> listNewObjects.add(resources[i].resource.getClass().getSimpleName() + "(" + resources[i].resource.hashCode() + ")");
<del> }
<del>
<del> listEqualObjects.removeAll();
<add> listResources.add(resources[i].resource.getClass().getSimpleName() + "(" + resources[i].resource.hashCode() + ")");
<add> }
<add>
<add> listResourcesSameStackTrace.removeAll();
<ide> for (int i = 0; i < resourcesSameStackTrace.length; i++) {
<del> listEqualObjects.add(resourcesSameStackTrace[i].resource.getClass().getSimpleName() + "(" + resourcesSameStackTrace[i].resource.hashCode() + ")" + "[" + resourcesSameStackTrace[i].occurrences + "x]");
<del> }
<del>
<del> objectStatistics.setText(statistics.toString());
<add> listResourcesSameStackTrace.add(resourcesSameStackTrace[i].resource.getClass().getSimpleName() + "(" + resourcesSameStackTrace[i].resource.hashCode() + ")" + "[" + resourcesSameStackTrace[i].occurrences + "x]");
<add> }
<add>
<add> resourceStatistics.setText(statistics.toString());
<ide> }
<ide>
<ide> private String getStackTrace(Error error) {
<ide> d.horizontalSpan = 2;
<ide> collect.setLayoutData(d);
<ide>
<del> listNewObjects = new List(shell, SWT.BORDER | SWT.V_SCROLL);
<del> listNewObjects.addListener(SWT.Selection, new Listener() {
<add> listResources = new List(shell, SWT.BORDER | SWT.V_SCROLL);
<add> listResources.addListener(SWT.Selection, new Listener() {
<ide> @Override
<ide> public void handleEvent(Event event) {
<ide> selectObject();
<ide> }
<ide> });
<del> listNewObjects.setLayoutData(SWTUtil.createFillGridData());
<del>
<del> listEqualObjects = new List(shell, SWT.BORDER | SWT.V_SCROLL);
<del> listEqualObjects.addListener(SWT.Selection, new Listener() {
<add> listResources.setLayoutData(SWTUtil.createFillGridData());
<add>
<add> listResourcesSameStackTrace = new List(shell, SWT.BORDER | SWT.V_SCROLL);
<add> listResourcesSameStackTrace.addListener(SWT.Selection, new Listener() {
<ide> @Override
<ide> public void handleEvent(Event event) {
<ide> selectEqualObject();
<ide> }
<ide> });
<del> listEqualObjects.setLayoutData(SWTUtil.createFillGridData());
<del>
<del> objectStackTrace = new Label(shell, SWT.BORDER);
<del> objectStackTrace.setText("");
<del> objectStackTrace.setLayoutData(SWTUtil.createFillGridData());
<del>
<del> objectStatistics = new Label(shell, SWT.BORDER);
<del> objectStatistics.setText("0 object(s)");
<del> objectStatistics.setLayoutData(SWTUtil.createFillGridData());
<add> listResourcesSameStackTrace.setLayoutData(SWTUtil.createFillGridData());
<add>
<add> resourceStackTrace = new Label(shell, SWT.BORDER);
<add> resourceStackTrace.setText("");
<add> resourceStackTrace.setLayoutData(SWTUtil.createFillGridData());
<add>
<add> resourceStatistics = new Label(shell, SWT.BORDER);
<add> resourceStatistics.setText("0 object(s)");
<add> resourceStatistics.setLayoutData(SWTUtil.createFillGridData());
<ide>
<ide> shell.open();
<ide>
<ide> }
<ide>
<ide> private void selectEqualObject() {
<del> int index = listEqualObjects.getSelectionIndex();
<add> int index = listResourcesSameStackTrace.getSelectionIndex();
<ide> if (index == -1) {
<ide> return;
<ide> }
<ide>
<del> objectStackTrace.setText(getStackTrace(resourcesSameStackTrace[index].error));
<del> objectStackTrace.setVisible(true);
<add> resourceStackTrace.setText(getStackTrace(resourcesSameStackTrace[index].error));
<add> resourceStackTrace.setVisible(true);
<ide> }
<ide>
<ide> private void selectObject() {
<del> int index = listNewObjects.getSelectionIndex();
<add> int index = listResources.getSelectionIndex();
<ide> if (index == -1) {
<ide> return;
<ide> }
<ide>
<del> objectStackTrace.setText(getStackTrace(resources[index].error));
<del> objectStackTrace.setVisible(true);
<add> resourceStackTrace.setText(getStackTrace(resources[index].error));
<add> resourceStackTrace.setVisible(true);
<ide> }
<ide>
<ide> }
|
|
Java
|
bsd-3-clause
|
f35526eb245793a96c77e3fa861926f6e052871c
| 0 |
hispindia/dhis2-Core,msf-oca-his/dhis2-core,hispindia/dhis2-Core,hispindia/dhis2-Core,dhis2/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,hispindia/dhis2-Core,msf-oca-his/dhis2-core,dhis2/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,msf-oca-his/dhis2-core,dhis2/dhis2-core,hispindia/dhis2-Core
|
package org.hisp.dhis.analytics.table;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.hisp.dhis.analytics.AnalyticsTable;
import org.hisp.dhis.analytics.AnalyticsTableColumn;
import org.hisp.dhis.analytics.AnalyticsTablePartition;
import org.hisp.dhis.analytics.AnalyticsTableType;
import org.hisp.dhis.analytics.AnalyticsTableUpdateParams;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.commons.collection.UniqueArrayList;
import org.hisp.dhis.commons.util.TextUtils;
import org.hisp.dhis.organisationunit.OrganisationUnitGroupSet;
import org.hisp.dhis.organisationunit.OrganisationUnitLevel;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import static org.hisp.dhis.system.util.DateUtils.getLongDateString;
import static org.hisp.dhis.system.util.MathUtils.NUMERIC_LENIENT_REGEXP;
import static org.hisp.dhis.analytics.util.AnalyticsSqlUtils.quote;
/**
* @author Markus Bekken
*/
public class JdbcEnrollmentAnalyticsTableManager
extends AbstractEventJdbcTableManager
{
private static final Set<ValueType> NO_INDEX_VAL_TYPES = ImmutableSet.of( ValueType.TEXT, ValueType.LONG_TEXT );
@Override
public AnalyticsTableType getAnalyticsTableType()
{
return AnalyticsTableType.ENROLLMENT;
}
@Override
@Transactional
public List<AnalyticsTable> getAnalyticsTables( Date earliest )
{
List<AnalyticsTable> tables = new UniqueArrayList<>();
List<Program> programs = idObjectManager.getAllNoAcl( Program.class );
String baseName = getTableName();
for ( Program program : programs )
{
AnalyticsTable table = new AnalyticsTable( baseName, getDimensionColumns( program ), Lists.newArrayList(), program );
tables.add( table );
}
return tables;
}
@Override
public Set<String> getExistingDatabaseTables()
{
return new HashSet<>();
}
@Override
protected List<String> getPartitionChecks( AnalyticsTablePartition partition )
{
return Lists.newArrayList();
}
@Override
protected void populateTable( AnalyticsTableUpdateParams params, AnalyticsTablePartition partition )
{
final Program program = partition.getMasterTable().getProgram();
final String tableName = partition.getTempTableName();
String sql = "insert into " + partition.getTempTableName() + " (";
List<AnalyticsTableColumn> columns = getDimensionColumns( program );
validateDimensionColumns( columns );
for ( AnalyticsTableColumn col : columns )
{
sql += col.getName() + ",";
}
sql = TextUtils.removeLastComma( sql ) + ") select ";
for ( AnalyticsTableColumn col : columns )
{
sql += col.getAlias() + ",";
}
sql = TextUtils.removeLastComma( sql ) + " ";
sql += "from programinstance pi " +
"inner join program pr on pi.programid=pr.programid " +
"left join trackedentityinstance tei on pi.trackedentityinstanceid=tei.trackedentityinstanceid and tei.deleted is false " +
"inner join organisationunit ou on pi.organisationunitid=ou.organisationunitid " +
"left join _orgunitstructure ous on pi.organisationunitid=ous.organisationunitid " +
"left join _organisationunitgroupsetstructure ougs on pi.organisationunitid=ougs.organisationunitid " +
"and (cast(date_trunc('month', pi.enrollmentdate) as date)=ougs.startdate or ougs.startdate is null) " +
"left join _dateperiodstructure dps on cast(pi.enrollmentdate as date)=dps.dateperiod " +
"where pr.programid=" + program.getId() + " " +
"and pi.organisationunitid is not null " +
"and pi.lastupdated <= '" + getLongDateString( params.getStartTime() ) + "' " +
"and pi.incidentdate is not null " +
"and pi.deleted is false ";
populateAndLog( sql, tableName );
}
private List<AnalyticsTableColumn> getDimensionColumns( Program program )
{
final String dbl = statementBuilder.getDoubleColumnType();
final String numericClause = " and value " + statementBuilder.getRegexpMatch() + " '" + NUMERIC_LENIENT_REGEXP + "'";
final String dateClause = " and value " + statementBuilder.getRegexpMatch() + " '" + DATE_REGEXP + "'";
List<AnalyticsTableColumn> columns = new ArrayList<>();
List<OrganisationUnitLevel> levels =
organisationUnitService.getFilledOrganisationUnitLevels();
List<OrganisationUnitGroupSet> orgUnitGroupSets =
idObjectManager.getDataDimensionsNoAcl( OrganisationUnitGroupSet.class );
for ( OrganisationUnitLevel level : levels )
{
String column = quote( PREFIX_ORGUNITLEVEL + level.getLevel() );
columns.add( new AnalyticsTableColumn( column, "character(11)", "ous." + column, level.getCreated() ) );
}
for ( OrganisationUnitGroupSet groupSet : orgUnitGroupSets )
{
columns.add( new AnalyticsTableColumn( quote( groupSet.getUid() ), "character(11)", "ougs." + quote( groupSet.getUid() ), groupSet.getCreated() ) );
}
for ( PeriodType periodType : PeriodType.getAvailablePeriodTypes() )
{
String column = quote( periodType.getName().toLowerCase() );
columns.add( new AnalyticsTableColumn( column, "text", "dps." + column ) );
}
for ( TrackedEntityAttribute attribute : program.getNonConfidentialTrackedEntityAttributes() )
{
String dataType = getColumnType( attribute.getValueType() );
String dataClause = attribute.isNumericType() ? numericClause : attribute.isDateType() ? dateClause : "";
String select = getSelectClause( attribute.getValueType() );
boolean skipIndex = NO_INDEX_VAL_TYPES.contains( attribute.getValueType() ) && !attribute.hasOptionSet();
String sql = "(select " + select + " from trackedentityattributevalue " +
"where trackedentityinstanceid=pi.trackedentityinstanceid " +
"and trackedentityattributeid=" + attribute.getId() + dataClause + ") as " + quote( attribute.getUid() );
columns.add( new AnalyticsTableColumn( quote( attribute.getUid() ), dataType, sql, skipIndex ) );
}
columns.add( new AnalyticsTableColumn( quote( "pi" ), "character(11) not null", "pi.uid" ) );
columns.add( new AnalyticsTableColumn( quote( "enrollmentdate" ), "timestamp", "pi.enrollmentdate" ) );
columns.add( new AnalyticsTableColumn( quote( "incidentdate" ), "timestamp", "pi.incidentdate" ) );
final String executionDateSql = "(select psi.executionDate from programstageinstance psi " +
"where psi.programinstanceid=pi.programinstanceid " +
"and psi.executiondate is not null " +
"and psi.deleted is false " +
"order by psi.executiondate desc " +
"limit 1) as " + quote( "executiondate" );
columns.add( new AnalyticsTableColumn( quote( "executiondate" ), "timestamp", executionDateSql ) );
final String dueDateSql = "(select psi.duedate from programstageinstance psi " +
"where psi.programinstanceid = pi.programinstanceid " +
"and psi.duedate is not null " +
"and psi.deleted is false " +
"order by psi.duedate desc " +
"limit 1) as " + quote( "duedate" );
columns.add( new AnalyticsTableColumn( quote( "duedate" ), "timestamp", dueDateSql ) );
columns.add( new AnalyticsTableColumn( quote( "completeddate" ), "timestamp", "case pi.status when 'COMPLETED' then pi.enddate end" ) );
columns.add( new AnalyticsTableColumn( quote( "enrollmentstatus" ), "character(50)", "pi.status" ) );
columns.add( new AnalyticsTableColumn( quote( "longitude" ), dbl, "ST_X(pi.geometry)" ) );
columns.add( new AnalyticsTableColumn( quote( "latitude" ), dbl, "ST_Y(pi.geometry)" ) );
columns.add( new AnalyticsTableColumn( quote( "ou" ), "character(11) not null", "ou.uid" ) );
columns.add( new AnalyticsTableColumn( quote( "ouname" ), "text not null", "ou.name" ) );
columns.add( new AnalyticsTableColumn( quote( "oucode" ), "text", "ou.code" ) );
columns.add( new AnalyticsTableColumn( quote( "geom" ), "geometry", "pi.geometry", false, "gist" ) );
if ( program.isRegistration() )
{
columns.add( new AnalyticsTableColumn( quote( "tei" ), "character(11)", "tei.uid" ) );
}
return filterDimensionColumns( columns );
}
}
|
dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEnrollmentAnalyticsTableManager.java
|
package org.hisp.dhis.analytics.table;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.hisp.dhis.analytics.AnalyticsTable;
import org.hisp.dhis.analytics.AnalyticsTableColumn;
import org.hisp.dhis.analytics.AnalyticsTablePartition;
import org.hisp.dhis.analytics.AnalyticsTableType;
import org.hisp.dhis.analytics.AnalyticsTableUpdateParams;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.commons.collection.UniqueArrayList;
import org.hisp.dhis.commons.util.TextUtils;
import org.hisp.dhis.organisationunit.OrganisationUnitGroupSet;
import org.hisp.dhis.organisationunit.OrganisationUnitLevel;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import static org.hisp.dhis.system.util.DateUtils.getLongDateString;
import static org.hisp.dhis.system.util.MathUtils.NUMERIC_LENIENT_REGEXP;
import static org.hisp.dhis.analytics.util.AnalyticsSqlUtils.quote;
/**
* @author Markus Bekken
*/
public class JdbcEnrollmentAnalyticsTableManager
extends AbstractEventJdbcTableManager
{
private static final Set<ValueType> NO_INDEX_VAL_TYPES = ImmutableSet.of( ValueType.TEXT, ValueType.LONG_TEXT );
@Override
public AnalyticsTableType getAnalyticsTableType()
{
return AnalyticsTableType.ENROLLMENT;
}
@Override
@Transactional
public List<AnalyticsTable> getAnalyticsTables( Date earliest )
{
List<AnalyticsTable> tables = new UniqueArrayList<>();
List<Program> programs = idObjectManager.getAllNoAcl( Program.class );
String baseName = getTableName();
for ( Program program : programs )
{
AnalyticsTable table = new AnalyticsTable( baseName, getDimensionColumns( program ), Lists.newArrayList(), program );
tables.add( table );
}
return tables;
}
@Override
public Set<String> getExistingDatabaseTables()
{
return new HashSet<>();
}
@Override
protected List<String> getPartitionChecks( AnalyticsTablePartition partition )
{
return Lists.newArrayList();
}
@Override
protected void populateTable( AnalyticsTableUpdateParams params, AnalyticsTablePartition partition )
{
final Program program = partition.getMasterTable().getProgram();
final String tableName = partition.getTempTableName();
String sql = "insert into " + partition.getTempTableName() + " (";
List<AnalyticsTableColumn> columns = getDimensionColumns( program );
validateDimensionColumns( columns );
for ( AnalyticsTableColumn col : columns )
{
sql += col.getName() + ",";
}
sql = TextUtils.removeLastComma( sql ) + ") select ";
for ( AnalyticsTableColumn col : columns )
{
sql += col.getAlias() + ",";
}
sql = TextUtils.removeLastComma( sql ) + " ";
sql += "from programinstance pi " +
"inner join program pr on pi.programid=pr.programid " +
"left join trackedentityinstance tei on pi.trackedentityinstanceid=tei.trackedentityinstanceid and tei.deleted is false " +
"inner join organisationunit ou on pi.organisationunitid=ou.organisationunitid " +
"left join _orgunitstructure ous on pi.organisationunitid=ous.organisationunitid " +
"left join _organisationunitgroupsetstructure ougs on pi.organisationunitid=ougs.organisationunitid " +
"and (cast(date_trunc('month', pi.enrollmentdate) as date)=ougs.startdate or ougs.startdate is null) " +
"left join _dateperiodstructure dps on cast(pi.enrollmentdate as date)=dps.dateperiod " +
"where pr.programid=" + program.getId() + " " +
"and pi.organisationunitid is not null " +
"and pi.lastupdated <= '" + getLongDateString( params.getStartTime() ) + "' " +
"and pi.incidentdate is not null " +
"and pi.deleted is false ";
populateAndLog( sql, tableName );
}
private List<AnalyticsTableColumn> getDimensionColumns( Program program )
{
final String dbl = statementBuilder.getDoubleColumnType();
final String numericClause = " and value " + statementBuilder.getRegexpMatch() + " '" + NUMERIC_LENIENT_REGEXP + "'";
final String dateClause = " and value " + statementBuilder.getRegexpMatch() + " '" + DATE_REGEXP + "'";
List<AnalyticsTableColumn> columns = new ArrayList<>();
List<OrganisationUnitLevel> levels =
organisationUnitService.getFilledOrganisationUnitLevels();
List<OrganisationUnitGroupSet> orgUnitGroupSets =
idObjectManager.getDataDimensionsNoAcl( OrganisationUnitGroupSet.class );
for ( OrganisationUnitLevel level : levels )
{
String column = quote( PREFIX_ORGUNITLEVEL + level.getLevel() );
columns.add( new AnalyticsTableColumn( column, "character(11)", "ous." + column, level.getCreated() ) );
}
for ( OrganisationUnitGroupSet groupSet : orgUnitGroupSets )
{
columns.add( new AnalyticsTableColumn( quote( groupSet.getUid() ), "character(11)", "ougs." + quote( groupSet.getUid() ), groupSet.getCreated() ) );
}
for ( PeriodType periodType : PeriodType.getAvailablePeriodTypes() )
{
String column = quote( periodType.getName().toLowerCase() );
columns.add( new AnalyticsTableColumn( column, "text", "dps." + column ) );
}
for ( TrackedEntityAttribute attribute : program.getNonConfidentialTrackedEntityAttributes() )
{
String dataType = getColumnType( attribute.getValueType() );
String dataClause = attribute.isNumericType() ? numericClause : attribute.isDateType() ? dateClause : "";
String select = getSelectClause( attribute.getValueType() );
boolean skipIndex = NO_INDEX_VAL_TYPES.contains( attribute.getValueType() ) && !attribute.hasOptionSet();
String sql = "(select " + select + " from trackedentityattributevalue " +
"where trackedentityinstanceid=pi.trackedentityinstanceid " +
"and trackedentityattributeid=" + attribute.getId() + dataClause + ") as " + quote( attribute.getUid() );
columns.add( new AnalyticsTableColumn( quote( attribute.getUid() ), dataType, sql, skipIndex ) );
}
columns.add( new AnalyticsTableColumn( quote( "pi" ), "character(11) not null", "pi.uid" ) );
columns.add( new AnalyticsTableColumn( quote( "enrollmentdate" ), "timestamp", "pi.enrollmentdate" ) );
columns.add( new AnalyticsTableColumn( quote( "incidentdate" ), "timestamp", "pi.incidentdate" ) );
final String executionDateSql = "(select psi.executionDate from programstageinstance psi " +
"where psi.programinstanceid=pi.programinstanceid " +
"and psi.executiondate is not null " +
"and psi.deleted is false " +
"order by psi.executiondate desc " +
"limit 1) as " + quote( "executiondate" );
columns.add( new AnalyticsTableColumn( quote( "executiondate" ), "timestamp", executionDateSql ) );
final String dueDateSql = "(select psi.duedate from programstageinstance psi " +
"where psi.programinstanceid = pi.programinstanceid " +
"and psi.duedate is not null " +
"and psi.deleted is false " +
"order by psi.duedate desc " +
"limit 1) as " + quote( "duedate" );
columns.add( new AnalyticsTableColumn( quote( "duedate" ), "timestamp", dueDateSql ) );
columns.add( new AnalyticsTableColumn( quote( "completeddate" ), "timestamp", "case pi.status when 'COMPLETED' then pi.enddate end" ) );
columns.add( new AnalyticsTableColumn( quote( "enrollmentstatus" ), "character(50)", "pi.status" ) );
columns.add( new AnalyticsTableColumn( quote( "longitude" ), dbl, "ST_X(pi.geometry)" ) );
columns.add( new AnalyticsTableColumn( quote( "latitude" ), dbl, "ST_Y(pi.geometry)" ) );
columns.add( new AnalyticsTableColumn( quote( "ou" ), "character(11) not null", "ou.uid" ) );
columns.add( new AnalyticsTableColumn( quote( "ouname" ), "text not null", "ou.name" ) );
columns.add( new AnalyticsTableColumn( quote( "oucode" ), "text", "ou.code" ) );
if ( databaseInfo.isSpatialSupport() )
{
columns.add( new AnalyticsTableColumn( quote( "geom" ), "geometry(Point, 4326)", "pi.geometry", false, "gist" ) );
}
if ( program.isRegistration() )
{
columns.add( new AnalyticsTableColumn( quote( "tei" ), "character(11)", "tei.uid" ) );
}
return filterDimensionColumns( columns );
}
}
|
Fixed a bug where analytics fails when adding geometry data
|
dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEnrollmentAnalyticsTableManager.java
|
Fixed a bug where analytics fails when adding geometry data
|
<ide><path>his-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcEnrollmentAnalyticsTableManager.java
<ide> columns.add( new AnalyticsTableColumn( quote( "ouname" ), "text not null", "ou.name" ) );
<ide> columns.add( new AnalyticsTableColumn( quote( "oucode" ), "text", "ou.code" ) );
<ide>
<del> if ( databaseInfo.isSpatialSupport() )
<del> {
<del> columns.add( new AnalyticsTableColumn( quote( "geom" ), "geometry(Point, 4326)", "pi.geometry", false, "gist" ) );
<del> }
<add> columns.add( new AnalyticsTableColumn( quote( "geom" ), "geometry", "pi.geometry", false, "gist" ) );
<ide>
<ide> if ( program.isRegistration() )
<ide> {
|
|
Java
|
apache-2.0
|
39aaf93bbba93b56c6dd9bcf2ea2312077d5c233
| 0 |
irccloud/android,irccloud/android,irccloud/android,irccloud/android,irccloud/android
|
/*
* Copyright (c) 2013 IRCCloud, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.irccloud.android.fragment;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.irccloud.android.NetworkConnection;
import com.irccloud.android.R;
@SuppressLint("ValidFragment")
public class ChannelOptionsFragment extends DialogFragment {
CheckBox members;
CheckBox unread;
CheckBox joinpart;
CheckBox collapse;
CheckBox notifyAll;
int cid;
int bid;
public ChannelOptionsFragment() {
cid = -1;
bid = -1;
}
public ChannelOptionsFragment(int cid, int bid) {
this.cid = cid;
this.bid = bid;
}
public JSONObject updatePref(JSONObject prefs, CheckBox control, String key) throws JSONException {
boolean checked = control.isChecked();
if(control == notifyAll)
checked = !checked;
if(!checked) {
JSONObject map;
if(prefs.has(key))
map = prefs.getJSONObject(key);
else
map = new JSONObject();
map.put(String.valueOf(bid), true);
prefs.put(key, map);
} else {
if(prefs.has(key)) {
JSONObject map = prefs.getJSONObject(key);
map.remove(String.valueOf(bid));
prefs.put(key, map);
}
}
return prefs;
}
class SaveClickListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
JSONObject prefs = null;
try {
if(NetworkConnection.getInstance().getUserInfo() != null) {
prefs = NetworkConnection.getInstance().getUserInfo().prefs;
if (prefs == null) {
prefs = new JSONObject();
Crashlytics.logException(new Exception("Users prefs was null, creating new object"));
}
prefs = updatePref(prefs, members, "channel-hiddenMembers");
prefs = updatePref(prefs, unread, "channel-disableTrackUnread");
prefs = updatePref(prefs, joinpart, "channel-hideJoinPart");
prefs = updatePref(prefs, collapse, "channel-expandJoinPart");
prefs = updatePref(prefs, notifyAll, "channel-notifications-all");
NetworkConnection.getInstance().set_prefs(prefs.toString());
} else {
Toast.makeText(getActivity(), "An error occurred while saving preferences. Please try again shortly", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Crashlytics.logException(e);
Toast.makeText(getActivity(), "An error occurred while saving preferences. Please try again shortly", Toast.LENGTH_SHORT).show();
}
dismiss();
}
}
@Override
public void onResume() {
super.onResume();
try {
if(NetworkConnection.getInstance().getUserInfo() != null) {
JSONObject prefs = NetworkConnection.getInstance().getUserInfo().prefs;
if(prefs != null) {
if(prefs.has("channel-hideJoinPart")) {
JSONObject hiddenMap = prefs.getJSONObject("channel-hideJoinPart");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
joinpart.setChecked(false);
else
joinpart.setChecked(true);
} else {
joinpart.setChecked(true);
}
if(prefs.has("channel-disableTrackUnread")) {
JSONObject unreadMap = prefs.getJSONObject("channel-disableTrackUnread");
if(unreadMap.has(String.valueOf(bid)) && unreadMap.getBoolean(String.valueOf(bid)))
unread.setChecked(false);
else
unread.setChecked(true);
} else {
unread.setChecked(true);
}
if(prefs.has("channel-hiddenMembers")) {
JSONObject membersMap = prefs.getJSONObject("channel-hiddenMembers");
if(membersMap.has(String.valueOf(bid)) && membersMap.getBoolean(String.valueOf(bid)))
members.setChecked(false);
else
members.setChecked(true);
} else {
members.setChecked(true);
}
if(prefs.has("channel-expandJoinPart")) {
JSONObject expandMap = prefs.getJSONObject("channel-expandJoinPart");
if(expandMap.has(String.valueOf(bid)) && expandMap.getBoolean(String.valueOf(bid)))
collapse.setChecked(false);
else
collapse.setChecked(true);
} else {
collapse.setChecked(true);
}
if(prefs.has("channel-notifications-all")) {
JSONObject notifyAllMap = prefs.getJSONObject("channel-notifications-all");
if(notifyAllMap.has(String.valueOf(bid)) && notifyAllMap.getBoolean(String.valueOf(bid)))
notifyAll.setChecked(true);
else
notifyAll.setChecked(false);
} else {
notifyAll.setChecked(false);
}
} else {
notifyAll.setChecked(false);
joinpart.setChecked(true);
unread.setChecked(true);
members.setChecked(true);
collapse.setChecked(true);
}
} else {
notifyAll.setChecked(false);
joinpart.setChecked(true);
unread.setChecked(true);
members.setChecked(true);
collapse.setChecked(true);
}
if(!getActivity().getResources().getBoolean(R.bool.isTablet))
members.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if(savedInstanceState != null && savedInstanceState.containsKey("cid") && cid == -1) {
cid = savedInstanceState.getInt("cid");
bid = savedInstanceState.getInt("bid");
}
Context ctx = getActivity();
LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.dialog_channel_options,null);
members = (CheckBox)v.findViewById(R.id.members);
unread = (CheckBox)v.findViewById(R.id.unread);
notifyAll = (CheckBox)v.findViewById(R.id.notifyAll);
joinpart = (CheckBox)v.findViewById(R.id.joinpart);
collapse = (CheckBox)v.findViewById(R.id.collapse);
return new AlertDialog.Builder(ctx)
.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
.setTitle("Display Options")
.setView(v)
.setPositiveButton("Save", new SaveClickListener())
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt("cid", cid);
state.putInt("bid", bid);
}
}
|
src/com/irccloud/android/fragment/ChannelOptionsFragment.java
|
/*
* Copyright (c) 2013 IRCCloud, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.irccloud.android.fragment;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.irccloud.android.NetworkConnection;
import com.irccloud.android.R;
@SuppressLint("ValidFragment")
public class ChannelOptionsFragment extends DialogFragment {
CheckBox members;
CheckBox unread;
CheckBox joinpart;
CheckBox collapse;
CheckBox notifyAll;
int cid;
int bid;
public ChannelOptionsFragment() {
cid = -1;
bid = -1;
}
public ChannelOptionsFragment(int cid, int bid) {
this.cid = cid;
this.bid = bid;
}
public JSONObject updatePref(JSONObject prefs, CheckBox control, String key) throws JSONException {
boolean checked = control.isChecked();
if(control == notifyAll)
checked = !checked;
if(!checked) {
JSONObject map;
if(prefs.has(key))
map = prefs.getJSONObject(key);
else
map = new JSONObject();
map.put(String.valueOf(bid), true);
prefs.put(key, map);
} else {
if(prefs.has(key)) {
JSONObject map = prefs.getJSONObject(key);
map.remove(String.valueOf(bid));
prefs.put(key, map);
}
}
return prefs;
}
class SaveClickListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
JSONObject prefs = null;
try {
if(NetworkConnection.getInstance().getUserInfo() != null) {
prefs = NetworkConnection.getInstance().getUserInfo().prefs;
if (prefs == null)
prefs = new JSONObject();
prefs = updatePref(prefs, members, "channel-hiddenMembers");
prefs = updatePref(prefs, unread, "channel-disableTrackUnread");
prefs = updatePref(prefs, joinpart, "channel-hideJoinPart");
prefs = updatePref(prefs, collapse, "channel-expandJoinPart");
prefs = updatePref(prefs, notifyAll, "channel-notifications-all");
NetworkConnection.getInstance().set_prefs(prefs.toString());
} else {
Toast.makeText(getActivity(), "An error occurred while saving preferences. Please try again shortly", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Crashlytics.logException(e);
Toast.makeText(getActivity(), "An error occurred while saving preferences. Please try again shortly", Toast.LENGTH_SHORT).show();
}
dismiss();
}
}
@Override
public void onResume() {
super.onResume();
try {
if(NetworkConnection.getInstance().getUserInfo() != null) {
JSONObject prefs = NetworkConnection.getInstance().getUserInfo().prefs;
if(prefs != null) {
if(prefs.has("channel-hideJoinPart")) {
JSONObject hiddenMap = prefs.getJSONObject("channel-hideJoinPart");
if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid)))
joinpart.setChecked(false);
else
joinpart.setChecked(true);
} else {
joinpart.setChecked(true);
}
if(prefs.has("channel-disableTrackUnread")) {
JSONObject unreadMap = prefs.getJSONObject("channel-disableTrackUnread");
if(unreadMap.has(String.valueOf(bid)) && unreadMap.getBoolean(String.valueOf(bid)))
unread.setChecked(false);
else
unread.setChecked(true);
} else {
unread.setChecked(true);
}
if(prefs.has("channel-hiddenMembers")) {
JSONObject membersMap = prefs.getJSONObject("channel-hiddenMembers");
if(membersMap.has(String.valueOf(bid)) && membersMap.getBoolean(String.valueOf(bid)))
members.setChecked(false);
else
members.setChecked(true);
} else {
members.setChecked(true);
}
if(prefs.has("channel-expandJoinPart")) {
JSONObject expandMap = prefs.getJSONObject("channel-expandJoinPart");
if(expandMap.has(String.valueOf(bid)) && expandMap.getBoolean(String.valueOf(bid)))
collapse.setChecked(false);
else
collapse.setChecked(true);
} else {
collapse.setChecked(true);
}
if(prefs.has("channel-notifications-all")) {
JSONObject notifyAllMap = prefs.getJSONObject("channel-notifications-all");
if(notifyAllMap.has(String.valueOf(bid)) && notifyAllMap.getBoolean(String.valueOf(bid)))
notifyAll.setChecked(true);
else
notifyAll.setChecked(false);
} else {
notifyAll.setChecked(false);
}
} else {
notifyAll.setChecked(false);
joinpart.setChecked(true);
unread.setChecked(true);
members.setChecked(true);
collapse.setChecked(true);
}
} else {
notifyAll.setChecked(false);
joinpart.setChecked(true);
unread.setChecked(true);
members.setChecked(true);
collapse.setChecked(true);
}
if(!getActivity().getResources().getBoolean(R.bool.isTablet))
members.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if(savedInstanceState != null && savedInstanceState.containsKey("cid") && cid == -1) {
cid = savedInstanceState.getInt("cid");
bid = savedInstanceState.getInt("bid");
}
Context ctx = getActivity();
LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.dialog_channel_options,null);
members = (CheckBox)v.findViewById(R.id.members);
unread = (CheckBox)v.findViewById(R.id.unread);
notifyAll = (CheckBox)v.findViewById(R.id.notifyAll);
joinpart = (CheckBox)v.findViewById(R.id.joinpart);
collapse = (CheckBox)v.findViewById(R.id.collapse);
return new AlertDialog.Builder(ctx)
.setInverseBackgroundForced(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
.setTitle("Display Options")
.setView(v)
.setPositiveButton("Save", new SaveClickListener())
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt("cid", cid);
state.putInt("bid", bid);
}
}
|
Log a non-fatal ticket to Crashlytics when creating an empty user prefs object
|
src/com/irccloud/android/fragment/ChannelOptionsFragment.java
|
Log a non-fatal ticket to Crashlytics when creating an empty user prefs object
|
<ide><path>rc/com/irccloud/android/fragment/ChannelOptionsFragment.java
<ide> try {
<ide> if(NetworkConnection.getInstance().getUserInfo() != null) {
<ide> prefs = NetworkConnection.getInstance().getUserInfo().prefs;
<del> if (prefs == null)
<add> if (prefs == null) {
<ide> prefs = new JSONObject();
<add> Crashlytics.logException(new Exception("Users prefs was null, creating new object"));
<add> }
<ide>
<ide> prefs = updatePref(prefs, members, "channel-hiddenMembers");
<ide> prefs = updatePref(prefs, unread, "channel-disableTrackUnread");
|
|
JavaScript
|
mit
|
c34c42b90082afc57d21100a5936cbb57247f3db
| 0 |
postcss/postcss-messages,postcss/postcss-browser-reporter,jedmao/postcss-browser-reporter
|
var postcss = require('postcss');
var expect = require('chai').expect;
var plugin = require('../');
var warninger = function (css, result) {
result.warn("Here is some warning");
};
var warninger2 = function (css, result) {
result.warn("Here is another warning");
};
var beforeCustom = 'a{ }\n' +
'html::before{\n' +
' text-align: center;\n' +
' content: "Here is some warning"\n' +
'}';
var before = function (opts) {
opts = opts || {};
return ( opts.code || 'a{ }' ) + '\n' +
( opts.selector || 'html::before' ) + '{\n' +
' display: block;\n' +
' z-index: 1000;\n' +
' position: fixed;\n' +
' top: 0;\n' +
' left: 0;\n' +
' right: 0;\n' +
' font-size: .9em;\n' +
' padding: 1.5em 1em 1.5em 4.5em;\n' +
' color: white;\n' +
' background: #DF4F5E url("data:image/svg+xml;charset=utf-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2248px%22%20height%3D%2248px%22%20viewBox%3D%220%200%20512%20512%22%20enable-background%3D%22new%200%200%20512%20512%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpath%20fill%3D%22%23A82734%22%20id%3D%22warning-4-icon%22%20d%3D%22M228.55%2C134.812h54.9v166.5h-54.9V134.812z%20M256%2C385.188c-16.362%2C0-29.626-13.264-29.626-29.625c0-16.362%2C13.264-29.627%2C29.626-29.627c16.361%2C0%2C29.625%2C13.265%2C29.625%2C29.627C285.625%2C371.924%2C272.361%2C385.188%2C256%2C385.188z%20M256%2C90c91.742%2C0%2C166%2C74.245%2C166%2C166c0%2C91.741-74.245%2C166-166%2C166c-91.742%2C0-166-74.245-166-166C90%2C164.259%2C164.245%2C90%2C256%2C90z%20M256%2C50C142.229%2C50%2C50%2C142.229%2C50%2C256s92.229%2C206%2C206%2C206s206-92.229%2C206-206S369.771%2C50%2C256%2C50z%22%2F%3E%3C%2Fsvg%3E") .5em no-repeat, linear-gradient(#DF4F5E, #CE3741);\n' +
' border: 1px solid #C64F4B;\n' +
' border-radius: 3px;\n' +
' box-shadow: inset 0 1px 0 #EB8A93, 0 0 .3em rgba(0,0,0, .5);\n' +
' white-space: pre-wrap;\n' +
' font-family: Menlo, Monaco, monospace;\n' +
' text-shadow: 0 1px #A82734;\n' +
' content: "Here is some warning' + ( opts && opts.content ? opts.content : '' ) + '"\n' +
'}';
};
var test = function (input, output, plugins) {
expect(postcss(plugins).process(input).css).to.eql(output);
};
describe('postcss-messages', function () {
it('displays warning before html', function () {
test('a{ }', before(), [warninger, plugin()]);
});
it('displays warning after html if needed', function () {
var code = 'html::before{ }';
test(code, before({ selector: 'html::after', code: code }), [warninger, plugin()]);
code = 'html:before{ }';
test(code, before({ selector: 'html::after', code: code }), [warninger, plugin()]);
});
it('not displays warning before html if disabled', function () {
test('a{ }', 'a{ }', [warninger, plugin({ disabled: true })]);
});
it('not displays warning before html if no warnings', function () {
test('a{ }', 'a{ }', [plugin()]);
});
it('displays two warnings from two plugins on new lines', function () {
test('a{ }', before({ content: '\\00000aHere is another warning' }), [warninger, warninger2, plugin({})]);
});
it('displays only warnings from plugins before', function () {
test('a{ }', before(), [warninger, plugin({}), warninger2]);
});
it('displays warning before body', function () {
test('a{ }', before({ selector: 'body:before' }), [warninger, plugin({ selector: 'body:before' })]);
});
it('displays warning with custom styles ', function () {
test('a{ }', beforeCustom, [warninger, plugin({ styles: { 'text-align': 'center' } })]);
});
});
|
test/test.js
|
var postcss = require('postcss');
var expect = require('chai').expect;
var plugin = require('../');
var warninger = function (css, result) {
result.warn("Here is some warning");
};
var warninger2 = function (css, result) {
result.warn("Here is another warning");
};
var beforeCustom = 'a{ }\n' +
'html::before{\n' +
' text-align: center;\n' +
' content: "Here is some warning"\n' +
'}';
var before = function (opts) {
opts = opts || {};
return ( opts.code || 'a{ }' ) + '\n' +
( opts.selector || 'html::before' ) + '{\n' +
' display: block;\n' +
' z-index: 1000;\n' +
' position: fixed;\n' +
' top: 0;\n' +
' left: 0;\n' +
' right: 0;\n' +
' font-size: .9em;\n' +
' padding: 1.5em 1em 1.5em 4.5em;\n' +
' color: white;\n' +
' background: #DF4F5E url("data:image/svg+xml;charset=utf-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2248px%22%20height%3D%2248px%22%20viewBox%3D%220%200%20512%20512%22%20enable-background%3D%22new%200%200%20512%20512%22%20xml%3Aspace%3D%22preserve%22%3E%3Cpath%20fill%3D%22%23A82734%22%20id%3D%22warning-4-icon%22%20d%3D%22M228.55%2C134.812h54.9v166.5h-54.9V134.812z%20M256%2C385.188c-16.362%2C0-29.626-13.264-29.626-29.625c0-16.362%2C13.264-29.627%2C29.626-29.627c16.361%2C0%2C29.625%2C13.265%2C29.625%2C29.627C285.625%2C371.924%2C272.361%2C385.188%2C256%2C385.188z%20M256%2C90c91.742%2C0%2C166%2C74.245%2C166%2C166c0%2C91.741-74.245%2C166-166%2C166c-91.742%2C0-166-74.245-166-166C90%2C164.259%2C164.245%2C90%2C256%2C90z%20M256%2C50C142.229%2C50%2C50%2C142.229%2C50%2C256s92.229%2C206%2C206%2C206s206-92.229%2C206-206S369.771%2C50%2C256%2C50z%22%2F%3E%3C%2Fsvg%3E") .5em no-repeat, linear-gradient(#DF4F5E, #CE3741);\n' +
' border: 1px solid #C64F4B;\n' +
' border-radius: 3px;\n' +
' box-shadow: inset 0 1px 0 #EB8A93, 0 0 .3em rgba(0,0,0, .5);\n' +
' white-space: pre;\n' +
' font-family: Menlo, Monaco, monospace;\n' +
' text-shadow: 0 1px #A82734;\n' +
' content: "Here is some warning' + ( opts && opts.content ? opts.content : '' ) + '"\n' +
'}';
};
var test = function (input, output, plugins) {
expect(postcss(plugins).process(input).css).to.eql(output);
};
describe('postcss-messages', function () {
it('displays warning before html', function () {
test('a{ }', before(), [warninger, plugin()]);
});
it('displays warning after html if needed', function () {
var code = 'html::before{ }';
test(code, before({ selector: 'html::after', code: code }), [warninger, plugin()]);
code = 'html:before{ }';
test(code, before({ selector: 'html::after', code: code }), [warninger, plugin()]);
});
it('not displays warning before html if disabled', function () {
test('a{ }', 'a{ }', [warninger, plugin({ disabled: true })]);
});
it('not displays warning before html if no warnings', function () {
test('a{ }', 'a{ }', [plugin()]);
});
it('displays two warnings from two plugins on new lines', function () {
test('a{ }', before({ content: '\\00000aHere is another warning' }), [warninger, warninger2, plugin({})]);
});
it('displays only warnings from plugins before', function () {
test('a{ }', before(), [warninger, plugin({}), warninger2]);
});
it('displays warning before body', function () {
test('a{ }', before({ selector: 'body:before' }), [warninger, plugin({ selector: 'body:before' })]);
});
it('displays warning with custom styles ', function () {
test('a{ }', beforeCustom, [warninger, plugin({ styles: { 'text-align': 'center' } })]);
});
});
|
Fix tests
|
test/test.js
|
Fix tests
|
<ide><path>est/test.js
<ide> ' border: 1px solid #C64F4B;\n' +
<ide> ' border-radius: 3px;\n' +
<ide> ' box-shadow: inset 0 1px 0 #EB8A93, 0 0 .3em rgba(0,0,0, .5);\n' +
<del> ' white-space: pre;\n' +
<add> ' white-space: pre-wrap;\n' +
<ide> ' font-family: Menlo, Monaco, monospace;\n' +
<ide> ' text-shadow: 0 1px #A82734;\n' +
<ide> ' content: "Here is some warning' + ( opts && opts.content ? opts.content : '' ) + '"\n' +
|
|
Java
|
apache-2.0
|
cd2c44ff879cfaba85f8650e4792ae803133988a
| 0 |
redisson/redisson
|
package org.redisson;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.*;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.config.Config;
import org.redisson.connection.balancer.RandomLoadBalancer;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
public class RedissonLockTest extends BaseConcurrentTest {
static class LockWithoutBoolean extends Thread {
private CountDownLatch latch;
private RedissonClient redisson;
public LockWithoutBoolean(String name, CountDownLatch latch, RedissonClient redisson) {
super(name);
this.latch = latch;
this.redisson = redisson;
}
public void run() {
RLock lock = redisson.getLock("lock");
lock.lock(10, TimeUnit.MINUTES);
System.out.println(Thread.currentThread().getName() + " gets lock. and interrupt: " + Thread.currentThread().isInterrupted());
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
latch.countDown();
Thread.currentThread().interrupt();
} finally {
try {
lock.unlock();
} finally {
latch.countDown();
}
}
System.out.println(Thread.currentThread().getName() + " ends.");
}
}
public static class LockThread implements Runnable {
AtomicBoolean hasFails;
RedissonClient redissonClient;
String lockName;
public LockThread(AtomicBoolean hasFails, RedissonClient redissonClient, String lockName) {
this.hasFails = hasFails;
this.redissonClient = redissonClient;
this.lockName = lockName;
}
@Override
public void run() {
RLock lock = redissonClient.getLock(lockName);
try {
boolean bLocked = lock.tryLock(100, -1, TimeUnit.MILLISECONDS);
if (bLocked) {
lock.unlock();
} else {
hasFails.set(true);
}
} catch (Exception ex) {
hasFails.set(true);
}
}
}
@Test
public void testSubscriptionsPerConnection() throws InterruptedException, IOException {
RedisRunner.RedisProcess runner = new RedisRunner()
.port(RedisRunner.findFreePort())
.nosave()
.randomDir()
.run();
Config config = new Config();
config.useSingleServer()
.setSubscriptionConnectionPoolSize(1)
.setSubscriptionConnectionMinimumIdleSize(1)
.setSubscriptionsPerConnection(1)
.setAddress(runner.getRedisServerAddressAndPort());
RedissonClient redisson = Redisson.create(config);
ExecutorService e = Executors.newFixedThreadPool(32);
AtomicInteger errors = new AtomicInteger();
AtomicInteger ops = new AtomicInteger();
for (int i = 0; i < 5000; i++) {
int j = i;
e.submit(() -> {
try {
String lockKey = "lock-" + ThreadLocalRandom.current().nextInt(5);
RLock lock = redisson.getLock(lockKey);
lock.lock();
Thread.sleep(ThreadLocalRandom.current().nextInt(20));
lock.unlock();
ops.incrementAndGet();
} catch (Exception exception) {
exception.printStackTrace();
if(exception instanceof RedisTimeoutException){
return;
}
errors.incrementAndGet();
}
});
}
e.shutdown();
assertThat(e.awaitTermination(150, TimeUnit.SECONDS)).isTrue();
assertThat(errors.get()).isZero();
RedisClientConfig cc = new RedisClientConfig();
cc.setAddress(runner.getRedisServerAddressAndPort());
RedisClient c = RedisClient.create(cc);
RedisConnection ccc = c.connect();
List<String> channels = ccc.sync(RedisCommands.PUBSUB_CHANNELS);
assertThat(channels).isEmpty();
c.shutdown();
redisson.shutdown();
runner.stop();
}
@Test
public void testSinglePubSub() throws IOException, InterruptedException, ExecutionException {
RedisRunner.RedisProcess runner = new RedisRunner()
.port(RedisRunner.findFreePort())
.nosave()
.randomDir()
.run();
Config config = new Config();
config.useSingleServer()
.setAddress(runner.getRedisServerAddressAndPort())
.setSubscriptionConnectionPoolSize(1)
.setSubscriptionsPerConnection(1);
ExecutorService executorService = Executors.newFixedThreadPool(4);
RedissonClient redissonClient = Redisson.create(config);
AtomicBoolean hasFails = new AtomicBoolean();
for (int i = 0; i < 2; i++) {
Future<?> f1 = executorService.submit(new LockThread(hasFails, redissonClient, "Lock1_" + i));
Future<?> f2 = executorService.submit(new LockThread(hasFails, redissonClient, "Lock1_" + i));
Future<?> f3 = executorService.submit(new LockThread(hasFails, redissonClient, "Lock2_" + i));
Future<?> f4 = executorService.submit(new LockThread(hasFails, redissonClient, "Lock2_" + i));
f1.get();
f2.get();
f3.get();
f4.get();
}
assertThat(hasFails).isFalse();
redissonClient.shutdown();
runner.stop();
}
@Test
public void testLockIsNotRenewedAfterInterruptedTryLock() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
RLock lock = redisson.getLock("myLock");
assertThat(lock.isLocked()).isFalse();
Thread thread = new Thread(() -> {
countDownLatch.countDown();
if (!lock.tryLock()) {
return;
}
lock.unlock();
});
thread.start();
countDownLatch.await();
// let the tcp request be sent out
TimeUnit.MILLISECONDS.sleep(5);
thread.interrupt();
TimeUnit.SECONDS.sleep(45);
assertThat(lock.isLocked()).isFalse();
}
@Test
public void testRedisFailed() {
Assertions.assertThrows(WriteRedisConnectionException.class, () -> {
RedisRunner.RedisProcess master = new RedisRunner()
.port(6377)
.nosave()
.randomDir()
.run();
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6377");
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("myLock");
// kill RedisServer while main thread is sleeping.
master.stop();
Thread.sleep(3000);
lock.tryLock(5, 10, TimeUnit.SECONDS);
});
}
@Test
public void testTryLockWait() throws InterruptedException {
testSingleInstanceConcurrency(1, r -> {
RLock lock = r.getLock("lock");
lock.lock();
});
RLock lock = redisson.getLock("lock");
long startTime = System.currentTimeMillis();
lock.tryLock(3, TimeUnit.SECONDS);
assertThat(System.currentTimeMillis() - startTime).isBetween(2990L, 3100L);
}
@Test
public void testLockUninterruptibly() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(2);
Thread thread_1 = new LockWithoutBoolean("thread-1", latch, redisson);
Thread thread_2 = new LockWithoutBoolean("thread-2", latch, redisson);
thread_1.start();
TimeUnit.SECONDS.sleep(1); // let thread-1 get the lock
thread_2.start();
TimeUnit.SECONDS.sleep(1); // let thread_2 waiting for the lock
thread_2.interrupt(); // interrupte the thread-2
boolean res = latch.await(2, TimeUnit.SECONDS);
assertThat(res).isFalse();
}
@Test
public void testForceUnlock() {
RLock lock = redisson.getLock("lock");
lock.lock();
lock.forceUnlock();
Assertions.assertFalse(lock.isLocked());
lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isLocked());
}
@Test
public void testExpire() throws InterruptedException {
RLock lock = redisson.getLock("lock");
lock.lock(2, TimeUnit.SECONDS);
final long startTime = System.currentTimeMillis();
Thread t = new Thread() {
public void run() {
RLock lock1 = redisson.getLock("lock");
lock1.lock();
long spendTime = System.currentTimeMillis() - startTime;
Assertions.assertTrue(spendTime < 2020);
lock1.unlock();
};
};
t.start();
t.join();
assertThatThrownBy(() -> {
lock.unlock();
}).isInstanceOf(IllegalMonitorStateException.class);
}
@Test
public void testInCluster() throws Exception {
RedisRunner master1 = new RedisRunner().port(6890).randomDir().nosave();
RedisRunner master2 = new RedisRunner().port(6891).randomDir().nosave();
RedisRunner master3 = new RedisRunner().port(6892).randomDir().nosave();
RedisRunner slave1 = new RedisRunner().port(6900).randomDir().nosave();
RedisRunner slave2 = new RedisRunner().port(6901).randomDir().nosave();
RedisRunner slave3 = new RedisRunner().port(6902).randomDir().nosave();
ClusterRunner clusterRunner = new ClusterRunner()
.addNode(master1, slave1)
.addNode(master2, slave2)
.addNode(master3, slave3);
ClusterRunner.ClusterProcesses process = clusterRunner.run();
Thread.sleep(5000);
Config config = new Config();
config.useClusterServers()
.setLoadBalancer(new RandomLoadBalancer())
.addNodeAddress(process.getNodes().stream().findAny().get().getRedisServerAddressAndPort());
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("myLock");
lock.lock();
assertThat(lock.isLocked()).isTrue();
lock.unlock();
assertThat(lock.isLocked()).isFalse();
redisson.shutdown();
process.shutdown();
}
@Test
public void testAutoExpire() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
RedissonClient r = createInstance();
Thread t = new Thread() {
@Override
public void run() {
RLock lock = r.getLock("lock");
lock.lock();
latch.countDown();
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
Assertions.assertTrue(latch.await(1, TimeUnit.SECONDS));
RLock lock = redisson.getLock("lock");
t.join();
r.shutdown();
await().atMost(redisson.getConfig().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS).until(() -> !lock.isLocked());
}
@Test
public void testGetHoldCount() {
RLock lock = redisson.getLock("lock");
Assertions.assertEquals(0, lock.getHoldCount());
lock.lock();
Assertions.assertEquals(1, lock.getHoldCount());
lock.unlock();
Assertions.assertEquals(0, lock.getHoldCount());
lock.lock();
lock.lock();
Assertions.assertEquals(2, lock.getHoldCount());
lock.unlock();
Assertions.assertEquals(1, lock.getHoldCount());
lock.unlock();
Assertions.assertEquals(0, lock.getHoldCount());
}
@Test
public void testIsHeldByCurrentThreadOtherThread() throws InterruptedException {
RLock lock = redisson.getLock("lock");
lock.lock();
Thread t = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isHeldByCurrentThread());
};
};
t.start();
t.join();
lock.unlock();
Thread t2 = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isHeldByCurrentThread());
};
};
t2.start();
t2.join();
}
@Test
public void testIsHeldByCurrentThread() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isHeldByCurrentThread());
lock.lock();
Assertions.assertTrue(lock.isHeldByCurrentThread());
lock.unlock();
Assertions.assertFalse(lock.isHeldByCurrentThread());
}
@Test
public void testIsLockedOtherThread() throws InterruptedException {
RLock lock = redisson.getLock("lock");
lock.lock();
Thread t = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
Assertions.assertTrue(lock.isLocked());
};
};
t.start();
t.join();
lock.unlock();
Thread t2 = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isLocked());
};
};
t2.start();
t2.join();
}
@Test
public void testIsLocked() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isLocked());
lock.lock();
Assertions.assertTrue(lock.isLocked());
lock.unlock();
Assertions.assertFalse(lock.isLocked());
}
@Test
public void testUnlockFail() {
Assertions.assertThrows(IllegalMonitorStateException.class, () -> {
RLock lock = redisson.getLock("lock");
Thread t = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
lock.lock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
};
};
t.start();
t.join(400);
try {
lock.unlock();
} catch (IllegalMonitorStateException e) {
t.join();
throw e;
}
});
}
@Test
public void testLockUnlock() {
Lock lock = redisson.getLock("lock1");
lock.lock();
lock.unlock();
lock.lock();
lock.unlock();
}
@Test
public void testReentrancy() throws InterruptedException {
Lock lock = redisson.getLock("lock1");
Assertions.assertTrue(lock.tryLock());
Assertions.assertTrue(lock.tryLock());
lock.unlock();
// next row for test renew expiration tisk.
//Thread.currentThread().sleep(TimeUnit.SECONDS.toMillis(RedissonLock.LOCK_EXPIRATION_INTERVAL_SECONDS*2));
Thread thread1 = new Thread() {
@Override
public void run() {
RLock lock1 = redisson.getLock("lock1");
Assertions.assertFalse(lock1.tryLock());
}
};
thread1.start();
thread1.join();
lock.unlock();
}
@Test
public void testConcurrency_SingleInstance() throws InterruptedException {
final AtomicInteger lockedCounter = new AtomicInteger();
int iterations = 15;
testSingleInstanceConcurrency(iterations, r -> {
Lock lock = r.getLock("testConcurrency_SingleInstance");
lock.lock();
lockedCounter.incrementAndGet();
lock.unlock();
});
Assertions.assertEquals(iterations, lockedCounter.get());
}
@Test
public void testConcurrencyLoop_MultiInstance() throws InterruptedException {
final int iterations = 100;
final AtomicInteger lockedCounter = new AtomicInteger();
testMultiInstanceConcurrency(16, r -> {
for (int i = 0; i < iterations; i++) {
r.getLock("testConcurrency_MultiInstance1").lock();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
lockedCounter.incrementAndGet();
r.getLock("testConcurrency_MultiInstance1").unlock();
}
});
Assertions.assertEquals(16 * iterations, lockedCounter.get());
}
@Test
public void testConcurrency_MultiInstance() throws InterruptedException {
int iterations = 100;
final AtomicInteger lockedCounter = new AtomicInteger();
testMultiInstanceConcurrency(iterations, r -> {
Lock lock = r.getLock("testConcurrency_MultiInstance2");
lock.lock();
lockedCounter.incrementAndGet();
lock.unlock();
});
Assertions.assertEquals(iterations, lockedCounter.get());
}
}
|
redisson/src/test/java/org/redisson/RedissonLockTest.java
|
package org.redisson;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.redisson.client.RedisClientConfig;
import org.redisson.client.RedisConnection;
import org.redisson.client.WriteRedisConnectionException;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.config.Config;
import org.redisson.connection.balancer.RandomLoadBalancer;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
public class RedissonLockTest extends BaseConcurrentTest {
static class LockWithoutBoolean extends Thread {
private CountDownLatch latch;
private RedissonClient redisson;
public LockWithoutBoolean(String name, CountDownLatch latch, RedissonClient redisson) {
super(name);
this.latch = latch;
this.redisson = redisson;
}
public void run() {
RLock lock = redisson.getLock("lock");
lock.lock(10, TimeUnit.MINUTES);
System.out.println(Thread.currentThread().getName() + " gets lock. and interrupt: " + Thread.currentThread().isInterrupted());
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
latch.countDown();
Thread.currentThread().interrupt();
} finally {
try {
lock.unlock();
} finally {
latch.countDown();
}
}
System.out.println(Thread.currentThread().getName() + " ends.");
}
}
public static class LockThread implements Runnable {
AtomicBoolean hasFails;
RedissonClient redissonClient;
String lockName;
public LockThread(AtomicBoolean hasFails, RedissonClient redissonClient, String lockName) {
this.hasFails = hasFails;
this.redissonClient = redissonClient;
this.lockName = lockName;
}
@Override
public void run() {
RLock lock = redissonClient.getLock(lockName);
try {
boolean bLocked = lock.tryLock(100, -1, TimeUnit.MILLISECONDS);
if (bLocked) {
lock.unlock();
} else {
hasFails.set(true);
}
} catch (Exception ex) {
hasFails.set(true);
}
}
}
@Test
public void testSubscriptionsPerConnection() throws InterruptedException, IOException {
RedisRunner.RedisProcess runner = new RedisRunner()
.port(RedisRunner.findFreePort())
.nosave()
.randomDir()
.run();
Config config = new Config();
config.useSingleServer()
.setSubscriptionConnectionPoolSize(1)
.setSubscriptionConnectionMinimumIdleSize(1)
.setSubscriptionsPerConnection(5)
.setAddress(runner.getRedisServerAddressAndPort());
RedissonClient redisson = Redisson.create(config);
ExecutorService e = Executors.newFixedThreadPool(32);
AtomicInteger errors = new AtomicInteger();
for (int i = 0; i < 100; i++) {
e.submit(() -> {
try {
String lockKey = "lock-" + ThreadLocalRandom.current().nextInt(5);
RLock lock = redisson.getLock(lockKey);
lock.lock();
Thread.sleep(ThreadLocalRandom.current().nextInt(20));
lock.unlock();
} catch (Exception exception){
exception.printStackTrace();
errors.incrementAndGet();
}
});
}
e.shutdown();
assertThat(e.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
assertThat(errors.get()).isZero();
RedisClientConfig cc = new RedisClientConfig();
cc.setAddress(runner.getRedisServerAddressAndPort());
RedisClient c = RedisClient.create(cc);
RedisConnection ccc = c.connect();
List<String> channels = ccc.sync(RedisCommands.PUBSUB_CHANNELS);
assertThat(channels).isEmpty();
c.shutdown();
redisson.shutdown();
runner.stop();
}
@Test
public void testSinglePubSub() throws IOException, InterruptedException, ExecutionException {
RedisRunner.RedisProcess runner = new RedisRunner()
.port(RedisRunner.findFreePort())
.nosave()
.randomDir()
.run();
Config config = new Config();
config.useSingleServer()
.setAddress(runner.getRedisServerAddressAndPort())
.setSubscriptionConnectionPoolSize(1)
.setSubscriptionsPerConnection(1);
ExecutorService executorService = Executors.newFixedThreadPool(4);
RedissonClient redissonClient = Redisson.create(config);
AtomicBoolean hasFails = new AtomicBoolean();
for (int i = 0; i < 2; i++) {
Future<?> f1 = executorService.submit(new LockThread(hasFails, redissonClient, "Lock1_" + i));
Future<?> f2 = executorService.submit(new LockThread(hasFails, redissonClient, "Lock1_" + i));
Future<?> f3 = executorService.submit(new LockThread(hasFails, redissonClient, "Lock2_" + i));
Future<?> f4 = executorService.submit(new LockThread(hasFails, redissonClient, "Lock2_" + i));
f1.get();
f2.get();
f3.get();
f4.get();
}
assertThat(hasFails).isFalse();
redissonClient.shutdown();
runner.stop();
}
@Test
public void testLockIsNotRenewedAfterInterruptedTryLock() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
RLock lock = redisson.getLock("myLock");
assertThat(lock.isLocked()).isFalse();
Thread thread = new Thread(() -> {
countDownLatch.countDown();
if (!lock.tryLock()) {
return;
}
lock.unlock();
});
thread.start();
countDownLatch.await();
// let the tcp request be sent out
TimeUnit.MILLISECONDS.sleep(5);
thread.interrupt();
TimeUnit.SECONDS.sleep(45);
assertThat(lock.isLocked()).isFalse();
}
@Test
public void testRedisFailed() {
Assertions.assertThrows(WriteRedisConnectionException.class, () -> {
RedisRunner.RedisProcess master = new RedisRunner()
.port(6377)
.nosave()
.randomDir()
.run();
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6377");
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("myLock");
// kill RedisServer while main thread is sleeping.
master.stop();
Thread.sleep(3000);
lock.tryLock(5, 10, TimeUnit.SECONDS);
});
}
@Test
public void testTryLockWait() throws InterruptedException {
testSingleInstanceConcurrency(1, r -> {
RLock lock = r.getLock("lock");
lock.lock();
});
RLock lock = redisson.getLock("lock");
long startTime = System.currentTimeMillis();
lock.tryLock(3, TimeUnit.SECONDS);
assertThat(System.currentTimeMillis() - startTime).isBetween(2990L, 3100L);
}
@Test
public void testLockUninterruptibly() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(2);
Thread thread_1 = new LockWithoutBoolean("thread-1", latch, redisson);
Thread thread_2 = new LockWithoutBoolean("thread-2", latch, redisson);
thread_1.start();
TimeUnit.SECONDS.sleep(1); // let thread-1 get the lock
thread_2.start();
TimeUnit.SECONDS.sleep(1); // let thread_2 waiting for the lock
thread_2.interrupt(); // interrupte the thread-2
boolean res = latch.await(2, TimeUnit.SECONDS);
assertThat(res).isFalse();
}
@Test
public void testForceUnlock() {
RLock lock = redisson.getLock("lock");
lock.lock();
lock.forceUnlock();
Assertions.assertFalse(lock.isLocked());
lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isLocked());
}
@Test
public void testExpire() throws InterruptedException {
RLock lock = redisson.getLock("lock");
lock.lock(2, TimeUnit.SECONDS);
final long startTime = System.currentTimeMillis();
Thread t = new Thread() {
public void run() {
RLock lock1 = redisson.getLock("lock");
lock1.lock();
long spendTime = System.currentTimeMillis() - startTime;
Assertions.assertTrue(spendTime < 2020);
lock1.unlock();
};
};
t.start();
t.join();
assertThatThrownBy(() -> {
lock.unlock();
}).isInstanceOf(IllegalMonitorStateException.class);
}
@Test
public void testInCluster() throws Exception {
RedisRunner master1 = new RedisRunner().port(6890).randomDir().nosave();
RedisRunner master2 = new RedisRunner().port(6891).randomDir().nosave();
RedisRunner master3 = new RedisRunner().port(6892).randomDir().nosave();
RedisRunner slave1 = new RedisRunner().port(6900).randomDir().nosave();
RedisRunner slave2 = new RedisRunner().port(6901).randomDir().nosave();
RedisRunner slave3 = new RedisRunner().port(6902).randomDir().nosave();
ClusterRunner clusterRunner = new ClusterRunner()
.addNode(master1, slave1)
.addNode(master2, slave2)
.addNode(master3, slave3);
ClusterRunner.ClusterProcesses process = clusterRunner.run();
Thread.sleep(5000);
Config config = new Config();
config.useClusterServers()
.setLoadBalancer(new RandomLoadBalancer())
.addNodeAddress(process.getNodes().stream().findAny().get().getRedisServerAddressAndPort());
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("myLock");
lock.lock();
assertThat(lock.isLocked()).isTrue();
lock.unlock();
assertThat(lock.isLocked()).isFalse();
redisson.shutdown();
process.shutdown();
}
@Test
public void testAutoExpire() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
RedissonClient r = createInstance();
Thread t = new Thread() {
@Override
public void run() {
RLock lock = r.getLock("lock");
lock.lock();
latch.countDown();
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
Assertions.assertTrue(latch.await(1, TimeUnit.SECONDS));
RLock lock = redisson.getLock("lock");
t.join();
r.shutdown();
await().atMost(redisson.getConfig().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS).until(() -> !lock.isLocked());
}
@Test
public void testGetHoldCount() {
RLock lock = redisson.getLock("lock");
Assertions.assertEquals(0, lock.getHoldCount());
lock.lock();
Assertions.assertEquals(1, lock.getHoldCount());
lock.unlock();
Assertions.assertEquals(0, lock.getHoldCount());
lock.lock();
lock.lock();
Assertions.assertEquals(2, lock.getHoldCount());
lock.unlock();
Assertions.assertEquals(1, lock.getHoldCount());
lock.unlock();
Assertions.assertEquals(0, lock.getHoldCount());
}
@Test
public void testIsHeldByCurrentThreadOtherThread() throws InterruptedException {
RLock lock = redisson.getLock("lock");
lock.lock();
Thread t = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isHeldByCurrentThread());
};
};
t.start();
t.join();
lock.unlock();
Thread t2 = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isHeldByCurrentThread());
};
};
t2.start();
t2.join();
}
@Test
public void testIsHeldByCurrentThread() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isHeldByCurrentThread());
lock.lock();
Assertions.assertTrue(lock.isHeldByCurrentThread());
lock.unlock();
Assertions.assertFalse(lock.isHeldByCurrentThread());
}
@Test
public void testIsLockedOtherThread() throws InterruptedException {
RLock lock = redisson.getLock("lock");
lock.lock();
Thread t = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
Assertions.assertTrue(lock.isLocked());
};
};
t.start();
t.join();
lock.unlock();
Thread t2 = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isLocked());
};
};
t2.start();
t2.join();
}
@Test
public void testIsLocked() {
RLock lock = redisson.getLock("lock");
Assertions.assertFalse(lock.isLocked());
lock.lock();
Assertions.assertTrue(lock.isLocked());
lock.unlock();
Assertions.assertFalse(lock.isLocked());
}
@Test
public void testUnlockFail() {
Assertions.assertThrows(IllegalMonitorStateException.class, () -> {
RLock lock = redisson.getLock("lock");
Thread t = new Thread() {
public void run() {
RLock lock = redisson.getLock("lock");
lock.lock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lock.unlock();
};
};
t.start();
t.join(400);
try {
lock.unlock();
} catch (IllegalMonitorStateException e) {
t.join();
throw e;
}
});
}
@Test
public void testLockUnlock() {
Lock lock = redisson.getLock("lock1");
lock.lock();
lock.unlock();
lock.lock();
lock.unlock();
}
@Test
public void testReentrancy() throws InterruptedException {
Lock lock = redisson.getLock("lock1");
Assertions.assertTrue(lock.tryLock());
Assertions.assertTrue(lock.tryLock());
lock.unlock();
// next row for test renew expiration tisk.
//Thread.currentThread().sleep(TimeUnit.SECONDS.toMillis(RedissonLock.LOCK_EXPIRATION_INTERVAL_SECONDS*2));
Thread thread1 = new Thread() {
@Override
public void run() {
RLock lock1 = redisson.getLock("lock1");
Assertions.assertFalse(lock1.tryLock());
}
};
thread1.start();
thread1.join();
lock.unlock();
}
@Test
public void testConcurrency_SingleInstance() throws InterruptedException {
final AtomicInteger lockedCounter = new AtomicInteger();
int iterations = 15;
testSingleInstanceConcurrency(iterations, r -> {
Lock lock = r.getLock("testConcurrency_SingleInstance");
lock.lock();
lockedCounter.incrementAndGet();
lock.unlock();
});
Assertions.assertEquals(iterations, lockedCounter.get());
}
@Test
public void testConcurrencyLoop_MultiInstance() throws InterruptedException {
final int iterations = 100;
final AtomicInteger lockedCounter = new AtomicInteger();
testMultiInstanceConcurrency(16, r -> {
for (int i = 0; i < iterations; i++) {
r.getLock("testConcurrency_MultiInstance1").lock();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
lockedCounter.incrementAndGet();
r.getLock("testConcurrency_MultiInstance1").unlock();
}
});
Assertions.assertEquals(16 * iterations, lockedCounter.get());
}
@Test
public void testConcurrency_MultiInstance() throws InterruptedException {
int iterations = 100;
final AtomicInteger lockedCounter = new AtomicInteger();
testMultiInstanceConcurrency(iterations, r -> {
Lock lock = r.getLock("testConcurrency_MultiInstance2");
lock.lock();
lockedCounter.incrementAndGet();
lock.unlock();
});
Assertions.assertEquals(iterations, lockedCounter.get());
}
}
|
Fixed - pubsub channel isn't released if subscription timeout occurred. #4064
|
redisson/src/test/java/org/redisson/RedissonLockTest.java
|
Fixed - pubsub channel isn't released if subscription timeout occurred. #4064
|
<ide><path>edisson/src/test/java/org/redisson/RedissonLockTest.java
<ide> import org.junit.jupiter.api.Test;
<ide> import org.redisson.api.RLock;
<ide> import org.redisson.api.RedissonClient;
<del>import org.redisson.client.RedisClient;
<del>import org.redisson.client.RedisClientConfig;
<del>import org.redisson.client.RedisConnection;
<del>import org.redisson.client.WriteRedisConnectionException;
<add>import org.redisson.client.*;
<ide> import org.redisson.client.protocol.RedisCommands;
<ide> import org.redisson.config.Config;
<ide> import org.redisson.connection.balancer.RandomLoadBalancer;
<ide> config.useSingleServer()
<ide> .setSubscriptionConnectionPoolSize(1)
<ide> .setSubscriptionConnectionMinimumIdleSize(1)
<del> .setSubscriptionsPerConnection(5)
<add> .setSubscriptionsPerConnection(1)
<ide> .setAddress(runner.getRedisServerAddressAndPort());
<ide>
<ide> RedissonClient redisson = Redisson.create(config);
<ide> ExecutorService e = Executors.newFixedThreadPool(32);
<ide> AtomicInteger errors = new AtomicInteger();
<del> for (int i = 0; i < 100; i++) {
<add> AtomicInteger ops = new AtomicInteger();
<add> for (int i = 0; i < 5000; i++) {
<add> int j = i;
<ide> e.submit(() -> {
<ide> try {
<ide> String lockKey = "lock-" + ThreadLocalRandom.current().nextInt(5);
<ide> lock.lock();
<ide> Thread.sleep(ThreadLocalRandom.current().nextInt(20));
<ide> lock.unlock();
<del> } catch (Exception exception){
<add> ops.incrementAndGet();
<add> } catch (Exception exception) {
<ide> exception.printStackTrace();
<add> if(exception instanceof RedisTimeoutException){
<add> return;
<add> }
<ide> errors.incrementAndGet();
<ide> }
<ide> });
<ide> }
<ide>
<ide> e.shutdown();
<del> assertThat(e.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
<add> assertThat(e.awaitTermination(150, TimeUnit.SECONDS)).isTrue();
<ide> assertThat(errors.get()).isZero();
<ide>
<ide> RedisClientConfig cc = new RedisClientConfig();
|
|
JavaScript
|
mit
|
16d87a0035033cc4aad18c8bafe11851ebbaa07c
| 0 |
siimple/siimple-elements
|
import h from '../hyperscript.js';
import colors from '../colors.js';
import SiimpleComponent from '../index.js';
//Navbar sizes
var navbar_sizes = ['small', 'large', 'fluid'];
//Navbar default class
export class SiimpleNavbar extends SiimpleComponent
{
//Render the navbar element
render()
{
//Save the props
var props = this.props;
//Initialize the class list
var class_list = [ 'siimple-navbar' ];
//Check the color
if(typeof props.color === 'string' && colors.list.indexOf(props.color.toLowerCase()) !== -1)
{
//Add the color class
class_list.push('siimple-navbar--' + props.color.toLowerCase());
}
//Check the size
if(typeof props.size === 'string' && navbar_sizes.indexOf(props.size.toLowerCase()) !== -1)
{
//Add the size class
class_list.push('siimple-navbar--' + props.size.toLowerCase());
}
//Render the navbar
return h.div({ className: class_list }, props.children);
}
}
//Navbar default props
SiimpleNavbar.defaultProps = { color: null, size: null };
//Navbar title element
export class SiimpleNavbarTitle extends SiimpleComponent
{
//Constructor
constructor(props)
{
//Call the super method
super(props);
//Bind the handle click
this.handleClick = this.handleClick.bind(this);
}
//Handle the title click event
handleClick(e)
{
//Check the onclick listener
if(typeof this.props.onClick === 'function')
{
//Call the onclick listener
this.props.onClick.call(null, e);
}
}
//Render the navbar title element
render()
{
//Initialize the title element props
var props = { className: 'siimple-navbar-title', style: { align: 'left' }, onClick: this.handleClick };
//Render the navbar title
return h.div(props, this.props.children);
}
}
//Navbar title default props
SiimpleNavbarTitle.defaultProps = { onClick: null };
//Navbar link element
export class SiimpleNavbarLink extends SiimpleComponent
{
//Constructor
constructor(props)
{
//Call the super method
super(props);
//Bind the handle click
this.handleClick = this.handleClick.bind(this);
}
//Handle the link click event
handleClick(e)
{
//Check the onclick listener
if(typeof this.props.onClick === 'function')
{
//Call the onclick listener
this.props.onClick.call(null, e);
}
}
//Render the navbar title element
render()
{
//Initialize the link element props
var props = { className: 'siimple-navbar-link', style: { align: 'right' }, onClick: this.handleClick };
//Render the navbar link
return h.div(props, this.props.children);
}
}
//Navbar link default props
SiimpleNavbarLink.defaultProps = { onClick: null };
|
src/layout/navbar.js
|
import h from '../hyperscript.js';
import colors from '../colors.js';
import SiimpleComponent from '../index.js';
//Navbar sizes
var navbar_sizes = ['small', 'large', 'fluid'];
//Navbar default class
export class SiimpleNavbar extends SiimpleComponent
{
//Render the navbar element
render()
{
//Save the props
var props = this.props;
//Initialize the class list
var class_list = [ 'siimple-navbar' ];
//Check the color
if(typeof props.color === 'string' && colors.list.indexOf(props.color.toLowerCase()) !== -1)
{
//Add the color class
class_list.push('siimple-navbar--' + props.color.toLowerCase());
}
//Check the size
if(typeof props.size === 'string' && navbar_sizes.indexOf(props.size.toLowerCase()) !== -1)
{
//Add the size class
class_list.push('siimple-navbar--' + props.size.toLowerCase());
}
//Render the navbar
return h.div({ className: class_list }, props.children);
}
}
//Navbar default props
SiimpleNavbar.defaultProps = { color: null, size: null };
//Navbar title element
export class SiimpleNavbarTitle extends SiimpleComponent
{
//Constructor
constructor(props)
{
//Call the super method
super(props);
//Bind the handle click
this.handleClick = this.handleClick.bind(this);
}
//Handle the title click event
handleClick(e)
{
//Check the onclick listener
if(typeof this.props.onClick === 'function')
{
//Call the onclick listener
this.props.onClick.call(null, e);
}
}
//Render the navbar title element
render()
{
//Initialize the title element props
var props = { className: 'siimple-navbar-title', style: { align: 'left' }, onClick: this.handleClick };
//Render the navbar title
return h.div(props, this.props.children);
}
}
//Navbar title default props
SiimpleNavbarTitle.defaultProps = { onClick: null };
|
src/layout/navbar.js: added navbar link component
|
src/layout/navbar.js
|
src/layout/navbar.js: added navbar link component
|
<ide><path>rc/layout/navbar.js
<ide>
<ide> //Navbar title default props
<ide> SiimpleNavbarTitle.defaultProps = { onClick: null };
<add>
<add>//Navbar link element
<add>export class SiimpleNavbarLink extends SiimpleComponent
<add>{
<add> //Constructor
<add> constructor(props)
<add> {
<add> //Call the super method
<add> super(props);
<add>
<add> //Bind the handle click
<add> this.handleClick = this.handleClick.bind(this);
<add> }
<add>
<add> //Handle the link click event
<add> handleClick(e)
<add> {
<add> //Check the onclick listener
<add> if(typeof this.props.onClick === 'function')
<add> {
<add> //Call the onclick listener
<add> this.props.onClick.call(null, e);
<add> }
<add> }
<add>
<add> //Render the navbar title element
<add> render()
<add> {
<add> //Initialize the link element props
<add> var props = { className: 'siimple-navbar-link', style: { align: 'right' }, onClick: this.handleClick };
<add>
<add> //Render the navbar link
<add> return h.div(props, this.props.children);
<add> }
<add>}
<add>
<add>//Navbar link default props
<add>SiimpleNavbarLink.defaultProps = { onClick: null };
|
|
Java
|
apache-2.0
|
f64439533ab6900514f570cfac060bfcc4307c1c
| 0 |
unidev-polydata/polydata-insights,unidev-polydata/polydata-insights
|
package com.unidev.polyinsights.model;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Time interval used for queries
*/
public enum TimeInterval {
DAY(TimeUnit.DAYS.toMillis(1)), WEEK(TimeUnit.DAYS.toMillis(7)), MONTH(TimeUnit.DAYS.toMillis(30)), YEAR(TimeUnit.DAYS.toMillis(365));
public Date fetchDateFrom(Date date) {
return new Date(date.getTime() - interval);
}
private long interval;
TimeInterval(long interval) {
this.interval = interval;
}
public long getInterval() {
return interval;
}
}
|
poly-insights/src/main/java/com/unidev/polyinsights/model/TimeInterval.java
|
package com.unidev.polyinsights.model;
/**
* Time interval used for queries
*/
public enum TimeInterval {
DAY, WEEK, MONTH, YEAR
}
|
Added time interval in ms
|
poly-insights/src/main/java/com/unidev/polyinsights/model/TimeInterval.java
|
Added time interval in ms
|
<ide><path>oly-insights/src/main/java/com/unidev/polyinsights/model/TimeInterval.java
<ide> package com.unidev.polyinsights.model;
<add>
<add>import java.util.Date;
<add>import java.util.concurrent.TimeUnit;
<ide>
<ide> /**
<ide> * Time interval used for queries
<ide> */
<ide> public enum TimeInterval {
<ide>
<del> DAY, WEEK, MONTH, YEAR
<add> DAY(TimeUnit.DAYS.toMillis(1)), WEEK(TimeUnit.DAYS.toMillis(7)), MONTH(TimeUnit.DAYS.toMillis(30)), YEAR(TimeUnit.DAYS.toMillis(365));
<add>
<add> public Date fetchDateFrom(Date date) {
<add> return new Date(date.getTime() - interval);
<add> }
<add>
<add> private long interval;
<add>
<add> TimeInterval(long interval) {
<add> this.interval = interval;
<add> }
<add>
<add> public long getInterval() {
<add> return interval;
<add> }
<ide>
<ide> }
|
|
Java
|
lgpl-2.1
|
82d896a35e08be5712bdc15bdb93e5d4fc0ddd46
| 0 |
MinecraftForge/FML
|
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.asm.transformers;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PROTECTED;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.io.LineProcessor;
import com.google.common.io.Resources;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
public class AccessTransformer implements IClassTransformer
{
private static final boolean DEBUG = false;
private class Modifier
{
public String name = "";
public String desc = "";
public int oldAccess = 0;
public int newAccess = 0;
public int targetAccess = 0;
public boolean changeFinal = false;
public boolean markFinal = false;
protected boolean modifyClassVisibility;
private void setTargetAccess(String name)
{
if (name.startsWith("public")) targetAccess = ACC_PUBLIC;
else if (name.startsWith("private")) targetAccess = ACC_PRIVATE;
else if (name.startsWith("protected")) targetAccess = ACC_PROTECTED;
if (name.endsWith("-f"))
{
changeFinal = true;
markFinal = false;
}
else if (name.endsWith("+f"))
{
changeFinal = true;
markFinal = true;
}
}
}
private Multimap<String, Modifier> modifiers = ArrayListMultimap.create();
public AccessTransformer() throws IOException
{
this("fml_at.cfg");
}
protected AccessTransformer(String rulesFile) throws IOException
{
readMapFile(rulesFile);
}
private void readMapFile(String rulesFile) throws IOException
{
File file = new File(rulesFile);
URL rulesResource;
if (file.exists())
{
rulesResource = file.toURI().toURL();
}
else
{
rulesResource = Resources.getResource(rulesFile);
}
Resources.readLines(rulesResource, Charsets.UTF_8, new LineProcessor<Void>()
{
@Override
public Void getResult()
{
return null;
}
@Override
public boolean processLine(String input) throws IOException
{
String line = Iterables.getFirst(Splitter.on('#').limit(2).split(input), "").trim();
if (line.length()==0)
{
return true;
}
List<String> parts = Lists.newArrayList(Splitter.on(" ").trimResults().split(line));
if (parts.size()>2)
{
throw new RuntimeException("Invalid config file line "+ input);
}
Modifier m = new Modifier();
m.setTargetAccess(parts.get(0));
List<String> descriptor = Lists.newArrayList(Splitter.on(".").trimResults().split(parts.get(1)));
if (descriptor.size() == 1)
{
m.modifyClassVisibility = true;
}
else
{
String nameReference = descriptor.get(1);
int parenIdx = nameReference.indexOf('(');
if (parenIdx>0)
{
m.desc = nameReference.substring(parenIdx);
m.name = nameReference.substring(0,parenIdx);
}
else
{
m.name = nameReference;
}
}
modifiers.put(descriptor.get(0).replace('/', '.'), m);
return true;
}
});
System.out.printf("Loaded %d rules from AccessTransformer config file %s\n", modifiers.size(), rulesFile);
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
if (bytes == null) { return null; }
boolean makeAllPublic = FMLDeobfuscatingRemapper.INSTANCE.isRemappedClass(name);
if (DEBUG)
{
FMLRelaunchLog.fine("Considering all methods and fields on %s (%s): %b\n", name, transformedName, makeAllPublic);
}
if (!makeAllPublic && !modifiers.containsKey(name)) { return bytes; }
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
if (makeAllPublic)
{
// class
Modifier m = new Modifier();
m.targetAccess = ACC_PUBLIC;
m.modifyClassVisibility = true;
modifiers.put(name,m);
// fields
m = new Modifier();
m.targetAccess = ACC_PUBLIC;
m.name = "*";
modifiers.put(name,m);
// methods
m = new Modifier();
m.targetAccess = ACC_PUBLIC;
m.name = "*";
m.desc = "<dummy>";
modifiers.put(name,m);
if (DEBUG)
{
System.out.printf("Injected all public modifiers for %s (%s)\n", name, transformedName);
}
}
Collection<Modifier> mods = modifiers.get(name);
for (Modifier m : mods)
{
if (m.modifyClassVisibility)
{
classNode.access = getFixedAccess(classNode.access, m);
if (DEBUG)
{
System.out.println(String.format("Class: %s %s -> %s", name, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
continue;
}
if (m.desc.isEmpty())
{
for (FieldNode n : classNode.fields)
{
if (n.name.equals(m.name) || m.name.equals("*"))
{
n.access = getFixedAccess(n.access, m);
if (DEBUG)
{
System.out.println(String.format("Field: %s.%s %s -> %s", name, n.name, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
if (!m.name.equals("*"))
{
break;
}
}
}
}
else
{
for (MethodNode n : classNode.methods)
{
if ((n.name.equals(m.name) && n.desc.equals(m.desc)) || m.name.equals("*"))
{
n.access = getFixedAccess(n.access, m);
if (DEBUG)
{
System.out.println(String.format("Method: %s.%s%s %s -> %s", name, n.name, n.desc, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
if (!m.name.equals("*"))
{
break;
}
}
}
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
private String toBinary(int num)
{
return String.format("%16s", Integer.toBinaryString(num)).replace(' ', '0');
}
private int getFixedAccess(int access, Modifier target)
{
target.oldAccess = access;
int t = target.targetAccess;
int ret = (access & ~7);
switch (access & 7)
{
case ACC_PRIVATE:
ret |= t;
break;
case 0: // default
ret |= (t != ACC_PRIVATE ? t : 0 /* default */);
break;
case ACC_PROTECTED:
ret |= (t != ACC_PRIVATE && t != 0 /* default */? t : ACC_PROTECTED);
break;
case ACC_PUBLIC:
ret |= (t != ACC_PRIVATE && t != 0 /* default */&& t != ACC_PROTECTED ? t : ACC_PUBLIC);
break;
default:
throw new RuntimeException("The fuck?");
}
// Clear the "final" marker on fields only if specified in control field
if (target.changeFinal)
{
if (target.markFinal)
{
ret |= ACC_FINAL;
}
else
{
ret &= ~ACC_FINAL;
}
}
target.newAccess = ret;
return ret;
}
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Usage: AccessTransformer <JarPath> <MapFile> [MapFile2]... ");
System.exit(1);
}
boolean hasTransformer = false;
AccessTransformer[] trans = new AccessTransformer[args.length - 1];
for (int x = 1; x < args.length; x++)
{
try
{
trans[x - 1] = new AccessTransformer(args[x]);
hasTransformer = true;
}
catch (IOException e)
{
System.out.println("Could not read Transformer Map: " + args[x]);
e.printStackTrace();
}
}
if (!hasTransformer)
{
System.out.println("Culd not find a valid transformer to perform");
System.exit(1);
}
File orig = new File(args[0]);
File temp = new File(args[0] + ".ATBack");
if (!orig.exists() && !temp.exists())
{
System.out.println("Could not find target jar: " + orig);
System.exit(1);
}
if (!orig.renameTo(temp))
{
System.out.println("Could not rename file: " + orig + " -> " + temp);
System.exit(1);
}
try
{
processJar(temp, orig, trans);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
if (!temp.delete())
{
System.out.println("Could not delete temp file: " + temp);
}
}
private static void processJar(File inFile, File outFile, AccessTransformer[] transformers) throws IOException
{
ZipInputStream inJar = null;
ZipOutputStream outJar = null;
try
{
try
{
inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open input file: " + e.getMessage());
}
try
{
outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open output file: " + e.getMessage());
}
ZipEntry entry;
while ((entry = inJar.getNextEntry()) != null)
{
if (entry.isDirectory())
{
outJar.putNextEntry(entry);
continue;
}
byte[] data = new byte[4096];
ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();
int len;
do
{
len = inJar.read(data);
if (len > 0)
{
entryBuffer.write(data, 0, len);
}
}
while (len != -1);
byte[] entryData = entryBuffer.toByteArray();
String entryName = entry.getName();
if (entryName.endsWith(".class") && !entryName.startsWith("."))
{
ClassNode cls = new ClassNode();
ClassReader rdr = new ClassReader(entryData);
rdr.accept(cls, 0);
String name = cls.name.replace('/', '.').replace('\\', '.');
for (AccessTransformer trans : transformers)
{
entryData = trans.transform(name, name, entryData);
}
}
ZipEntry newEntry = new ZipEntry(entryName);
outJar.putNextEntry(newEntry);
outJar.write(entryData);
}
}
finally
{
if (outJar != null)
{
try
{
outJar.close();
}
catch (IOException e)
{
}
}
if (inJar != null)
{
try
{
inJar.close();
}
catch (IOException e)
{
}
}
}
}
public void ensurePublicAccessFor(String modClazzName)
{
Modifier m = new Modifier();
m.setTargetAccess("public");
m.modifyClassVisibility = true;
modifiers.put(modClazzName, m);
}
}
|
common/cpw/mods/fml/common/asm/transformers/AccessTransformer.java
|
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common.asm.transformers;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
import static org.objectweb.asm.Opcodes.ACC_PROTECTED;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.io.LineProcessor;
import com.google.common.io.Resources;
import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
public class AccessTransformer implements IClassTransformer
{
private static final boolean DEBUG = false;
private class Modifier
{
public String name = "";
public String desc = "";
public int oldAccess = 0;
public int newAccess = 0;
public int targetAccess = 0;
public boolean changeFinal = false;
public boolean markFinal = false;
protected boolean modifyClassVisibility;
private void setTargetAccess(String name)
{
if (name.startsWith("public")) targetAccess = ACC_PUBLIC;
else if (name.startsWith("private")) targetAccess = ACC_PRIVATE;
else if (name.startsWith("protected")) targetAccess = ACC_PROTECTED;
if (name.endsWith("-f"))
{
changeFinal = true;
markFinal = false;
}
else if (name.endsWith("+f"))
{
changeFinal = true;
markFinal = true;
}
}
}
private Multimap<String, Modifier> modifiers = ArrayListMultimap.create();
public AccessTransformer() throws IOException
{
this("fml_at.cfg");
}
protected AccessTransformer(String rulesFile) throws IOException
{
readMapFile(rulesFile);
}
private void readMapFile(String rulesFile) throws IOException
{
File file = new File(rulesFile);
URL rulesResource;
if (file.exists())
{
rulesResource = file.toURI().toURL();
}
else
{
rulesResource = Resources.getResource(rulesFile);
}
Resources.readLines(rulesResource, Charsets.UTF_8, new LineProcessor<Void>()
{
@Override
public Void getResult()
{
return null;
}
@Override
public boolean processLine(String input) throws IOException
{
String line = Iterables.getFirst(Splitter.on('#').limit(2).split(input), "").trim();
if (line.length()==0)
{
return true;
}
List<String> parts = Lists.newArrayList(Splitter.on(" ").trimResults().split(line));
if (parts.size()>2)
{
throw new RuntimeException("Invalid config file line "+ input);
}
Modifier m = new Modifier();
m.setTargetAccess(parts.get(0));
List<String> descriptor = Lists.newArrayList(Splitter.on(".").trimResults().split(parts.get(1)));
if (descriptor.size() == 1)
{
m.modifyClassVisibility = true;
}
else
{
String nameReference = descriptor.get(1);
int parenIdx = nameReference.indexOf('(');
if (parenIdx>0)
{
m.desc = nameReference.substring(parenIdx);
m.name = nameReference.substring(0,parenIdx);
}
else
{
m.name = nameReference;
}
}
modifiers.put(descriptor.get(0).replace('/', '.'), m);
return true;
}
});
System.out.printf("Loaded %d rules from AccessTransformer config file %s\n", modifiers.size(), rulesFile);
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
if (bytes == null) { return null; }
boolean makeAllPublic = FMLDeobfuscatingRemapper.INSTANCE.isRemappedClass(name);
if (DEBUG)
{
FMLRelaunchLog.fine("Considering all methods and fields on %s (%s): %b\n", name, transformedName, makeAllPublic);
}
if (!makeAllPublic && !modifiers.containsKey(name)) { return bytes; }
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
if (makeAllPublic)
{
// class
Modifier m = new Modifier();
m.targetAccess = ACC_PUBLIC;
m.modifyClassVisibility = true;
modifiers.put(name,m);
// fields
m = new Modifier();
m.targetAccess = ACC_PUBLIC;
m.name = "*";
modifiers.put(name,m);
// methods
m = new Modifier();
m.targetAccess = ACC_PUBLIC;
m.name = "*";
m.desc = "<dummy>";
modifiers.put(name,m);
if (DEBUG)
{
System.out.printf("Injected all public modifiers for %s (%s)\n", name, transformedName);
}
}
Collection<Modifier> mods = modifiers.get(name);
for (Modifier m : mods)
{
if (m.modifyClassVisibility)
{
classNode.access = getFixedAccess(classNode.access, m);
if (DEBUG)
{
System.out.println(String.format("Class: %s %s -> %s", name, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
continue;
}
if (m.desc.isEmpty())
{
for (FieldNode n : classNode.fields)
{
if (n.name.equals(m.name) || m.name.equals("*"))
{
n.access = getFixedAccess(n.access, m);
if (DEBUG)
{
System.out.println(String.format("Field: %s.%s %s -> %s", name, n.name, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
if (!m.name.equals("*"))
{
break;
}
}
}
}
else
{
for (MethodNode n : classNode.methods)
{
if ((n.name.equals(m.name) && n.desc.equals(m.desc)) || m.name.equals("*"))
{
n.access = getFixedAccess(n.access, m);
if (DEBUG)
{
System.out.println(String.format("Method: %s.%s%s %s -> %s", name, n.name, n.desc, toBinary(m.oldAccess), toBinary(m.newAccess)));
}
if (!m.name.equals("*"))
{
break;
}
}
}
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
private String toBinary(int num)
{
return String.format("%16s", Integer.toBinaryString(num)).replace(' ', '0');
}
private int getFixedAccess(int access, Modifier target)
{
target.oldAccess = access;
int t = target.targetAccess;
int ret = (access & ~7);
switch (access & 7)
{
case ACC_PRIVATE:
ret |= t;
break;
case 0: // default
ret |= (t != ACC_PRIVATE ? t : 0 /* default */);
break;
case ACC_PROTECTED:
ret |= (t != ACC_PRIVATE && t != 0 /* default */? t : ACC_PROTECTED);
break;
case ACC_PUBLIC:
ret |= (t != ACC_PRIVATE && t != 0 /* default */&& t != ACC_PROTECTED ? t : ACC_PUBLIC);
break;
default:
throw new RuntimeException("The fuck?");
}
// Clear the "final" marker on fields only if specified in control field
if (target.changeFinal && target.desc == "")
{
if (target.markFinal)
{
ret |= ACC_FINAL;
}
else
{
ret &= ~ACC_FINAL;
}
}
target.newAccess = ret;
return ret;
}
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Usage: AccessTransformer <JarPath> <MapFile> [MapFile2]... ");
System.exit(1);
}
boolean hasTransformer = false;
AccessTransformer[] trans = new AccessTransformer[args.length - 1];
for (int x = 1; x < args.length; x++)
{
try
{
trans[x - 1] = new AccessTransformer(args[x]);
hasTransformer = true;
}
catch (IOException e)
{
System.out.println("Could not read Transformer Map: " + args[x]);
e.printStackTrace();
}
}
if (!hasTransformer)
{
System.out.println("Culd not find a valid transformer to perform");
System.exit(1);
}
File orig = new File(args[0]);
File temp = new File(args[0] + ".ATBack");
if (!orig.exists() && !temp.exists())
{
System.out.println("Could not find target jar: " + orig);
System.exit(1);
}
if (!orig.renameTo(temp))
{
System.out.println("Could not rename file: " + orig + " -> " + temp);
System.exit(1);
}
try
{
processJar(temp, orig, trans);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
if (!temp.delete())
{
System.out.println("Could not delete temp file: " + temp);
}
}
private static void processJar(File inFile, File outFile, AccessTransformer[] transformers) throws IOException
{
ZipInputStream inJar = null;
ZipOutputStream outJar = null;
try
{
try
{
inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open input file: " + e.getMessage());
}
try
{
outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException("Could not open output file: " + e.getMessage());
}
ZipEntry entry;
while ((entry = inJar.getNextEntry()) != null)
{
if (entry.isDirectory())
{
outJar.putNextEntry(entry);
continue;
}
byte[] data = new byte[4096];
ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();
int len;
do
{
len = inJar.read(data);
if (len > 0)
{
entryBuffer.write(data, 0, len);
}
}
while (len != -1);
byte[] entryData = entryBuffer.toByteArray();
String entryName = entry.getName();
if (entryName.endsWith(".class") && !entryName.startsWith("."))
{
ClassNode cls = new ClassNode();
ClassReader rdr = new ClassReader(entryData);
rdr.accept(cls, 0);
String name = cls.name.replace('/', '.').replace('\\', '.');
for (AccessTransformer trans : transformers)
{
entryData = trans.transform(name, name, entryData);
}
}
ZipEntry newEntry = new ZipEntry(entryName);
outJar.putNextEntry(newEntry);
outJar.write(entryData);
}
}
finally
{
if (outJar != null)
{
try
{
outJar.close();
}
catch (IOException e)
{
}
}
if (inJar != null)
{
try
{
inJar.close();
}
catch (IOException e)
{
}
}
}
}
public void ensurePublicAccessFor(String modClazzName)
{
Modifier m = new Modifier();
m.setTargetAccess("public");
m.modifyClassVisibility = true;
modifiers.put(modClazzName, m);
}
}
|
Make final transformers actually work on methods as well.
|
common/cpw/mods/fml/common/asm/transformers/AccessTransformer.java
|
Make final transformers actually work on methods as well.
|
<ide><path>ommon/cpw/mods/fml/common/asm/transformers/AccessTransformer.java
<ide> }
<ide>
<ide> // Clear the "final" marker on fields only if specified in control field
<del> if (target.changeFinal && target.desc == "")
<add> if (target.changeFinal)
<ide> {
<ide> if (target.markFinal)
<ide> {
|
|
Java
|
mit
|
5ae0beafa305d4df6dc603e16ed8a258c5e42e7c
| 0 |
FreeTymeKiyan/LeetCode-Sol-Res,FreeTymeKiyan/LeetCode-Sol-Res
|
package com.freetymekiyan.algorithms.level.hard;
import java.util.Arrays;
/**
* 85. Maximal Rectangle
* <p>
* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
* <p>
* For example, given the following matrix:
* <p>
* 1 0 1 0 0
* 1 0 1 1 1
* 1 1 1 1 1
* 1 0 0 1 0
* Return 6.
* <p>
* Company Tags: Facebook
* Tags: Array, Hash Table, Stack, Dynamic Programming
* Similar Problems: (H) Largest Rectangle in Histogram, (M) Maximal Square
*/
public class MaximalRectangle {
/**
* DP.
* Three matrices: left, right, and height.
* Height is number of continuous 1's that end at j.
* Left is the left boundary of this height. The actual value is an index.
* Right is the right boundary of this right. The actual value is index + 1.
* The rectangle area of this height at row i and column j is: [right(i,j) - left(i,j)] * height(i,j).
* <p>
* Recurrence relations:
* left(i,j) = max(left(i-1,j), leftBound)
* leftBound is the leftmost 1 of this height at current row.
* All left boundaries are initialized as 0, which is the leftmost possible.
* <p>
* right(i,j) = min(right(i-1,j), rightBound)
* rightBound is the rightmost 1 of this height at current row + 1.
* All right boundaries are initialized as n, which is the rightmost possible.
* <p>
* height(i,j) = height(i-1,j) + 1, if matrix[i][j]=='1'.
* height(i,j) = 0, if matrix[i][j]=='0'.
* <p>
* Implementation:
* Initialize left array and height as all zeroes, right array as the column length.
* For each row in the matrix, update height, left, right arrays.
* Then compute the area and record the maximum.
* Stop when all grids are done.
* https://discuss.leetcode.com/topic/6650/share-my-dp-solution
* <p>
* Note that the rectangle area we get is not the maximum at each grid, rather, it's the area of the rectangle of
* the maximum possible height.
* Why does that covers the maximum rectangle?
* Because:
* If the max rectangle has only 1 column, the bottom grid will have the max area.
* If the max rectangle has > 1 columns, the bottom row will have the max area.
*/
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[] left = new int[n];
int[] right = new int[n];
int[] height = new int[n];
// Arrays.fill(left, 0);
Arrays.fill(right, n);
// Arrays.fill(height, 0);
int max = 0;
for (int i = 0; i < m; i++) {
// Compute height (can do this from either side).
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
height[j]++;
} else {
height[j] = 0;
}
}
// Compute left boundaries (must from left to right).
int leftBound = 0; // Index of leftmost 1 of current row.
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
left[j] = Math.max(left[j], leftBound);
} else {
left[j] = 0;
leftBound = j + 1;
}
}
// Compute right boundaries (must from right to left).
int rightBound = n; // Index + 1 of rightmost 1 of current row.
for (int j = n - 1; j >= 0; j--) {
if (matrix[i][j] == '1') {
right[j] = Math.min(right[j], rightBound);
} else {
right[j] = n; // Like reset. Make sure right[j] >= curRight.
rightBound = j;
}
}
// Compute the area of rectangle (can do this from either side).
for (int j = 0; j < n; j++) {
max = Math.max(max, (right[j] - left[j]) * height[j]);
}
}
return max;
}
}
|
src/main/java/com/freetymekiyan/algorithms/level/hard/MaximalRectangle.java
|
package com.freetymekiyan.algorithms.level.hard;
import java.util.Arrays;
/**
* Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
* <p>
* For example, given the following matrix:
* <p>
* 1 0 1 0 0
* 1 0 1 1 1
* 1 1 1 1 1
* 1 0 0 1 0
* Return 6.
* <p>
* Company Tags: Facebook
* Tags: Array, Hash Table, Stack, Dynamic Programming
* Similar Problems: (H) Largest Rectangle in Histogram, (M) Maximal Square
*/
public class MaximalRectangle {
/**
* DP.
* Three matrices: left, right, and height.
* Maximal rectangle area at row i and column j is: [right(i,j) - left(i,j)] * height(i,j).
* left is the left boundary of current row and previous row.
* left(i,j) = max(left(i-1,j), curLeft)
* curLeft is the left boundary candidate of current row.
* <p>
* right is the right boundary of current row. Actually is index + 1 for easy implementation.
* right(i,j) = min(right(i-1,j), curRight)
* curRight is the right boundary candidate of current row.
* <p>
* height is how many 1s, including current 1, from top to current position.
* height(i,j) = height(i-1,j) + 1, if matrix[i][j]=='1'.
* height(i,j) = 0, if matrix[i][j]=='0'.
* <p>
* Implementation:
* Initialize left array and height as all zeroes, right array as the column length.
* For each row in the matrix, update height, left, right arrays.
* Then compute the max area.
* Stop when all rows are looped through.
* https://discuss.leetcode.com/topic/6650/share-my-dp-solution
*/
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[] left = new int[n];
int[] right = new int[n];
int[] height = new int[n];
// Arrays.fill(left, 0);
Arrays.fill(right, n);
// Arrays.fill(height, 0);
int maxA = 0;
for (int i = 0; i < m; i++) {
// Compute height (can do this from either side).
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
height[j]++;
} else {
height[j] = 0;
}
}
// Compute left (must from left to right).
int curLeft = 0; // Index of leftmost 1 of current row.
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
left[j] = Math.max(left[j], curLeft);
} else {
left[j] = 0;
curLeft = j + 1;
}
}
// Compute right (must from right to left).
int curRight = n; // Index+1 of rightmost 1 of current row.
for (int j = n - 1; j >= 0; j--) {
if (matrix[i][j] == '1') {
right[j] = Math.min(right[j], curRight);
} else {
right[j] = n; // Like reset. Make sure right[j] >= curRight.
curRight = j;
}
}
// Compute the area of rectangle (can do this from either side).
for (int j = 0; j < n; j++) {
maxA = Math.max(maxA, (right[j] - left[j]) * height[j]);
}
}
return maxA;
}
}
|
update 85. Maximal Rectangle
|
src/main/java/com/freetymekiyan/algorithms/level/hard/MaximalRectangle.java
|
update 85. Maximal Rectangle
|
<ide><path>rc/main/java/com/freetymekiyan/algorithms/level/hard/MaximalRectangle.java
<ide> import java.util.Arrays;
<ide>
<ide> /**
<add> * 85. Maximal Rectangle
<add> * <p>
<ide> * Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
<ide> * <p>
<ide> * For example, given the following matrix:
<ide> /**
<ide> * DP.
<ide> * Three matrices: left, right, and height.
<del> * Maximal rectangle area at row i and column j is: [right(i,j) - left(i,j)] * height(i,j).
<del> * left is the left boundary of current row and previous row.
<del> * left(i,j) = max(left(i-1,j), curLeft)
<del> * curLeft is the left boundary candidate of current row.
<add> * Height is number of continuous 1's that end at j.
<add> * Left is the left boundary of this height. The actual value is an index.
<add> * Right is the right boundary of this right. The actual value is index + 1.
<add> * The rectangle area of this height at row i and column j is: [right(i,j) - left(i,j)] * height(i,j).
<ide> * <p>
<del> * right is the right boundary of current row. Actually is index + 1 for easy implementation.
<del> * right(i,j) = min(right(i-1,j), curRight)
<del> * curRight is the right boundary candidate of current row.
<add> * Recurrence relations:
<add> * left(i,j) = max(left(i-1,j), leftBound)
<add> * leftBound is the leftmost 1 of this height at current row.
<add> * All left boundaries are initialized as 0, which is the leftmost possible.
<ide> * <p>
<del> * height is how many 1s, including current 1, from top to current position.
<add> * right(i,j) = min(right(i-1,j), rightBound)
<add> * rightBound is the rightmost 1 of this height at current row + 1.
<add> * All right boundaries are initialized as n, which is the rightmost possible.
<add> * <p>
<ide> * height(i,j) = height(i-1,j) + 1, if matrix[i][j]=='1'.
<ide> * height(i,j) = 0, if matrix[i][j]=='0'.
<ide> * <p>
<ide> * Implementation:
<ide> * Initialize left array and height as all zeroes, right array as the column length.
<ide> * For each row in the matrix, update height, left, right arrays.
<del> * Then compute the max area.
<del> * Stop when all rows are looped through.
<add> * Then compute the area and record the maximum.
<add> * Stop when all grids are done.
<ide> * https://discuss.leetcode.com/topic/6650/share-my-dp-solution
<add> * <p>
<add> * Note that the rectangle area we get is not the maximum at each grid, rather, it's the area of the rectangle of
<add> * the maximum possible height.
<add> * Why does that covers the maximum rectangle?
<add> * Because:
<add> * If the max rectangle has only 1 column, the bottom grid will have the max area.
<add> * If the max rectangle has > 1 columns, the bottom row will have the max area.
<ide> */
<ide> public int maximalRectangle(char[][] matrix) {
<ide> int m = matrix.length;
<ide> // Arrays.fill(left, 0);
<ide> Arrays.fill(right, n);
<ide> // Arrays.fill(height, 0);
<del> int maxA = 0;
<add> int max = 0;
<ide> for (int i = 0; i < m; i++) {
<ide> // Compute height (can do this from either side).
<ide> for (int j = 0; j < n; j++) {
<ide> height[j] = 0;
<ide> }
<ide> }
<del> // Compute left (must from left to right).
<del> int curLeft = 0; // Index of leftmost 1 of current row.
<add> // Compute left boundaries (must from left to right).
<add> int leftBound = 0; // Index of leftmost 1 of current row.
<ide> for (int j = 0; j < n; j++) {
<ide> if (matrix[i][j] == '1') {
<del> left[j] = Math.max(left[j], curLeft);
<add> left[j] = Math.max(left[j], leftBound);
<ide> } else {
<ide> left[j] = 0;
<del> curLeft = j + 1;
<add> leftBound = j + 1;
<ide> }
<ide> }
<del> // Compute right (must from right to left).
<del> int curRight = n; // Index+1 of rightmost 1 of current row.
<add> // Compute right boundaries (must from right to left).
<add> int rightBound = n; // Index + 1 of rightmost 1 of current row.
<ide> for (int j = n - 1; j >= 0; j--) {
<ide> if (matrix[i][j] == '1') {
<del> right[j] = Math.min(right[j], curRight);
<add> right[j] = Math.min(right[j], rightBound);
<ide> } else {
<ide> right[j] = n; // Like reset. Make sure right[j] >= curRight.
<del> curRight = j;
<add> rightBound = j;
<ide> }
<ide> }
<ide> // Compute the area of rectangle (can do this from either side).
<ide> for (int j = 0; j < n; j++) {
<del> maxA = Math.max(maxA, (right[j] - left[j]) * height[j]);
<add> max = Math.max(max, (right[j] - left[j]) * height[j]);
<ide> }
<ide> }
<del> return maxA;
<add> return max;
<ide> }
<ide> }
|
|
Java
|
mit
|
e2213e690085d83aef346cb076da259222b6db7f
| 0 |
jbosboom/streamjit,jbosboom/streamjit
|
package edu.mit.streamjit.impl.compiler2;
import edu.mit.streamjit.impl.blob.Blob.Token;
/**
* A StorageSlot represents a slot in a storage: whether it's live or not, and
* if it is, where it should go when we drain.
* @author Jeffrey Bosboom <[email protected]>
* @since 11/29/2013
*/
public abstract class StorageSlot {
public static StorageSlot live(Token token, int index) {
assert token != null;
assert index >= 0 : index;
return new LiveStorageSlot(token, index);
}
public static StorageSlot hole() {
return HoleStorageSlot.INSTANCE;
}
public abstract boolean isLive();
public abstract boolean isHole();
public abstract boolean isDrainable();
public abstract StorageSlot duplify();
public abstract Token token();
public abstract int index();
@Override
public abstract String toString();
private static final class HoleStorageSlot extends StorageSlot {
private static final HoleStorageSlot INSTANCE = new HoleStorageSlot();
private HoleStorageSlot() {}
@Override
public boolean isLive() {
return false;
}
@Override
public boolean isHole() {
return true;
}
@Override
public boolean isDrainable() {
return false;
}
@Override
public StorageSlot duplify() {
return this; //a hole duplicate is just a hole
}
@Override
public Token token() {
throw new AssertionError("called token() on a hole");
}
@Override
public int index() {
throw new AssertionError("called index() on a hole");
}
@Override
public String toString() {
return "(hole)";
}
}
private static class LiveStorageSlot extends StorageSlot {
private final Token token;
private final int index;
protected LiveStorageSlot(Token token, int index) {
this.token = token;
this.index = index;
}
@Override
public boolean isLive() {
return true;
}
@Override
public boolean isHole() {
return false;
}
@Override
public boolean isDrainable() {
return true;
}
@Override
public StorageSlot duplify() {
return DuplicateStorageSlot.INSTANCE;
}
@Override
public Token token() {
return token;
}
@Override
public int index() {
return index;
}
@Override
public String toString() {
return String.format("%s[%d]", token(), index());
}
}
private static final class DuplicateStorageSlot extends StorageSlot {
private static final DuplicateStorageSlot INSTANCE = new DuplicateStorageSlot();
private DuplicateStorageSlot() {}
@Override
public boolean isLive() {
return true;
}
@Override
public boolean isHole() {
return false;
}
@Override
public boolean isDrainable() {
return false;
}
@Override
public StorageSlot duplify() {
return this;
}
@Override
public Token token() {
throw new AssertionError("called token() on a duplicate");
}
@Override
public int index() {
throw new AssertionError("called index() on a duplicate");
}
@Override
public String toString() {
return String.format("(dup)");
}
}
protected StorageSlot() {}
}
|
src/edu/mit/streamjit/impl/compiler2/StorageSlot.java
|
package edu.mit.streamjit.impl.compiler2;
import edu.mit.streamjit.impl.blob.Blob.Token;
/**
* A StorageSlot represents a slot in a storage: whether it's live or not, and
* if it is, where it should go when we drain.
* @author Jeffrey Bosboom <[email protected]>
* @since 11/29/2013
*/
public abstract class StorageSlot {
public static StorageSlot live(Token token, int index) {
assert token != null;
assert index >= 0 : index;
return new LiveStorageSlot(token, index);
}
public static StorageSlot hole() {
return HoleStorageSlot.INSTANCE;
}
public abstract boolean isLive();
public abstract boolean isHole();
public abstract boolean isDrainable();
public abstract StorageSlot duplify();
public abstract Token token();
public abstract int index();
@Override
public abstract String toString();
private static final class HoleStorageSlot extends StorageSlot {
private static final HoleStorageSlot INSTANCE = new HoleStorageSlot();
private HoleStorageSlot() {}
@Override
public boolean isLive() {
return false;
}
@Override
public boolean isHole() {
return true;
}
@Override
public boolean isDrainable() {
return false;
}
@Override
public StorageSlot duplify() {
return this; //a hole duplicate is just a hole
}
@Override
public Token token() {
throw new AssertionError("called token() on a hole");
}
@Override
public int index() {
throw new AssertionError("called index() on a hole");
}
@Override
public String toString() {
return "(hole)";
}
}
private static class LiveStorageSlot extends StorageSlot {
private final Token token;
private final int index;
/**
* If we've duplified, the duplicate slot we created. Caching this
* prevents a duplicate explosion.
*/
private StorageSlot duplicate;
protected LiveStorageSlot(Token token, int index) {
this.token = token;
this.index = index;
}
@Override
public boolean isLive() {
return true;
}
@Override
public boolean isHole() {
return false;
}
@Override
public boolean isDrainable() {
return true;
}
@Override
public StorageSlot duplify() {
if (duplicate == null)
duplicate = new DuplicateStorageSlot(token(), index());
return duplicate;
}
@Override
public Token token() {
return token;
}
@Override
public int index() {
return index;
}
@Override
public String toString() {
return String.format("%s[%d]", token(), index());
}
}
private static final class DuplicateStorageSlot extends LiveStorageSlot {
private DuplicateStorageSlot(Token token, int index) {
super(token, index);
}
@Override
public boolean isDrainable() {
return false;
}
@Override
public StorageSlot duplify() {
return this;
}
@Override
public String toString() {
return String.format("dup:%s[%d]", token(), index());
}
}
protected StorageSlot() {}
}
|
StorageSlot: make DuplicateStorageSlot a singleton
|
src/edu/mit/streamjit/impl/compiler2/StorageSlot.java
|
StorageSlot: make DuplicateStorageSlot a singleton
|
<ide><path>rc/edu/mit/streamjit/impl/compiler2/StorageSlot.java
<ide> private static class LiveStorageSlot extends StorageSlot {
<ide> private final Token token;
<ide> private final int index;
<del> /**
<del> * If we've duplified, the duplicate slot we created. Caching this
<del> * prevents a duplicate explosion.
<del> */
<del> private StorageSlot duplicate;
<ide> protected LiveStorageSlot(Token token, int index) {
<ide> this.token = token;
<ide> this.index = index;
<ide> }
<ide> @Override
<ide> public StorageSlot duplify() {
<del> if (duplicate == null)
<del> duplicate = new DuplicateStorageSlot(token(), index());
<del> return duplicate;
<add> return DuplicateStorageSlot.INSTANCE;
<ide> }
<ide> @Override
<ide> public Token token() {
<ide> }
<ide> }
<ide>
<del> private static final class DuplicateStorageSlot extends LiveStorageSlot {
<del> private DuplicateStorageSlot(Token token, int index) {
<del> super(token, index);
<add> private static final class DuplicateStorageSlot extends StorageSlot {
<add> private static final DuplicateStorageSlot INSTANCE = new DuplicateStorageSlot();
<add> private DuplicateStorageSlot() {}
<add> @Override
<add> public boolean isLive() {
<add> return true;
<add> }
<add> @Override
<add> public boolean isHole() {
<add> return false;
<ide> }
<ide> @Override
<ide> public boolean isDrainable() {
<ide> return this;
<ide> }
<ide> @Override
<add> public Token token() {
<add> throw new AssertionError("called token() on a duplicate");
<add> }
<add> @Override
<add> public int index() {
<add> throw new AssertionError("called index() on a duplicate");
<add> }
<add> @Override
<ide> public String toString() {
<del> return String.format("dup:%s[%d]", token(), index());
<add> return String.format("(dup)");
<ide> }
<ide> }
<ide>
|
|
Java
|
lgpl-2.1
|
7db1787ee0c23bf928b880ddaed323eb65926bef
| 0 |
joshkh/intermine,zebrafishmine/intermine,joshkh/intermine,justincc/intermine,drhee/toxoMine,drhee/toxoMine,drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine,zebrafishmine/intermine,drhee/toxoMine,drhee/toxoMine,elsiklab/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,elsiklab/intermine,JoeCarlson/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,justincc/intermine,zebrafishmine/intermine,justincc/intermine,kimrutherford/intermine,tomck/intermine,tomck/intermine,justincc/intermine,drhee/toxoMine,zebrafishmine/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,kimrutherford/intermine,joshkh/intermine,elsiklab/intermine,elsiklab/intermine,JoeCarlson/intermine,JoeCarlson/intermine,zebrafishmine/intermine,JoeCarlson/intermine,joshkh/intermine,joshkh/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,drhee/toxoMine,JoeCarlson/intermine,kimrutherford/intermine,JoeCarlson/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,tomck/intermine,justincc/intermine,kimrutherford/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,JoeCarlson/intermine,justincc/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,drhee/toxoMine,zebrafishmine/intermine,tomck/intermine,tomck/intermine,zebrafishmine/intermine,justincc/intermine,tomck/intermine,elsiklab/intermine,tomck/intermine,tomck/intermine,kimrutherford/intermine,kimrutherford/intermine
|
package org.intermine.web.logic.profile;
/*
* Copyright (C) 2002-2007 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.intermine.model.userprofile.Tag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.query.SavedQuery;
import org.intermine.web.logic.search.SearchRepository;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.tagging.TagTypes;
import org.intermine.web.logic.template.TemplateHelper;
import org.intermine.web.logic.template.TemplateQuery;
import org.apache.commons.collections.map.ListOrderedMap;
/**
* Class to represent a user of the webapp
*
* @author Mark Woodbridge
* @author Thomas Riley
*/
public class Profile
{
protected ProfileManager manager;
protected String username;
protected Integer userId;
protected String password;
protected Map<String, SavedQuery> savedQueries = new TreeMap<String, SavedQuery>();
protected Map<String, InterMineBag> savedBags = new TreeMap<String, InterMineBag>();
protected Map<String, TemplateQuery> savedTemplates = new TreeMap<String, TemplateQuery>();
protected Map<String, String> userOptions = new TreeMap<String, String>();
//protected Map categoryTemplates;
protected Map queryHistory = new ListOrderedMap();
private boolean savingDisabled;
private SearchRepository searchRepository =
new SearchRepository(this, TemplateHelper.USER_TEMPLATE);
/**
* Construct a Profile
* @param manager the manager for this profile
* @param username the username for this profile
* @param userId the id of this user
* @param password the password for this profile
* @param savedQueries the saved queries for this profile
* @param savedBags the saved bags for this profile
* @param savedTemplates the saved templates for this profile
*/
public Profile(ProfileManager manager, String username, Integer userId, String password,
Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags,
Map<String, TemplateQuery> savedTemplates) {
this.manager = manager;
this.username = username;
this.userId = userId;
this.password = password;
if (savedQueries != null) {
this.savedQueries.putAll(savedQueries);
}
if (savedBags != null) {
this.savedBags.putAll(savedBags);
}
if (savedTemplates != null) {
this.savedTemplates.putAll(savedTemplates);
}
reindex(TagTypes.TEMPLATE);
reindex(TagTypes.BAG);
}
/**
* Return the ProfileManager that was passed to the constructor.
* @return the ProfileManager
*/
public ProfileManager getProfileManager() {
return manager;
}
/**
* Get the value of username
* @return the value of username
*/
public String getUsername() {
return username;
}
/**
* Return true if and only if the user is logged is (and the Profile will be written to the
* userprofile).
* @return Return true if logged in
*/
public boolean isLoggedIn() {
return getUsername() != null;
}
/**
* Get the value of userId
* @return an Integer
*/
public Integer getUserId() {
return userId;
}
/**
* Set the userId
*
* @param userId an Integer
*/
public void setUserId(Integer userId) {
this.userId = userId;
}
/**
* Get the value of password
* @return the value of password
*/
public String getPassword() {
return password;
}
/**
* Disable saving until enableSaving() is called. This is called before many templates or
* queries need to be saved or deleted because each call to ProfileManager.saveProfile() is
* slow.
*/
public void disableSaving() {
savingDisabled = true;
}
/**
* Re-enable saving when saveTemplate(), deleteQuery() etc. are called. Also calls
* ProfileManager.saveProfile() to write this Profile to the database and rebuilds the
* template description index.
*/
public void enableSaving() {
savingDisabled = false;
if (manager != null) {
manager.saveProfile(this);
}
reindex(TagTypes.TEMPLATE);
reindex(TagTypes.BAG);
}
/**
* Get the users saved templates
* @return saved templates
*/
public Map<String, TemplateQuery> getSavedTemplates() {
return Collections.unmodifiableMap(savedTemplates);
}
/**
* Save a template
* @param name the template name
* @param template the template
*/
public void saveTemplate(String name, TemplateQuery template) {
savedTemplates.put(name, template);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
reindex(TagTypes.TEMPLATE);
}
}
/**
* get a template
* @param name the template
* @return template
*/
public TemplateQuery getTemplate(String name) {
return savedTemplates.get(name);
}
/**
* Delete a template
* @param name the template name
*/
public void deleteTemplate(String name) {
savedTemplates.remove(name);
if (manager != null) {
List favourites = manager.getTags("favourite", name, TagTypes.TEMPLATE, username);
for (Iterator iter = favourites.iterator(); iter.hasNext();) {
Tag tag = (Tag) iter.next();
manager.deleteTag(tag);
}
if (!savingDisabled) {
manager.saveProfile(this);
reindex(TagTypes.TEMPLATE);
}
}
}
/**
* Get the value of savedQueries
* @return the value of savedQueries
*/
public Map<String, SavedQuery> getSavedQueries() {
return Collections.unmodifiableMap(savedQueries);
}
/**
* Save a query
* @param name the query name
* @param query the query
*/
public void saveQuery(String name, SavedQuery query) {
savedQueries.put(name, query);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
}
/**
* Delete a query
* @param name the query name
*/
public void deleteQuery(String name) {
savedQueries.remove(name);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
}
/**
* Get the session query history.
* @return map from query name to SavedQuery
*/
public Map<String, SavedQuery> getHistory() {
return Collections.unmodifiableMap(queryHistory);
}
/**
* Save a query to the query history.
* @param query the SavedQuery to save to the history
*/
public void saveHistory(SavedQuery query) {
queryHistory.put(query.getName(), query);
}
/**
* Remove an item from the query history.
* @param name the of the SavedQuery from the history
*/
public void deleteHistory(String name) {
queryHistory.remove(name);
}
/**
* Rename an item in the history.
* @param oldName the name of the old item
* @param newName the new name
*/
public void renameHistory(String oldName, String newName) {
Map<String, SavedQuery> newMap = new ListOrderedMap();
Iterator<String> iter = queryHistory.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
SavedQuery sq = (SavedQuery) queryHistory.get(name);
if (name.equals(oldName)) {
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
}
newMap.put(sq.getName(), sq);
}
queryHistory = newMap;
}
/**
* Get the value of savedBags
* @return the value of savedBags
*/
public Map<String, InterMineBag> getSavedBags() {
return Collections.unmodifiableMap(savedBags);
}
/**
* Stores a new bag in the profile. Note that bags are always present in the user profile
* database, so this just adds the bag to the in-memory list of this profile.
*
* @param name the name of the bag
* @param bag the InterMineBag object
*/
public void saveBag(String name, InterMineBag bag) {
savedBags.put(name, bag);
reindex(TagTypes.BAG);
}
/**
* Create a bag - saves it to the user profile database too.
*
* @param name the bag name
* @param type the bag type
* @param description the bag description
* @param os the production ObjectStore
* @param uosw the ObjectStoreWriter of the userprofile database
* @throws ObjectStoreException if something goes wrong
*/
public void createBag(String name, String type, String description, ObjectStore os,
ObjectStoreWriter uosw) throws ObjectStoreException {
InterMineBag bag = new InterMineBag(name, type, description, new Date(), os, userId, uosw);
savedBags.put(name, bag);
reindex(TagTypes.BAG);
}
/**
* Delete a bag
* @param name the bag name
*/
public void deleteBag(String name) {
savedBags.remove(name);
reindex(TagTypes.BAG);
}
/**
* Create a map from category name to a list of templates contained
* within that category.
*/
private void reindex(String type) {
// We also take this opportunity to index the user's template queries, bags, etc.
searchRepository.addWebSearchables(type, getWebSearchablesByType(type));
}
/**
* Return a WebSearchable Map for the given type.
* @param type the type (from TagTypes)
* @return the Map
*/
public Map<String, ? extends WebSearchable> getWebSearchablesByType(String type) {
if (type.equals(TagTypes.TEMPLATE)) {
return savedTemplates;
} else {
if (type.equals(TagTypes.BAG)) {
return getSavedBags();
} else {
throw new RuntimeException("unknown type: " + type);
}
}
}
/**
* Get the SearchRepository for this Profile.
* @return the SearchRepository for the user
*/
public SearchRepository getSearchRepository() {
return searchRepository;
}
/**
* Return the userOption
* @return the value
*/
public String getUserOption(String name) {
return userOptions.get(name);
}
/**
* Set the userOption
* @param name the userOption name
* @param value the userOption value
*/
public void setUserOption(String name, String value) {
userOptions.put(name, value);
}
/**
* @return the userOptions
*/
public Map<String, String> getUserOptionsMap() {
return userOptions;
}
}
|
intermine/web/main/src/org/intermine/web/logic/profile/Profile.java
|
package org.intermine.web.logic.profile;
/*
* Copyright (C) 2002-2007 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.intermine.model.userprofile.Tag;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.query.SavedQuery;
import org.intermine.web.logic.search.SearchRepository;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.tagging.TagTypes;
import org.intermine.web.logic.template.TemplateHelper;
import org.intermine.web.logic.template.TemplateQuery;
import org.apache.commons.collections.map.ListOrderedMap;
/**
* Class to represent a user of the webapp
*
* @author Mark Woodbridge
* @author Thomas Riley
*/
public class Profile
{
protected ProfileManager manager;
protected String username;
protected Integer userId;
protected String password;
protected Map<String, SavedQuery> savedQueries = new TreeMap<String, SavedQuery>();
protected Map<String, InterMineBag> savedBags = new TreeMap<String, InterMineBag>();
protected Map<String, TemplateQuery> savedTemplates = new TreeMap<String, TemplateQuery>();
protected Map<String, String> userOptions = new TreeMap<String, String>();
//protected Map categoryTemplates;
protected Map queryHistory = new ListOrderedMap();
private boolean savingDisabled;
private SearchRepository searchRepository =
new SearchRepository(this, TemplateHelper.USER_TEMPLATE);
/**
* Construct a Profile
* @param manager the manager for this profile
* @param username the username for this profile
* @param userId the id of this user
* @param password the password for this profile
* @param savedQueries the saved queries for this profile
* @param savedBags the saved bags for this profile
* @param savedTemplates the saved templates for this profile
*/
public Profile(ProfileManager manager, String username, Integer userId, String password,
Map<String, SavedQuery> savedQueries, Map<String, InterMineBag> savedBags,
Map<String, TemplateQuery> savedTemplates) {
this.manager = manager;
this.username = username;
this.userId = userId;
this.password = password;
this.savedQueries.putAll(savedQueries);
this.savedBags.putAll(savedBags);
this.savedTemplates.putAll(savedTemplates);
reindex(TagTypes.TEMPLATE);
reindex(TagTypes.BAG);
}
/**
* Return the ProfileManager that was passed to the constructor.
* @return the ProfileManager
*/
public ProfileManager getProfileManager() {
return manager;
}
/**
* Get the value of username
* @return the value of username
*/
public String getUsername() {
return username;
}
/**
* Return true if and only if the user is logged is (and the Profile will be written to the
* userprofile).
* @return Return true if logged in
*/
public boolean isLoggedIn() {
return getUsername() != null;
}
/**
* Get the value of userId
* @return an Integer
*/
public Integer getUserId() {
return userId;
}
/**
* Set the userId
*
* @param userId an Integer
*/
public void setUserId(Integer userId) {
this.userId = userId;
}
/**
* Get the value of password
* @return the value of password
*/
public String getPassword() {
return password;
}
/**
* Disable saving until enableSaving() is called. This is called before many templates or
* queries need to be saved or deleted because each call to ProfileManager.saveProfile() is
* slow.
*/
public void disableSaving() {
savingDisabled = true;
}
/**
* Re-enable saving when saveTemplate(), deleteQuery() etc. are called. Also calls
* ProfileManager.saveProfile() to write this Profile to the database and rebuilds the
* template description index.
*/
public void enableSaving() {
savingDisabled = false;
if (manager != null) {
manager.saveProfile(this);
}
reindex(TagTypes.TEMPLATE);
reindex(TagTypes.BAG);
}
/**
* Get the users saved templates
* @return saved templates
*/
public Map<String, TemplateQuery> getSavedTemplates() {
return Collections.unmodifiableMap(savedTemplates);
}
/**
* Save a template
* @param name the template name
* @param template the template
*/
public void saveTemplate(String name, TemplateQuery template) {
savedTemplates.put(name, template);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
reindex(TagTypes.TEMPLATE);
}
}
/**
* get a template
* @param name the template
* @return template
*/
public TemplateQuery getTemplate(String name) {
return savedTemplates.get(name);
}
/**
* Delete a template
* @param name the template name
*/
public void deleteTemplate(String name) {
savedTemplates.remove(name);
if (manager != null) {
List favourites = manager.getTags("favourite", name, TagTypes.TEMPLATE, username);
for (Iterator iter = favourites.iterator(); iter.hasNext();) {
Tag tag = (Tag) iter.next();
manager.deleteTag(tag);
}
if (!savingDisabled) {
manager.saveProfile(this);
reindex(TagTypes.TEMPLATE);
}
}
}
/**
* Get the value of savedQueries
* @return the value of savedQueries
*/
public Map<String, SavedQuery> getSavedQueries() {
return Collections.unmodifiableMap(savedQueries);
}
/**
* Save a query
* @param name the query name
* @param query the query
*/
public void saveQuery(String name, SavedQuery query) {
savedQueries.put(name, query);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
}
/**
* Delete a query
* @param name the query name
*/
public void deleteQuery(String name) {
savedQueries.remove(name);
if (manager != null && !savingDisabled) {
manager.saveProfile(this);
}
}
/**
* Get the session query history.
* @return map from query name to SavedQuery
*/
public Map<String, SavedQuery> getHistory() {
return Collections.unmodifiableMap(queryHistory);
}
/**
* Save a query to the query history.
* @param query the SavedQuery to save to the history
*/
public void saveHistory(SavedQuery query) {
queryHistory.put(query.getName(), query);
}
/**
* Remove an item from the query history.
* @param name the of the SavedQuery from the history
*/
public void deleteHistory(String name) {
queryHistory.remove(name);
}
/**
* Rename an item in the history.
* @param oldName the name of the old item
* @param newName the new name
*/
public void renameHistory(String oldName, String newName) {
Map<String, SavedQuery> newMap = new ListOrderedMap();
Iterator<String> iter = queryHistory.keySet().iterator();
while (iter.hasNext()) {
String name = iter.next();
SavedQuery sq = (SavedQuery) queryHistory.get(name);
if (name.equals(oldName)) {
sq = new SavedQuery(newName, sq.getDateCreated(), sq.getPathQuery());
}
newMap.put(sq.getName(), sq);
}
queryHistory = newMap;
}
/**
* Get the value of savedBags
* @return the value of savedBags
*/
public Map<String, InterMineBag> getSavedBags() {
return Collections.unmodifiableMap(savedBags);
}
/**
* Stores a new bag in the profile. Note that bags are always present in the user profile
* database, so this just adds the bag to the in-memory list of this profile.
*
* @param name the name of the bag
* @param bag the InterMineBag object
*/
public void saveBag(String name, InterMineBag bag) {
savedBags.put(name, bag);
reindex(TagTypes.BAG);
}
/**
* Create a bag - saves it to the user profile database too.
*
* @param name the bag name
* @param type the bag type
* @param description the bag description
* @param os the production ObjectStore
* @param uosw the ObjectStoreWriter of the userprofile database
* @throws ObjectStoreException if something goes wrong
*/
public void createBag(String name, String type, String description, ObjectStore os,
ObjectStoreWriter uosw) throws ObjectStoreException {
InterMineBag bag = new InterMineBag(name, type, description, new Date(), os, userId, uosw);
savedBags.put(name, bag);
reindex(TagTypes.BAG);
}
/**
* Delete a bag
* @param name the bag name
*/
public void deleteBag(String name) {
savedBags.remove(name);
reindex(TagTypes.BAG);
}
/**
* Create a map from category name to a list of templates contained
* within that category.
*/
private void reindex(String type) {
// We also take this opportunity to index the user's template queries, bags, etc.
searchRepository.addWebSearchables(type, getWebSearchablesByType(type));
}
/**
* Return a WebSearchable Map for the given type.
* @param type the type (from TagTypes)
* @return the Map
*/
public Map<String, ? extends WebSearchable> getWebSearchablesByType(String type) {
if (type.equals(TagTypes.TEMPLATE)) {
return savedTemplates;
} else {
if (type.equals(TagTypes.BAG)) {
return getSavedBags();
} else {
throw new RuntimeException("unknown type: " + type);
}
}
}
/**
* Get the SearchRepository for this Profile.
* @return the SearchRepository for the user
*/
public SearchRepository getSearchRepository() {
return searchRepository;
}
/**
* Return the userOption
* @return the value
*/
public String getUserOption(String name) {
return userOptions.get(name);
}
/**
* Set the userOption
* @param name the userOption name
* @param value the userOption value
*/
public void setUserOption(String name, String value) {
userOptions.put(name, value);
}
/**
* @return the userOptions
*/
public Map<String, String> getUserOptionsMap() {
return userOptions;
}
}
|
Fixed NullPointerException loading default templates.
|
intermine/web/main/src/org/intermine/web/logic/profile/Profile.java
|
Fixed NullPointerException loading default templates.
|
<ide><path>ntermine/web/main/src/org/intermine/web/logic/profile/Profile.java
<ide> this.username = username;
<ide> this.userId = userId;
<ide> this.password = password;
<del> this.savedQueries.putAll(savedQueries);
<del> this.savedBags.putAll(savedBags);
<del> this.savedTemplates.putAll(savedTemplates);
<add> if (savedQueries != null) {
<add> this.savedQueries.putAll(savedQueries);
<add> }
<add> if (savedBags != null) {
<add> this.savedBags.putAll(savedBags);
<add> }
<add> if (savedTemplates != null) {
<add> this.savedTemplates.putAll(savedTemplates);
<add> }
<ide> reindex(TagTypes.TEMPLATE);
<ide> reindex(TagTypes.BAG);
<ide> }
|
|
Java
|
bsd-3-clause
|
66c17132d3871b96f8685156275747d04da19d11
| 0 |
BeeeOn/android,BeeeOn/android,BeeeOn/android
|
package com.rehivetech.beeeon.util;
import com.rehivetech.beeeon.R;
/**
* Created by david on 3.9.15.
*/
public class CacheHoldTime extends SettingsItem {
public static final String PERSISTENCE_CACHE_KEY = "pref_cache";
public static final int DO_NOT_ACTUALIZE = 0;
public static final int ONE_MINUTE = 60;
public static final int TWO_MINUTES = 2 * 60;
public static final int FIVE_MINUTES = 5 * 60;
public static final int TEN_MINUTES = 10 * 60;
public static final int THIRY_MINUTES = 30 * 30;
public CacheHoldTime() {
super();
mItems.add(new BaseItem(DO_NOT_ACTUALIZE, R.string.cache_listpreference_do_not_store));
mItems.add(new BaseItem(ONE_MINUTE, R.string.cache_listpreference_one_minute));
mItems.add(new BaseItem(TWO_MINUTES, R.string.cache_listpreference_two_minutes));
mItems.add(new BaseItem(FIVE_MINUTES, R.string.cache_listpreference_five_minutes));
mItems.add(new BaseItem(TEN_MINUTES, R.string.cache_listpreference_ten_minutes));
mItems.add(new BaseItem(THIRY_MINUTES, R.string.cache_listpreference_thirty_minutes));
}
@Override
public int getDefaultId() {
return FIVE_MINUTES;
}
@Override
public String getPersistenceKey() {
return PERSISTENCE_CACHE_KEY;
}
}
|
BeeeOn/app/src/main/java/com/rehivetech/beeeon/util/CacheHoldTime.java
|
package com.rehivetech.beeeon.util;
import com.rehivetech.beeeon.R;
/**
* Created by david on 3.9.15.
*/
public class CacheHoldTime extends SettingsItem {
public static final String PERSISTENCE_CACHE_KEY = "pref_cache";
public static final int DO_NOT_ACTUALIZE = 0;
public static final int ONE_MINUTE = 60;
public static final int TWO_MINUTES = 2 * 60;
public static final int FIVE_MINUTES = 5 * 60;
public static final int TEN_MINUTES = 10 * 60;
public static final int THIRY_MINUTES = 30 * 30;
public CacheHoldTime() {
super();
mItems.add(new BaseItem(DO_NOT_ACTUALIZE, R.string.cache_listpreference_do_not_store)); //TODO is that even possible?
mItems.add(new BaseItem(ONE_MINUTE, R.string.cache_listpreference_one_minute));
mItems.add(new BaseItem(TWO_MINUTES, R.string.cache_listpreference_two_minutes));
mItems.add(new BaseItem(FIVE_MINUTES, R.string.cache_listpreference_five_minutes));
mItems.add(new BaseItem(TEN_MINUTES, R.string.cache_listpreference_ten_minutes));
mItems.add(new BaseItem(THIRY_MINUTES, R.string.cache_listpreference_thirty_minutes));
}
@Override
public int getDefaultId() {
return DO_NOT_ACTUALIZE;
}
@Override
public String getPersistenceKey() {
return PERSISTENCE_CACHE_KEY;
}
}
|
Use better default value for CacheHoldTime
|
BeeeOn/app/src/main/java/com/rehivetech/beeeon/util/CacheHoldTime.java
|
Use better default value for CacheHoldTime
|
<ide><path>eeeOn/app/src/main/java/com/rehivetech/beeeon/util/CacheHoldTime.java
<ide> public CacheHoldTime() {
<ide> super();
<ide>
<del> mItems.add(new BaseItem(DO_NOT_ACTUALIZE, R.string.cache_listpreference_do_not_store)); //TODO is that even possible?
<add> mItems.add(new BaseItem(DO_NOT_ACTUALIZE, R.string.cache_listpreference_do_not_store));
<ide> mItems.add(new BaseItem(ONE_MINUTE, R.string.cache_listpreference_one_minute));
<ide> mItems.add(new BaseItem(TWO_MINUTES, R.string.cache_listpreference_two_minutes));
<ide> mItems.add(new BaseItem(FIVE_MINUTES, R.string.cache_listpreference_five_minutes));
<ide>
<ide> @Override
<ide> public int getDefaultId() {
<del> return DO_NOT_ACTUALIZE;
<add> return FIVE_MINUTES;
<ide> }
<ide>
<ide> @Override
|
|
Java
|
mit
|
de30fef85c8f1439eefdb314bff9672c03e99afd
| 0 |
RadicalZephyr/http-server
|
package net.zephyrizing.http_server_test;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Stream;
import net.zephyrizing.http_server.HttpProtocol;
import net.zephyrizing.http_server.HttpRequest;
import org.junit.Test;
import static java.util.Arrays.asList;
import static net.zephyrizing.http_server.HttpRequest.Method.*;
import static org.junit.Assert.*;
public class HttpRequestTest {
@Test
public void canCreateGETRequest() {
HttpRequest request = new HttpRequest(GET, "/", "1.1");
assertEquals(GET, request.method());
assertEquals(Paths.get("/"), request.path());
assertEquals("1.1", request.protocolVersion());
}
@Test
public void canCreatePOSTRequest() {
HttpRequest request = new HttpRequest(POST, "/root", "1.0");
assertEquals(POST, request.method());
assertEquals(Paths.get("/root"), request.path());
assertEquals("1.0", request.protocolVersion());
}
@Test
public void canResolveTheRootPath() {
HttpRequest request = new HttpRequest(POST, "/", "1.0");
Path root = Paths.get("/root/path");
Path requested = request.getResolvedPath(root);
assertEquals(Paths.get("/root/path"), requested);
}
@Test
public void canResolvePaths() {
HttpRequest request = new HttpRequest(POST, "/branch", "1.0");
Path root = Paths.get("/root/path");
Path requested = request.getResolvedPath(root);
assertEquals(Paths.get("/root/path/branch"), requested);
}
}
|
src/net/zephyrizing/http_server_test/HttpRequestTest.java
|
package net.zephyrizing.http_server_test;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Stream;
import net.zephyrizing.http_server.HttpProtocol;
import net.zephyrizing.http_server.HttpRequest;
import org.junit.Test;
import static java.util.Arrays.asList;
import static net.zephyrizing.http_server.HttpRequest.Method.*;
import static org.junit.Assert.*;
public class HttpRequestTest {
@Test
public void canCreateGETRequest() {
HttpRequest request = new HttpRequest(GET, "/", "1.1");
assertEquals(GET, request.method());
assertEquals(Paths.get("/"), request.path());
assertEquals("1.1", request.protocolVersion());
}
@Test
public void canCreatePOSTRequest() {
HttpRequest request = new HttpRequest(POST, "/root", "1.0");
assertEquals(POST, request.method());
assertEquals(Paths.get("/root"), request.path());
assertEquals("1.0", request.protocolVersion());
}
@Test
public void canResolveTheRootPath() {
HttpRequest request = new HttpRequest(POST, "/", "1.0");
Path root = Paths.get("/root/path");
Path requested = request.getResolvedPath(root);
assertEquals(Paths.get("/root/path"), requested);
}
@Test
public void canResolvePaths() {
HttpRequest request = new HttpRequest(POST, "/branch", "1.0");
Path root = Paths.get("/root/path");
Path requested = request.getResolvedPath(root);
assertEquals(Paths.get("/root/path/branch"), requested);
}
}
|
Add some readability whitespace to HttpRequestTests
|
src/net/zephyrizing/http_server_test/HttpRequestTest.java
|
Add some readability whitespace to HttpRequestTests
|
<ide><path>rc/net/zephyrizing/http_server_test/HttpRequestTest.java
<ide> @Test
<ide> public void canCreateGETRequest() {
<ide> HttpRequest request = new HttpRequest(GET, "/", "1.1");
<add>
<ide> assertEquals(GET, request.method());
<ide> assertEquals(Paths.get("/"), request.path());
<ide> assertEquals("1.1", request.protocolVersion());
<ide> @Test
<ide> public void canCreatePOSTRequest() {
<ide> HttpRequest request = new HttpRequest(POST, "/root", "1.0");
<add>
<ide> assertEquals(POST, request.method());
<ide> assertEquals(Paths.get("/root"), request.path());
<ide> assertEquals("1.0", request.protocolVersion());
|
|
Java
|
apache-2.0
|
7614737eaef0401011ca6082004e1fac5be6813f
| 0 |
plutext/sling,mmanski/sling,sdmcraft/sling,Sivaramvt/sling,mcdan/sling,plutext/sling,tteofili/sling,wimsymons/sling,ist-dresden/sling,mikibrv/sling,Nimco/sling,tyge68/sling,codders/k2-sling-fork,dulvac/sling,sdmcraft/sling,headwirecom/sling,cleliameneghin/sling,ieb/sling,nleite/sling,mikibrv/sling,mikibrv/sling,sdmcraft/sling,dulvac/sling,tteofili/sling,codders/k2-sling-fork,mmanski/sling,ffromm/sling,klcodanr/sling,JEBailey/sling,gutsy/sling,JEBailey/sling,tteofili/sling,roele/sling,klcodanr/sling,vladbailescu/sling,gutsy/sling,gutsy/sling,nleite/sling,vladbailescu/sling,anchela/sling,cleliameneghin/sling,labertasch/sling,roele/sling,trekawek/sling,mmanski/sling,JEBailey/sling,trekawek/sling,nleite/sling,awadheshv/sling,dulvac/sling,headwirecom/sling,roele/sling,SylvesterAbreu/sling,mcdan/sling,gutsy/sling,Nimco/sling,ffromm/sling,awadheshv/sling,plutext/sling,anchela/sling,awadheshv/sling,tyge68/sling,mcdan/sling,klcodanr/sling,wimsymons/sling,SylvesterAbreu/sling,plutext/sling,nleite/sling,gutsy/sling,mmanski/sling,tmaret/sling,tyge68/sling,Sivaramvt/sling,headwirecom/sling,sdmcraft/sling,Sivaramvt/sling,labertasch/sling,plutext/sling,JEBailey/sling,tteofili/sling,wimsymons/sling,roele/sling,mikibrv/sling,Sivaramvt/sling,mcdan/sling,labertasch/sling,JEBailey/sling,awadheshv/sling,mikibrv/sling,trekawek/sling,mcdan/sling,labertasch/sling,trekawek/sling,headwirecom/sling,ieb/sling,codders/k2-sling-fork,sdmcraft/sling,ieb/sling,ffromm/sling,SylvesterAbreu/sling,Nimco/sling,headwirecom/sling,mmanski/sling,ieb/sling,tyge68/sling,Sivaramvt/sling,tmaret/sling,Nimco/sling,ist-dresden/sling,anchela/sling,cleliameneghin/sling,tyge68/sling,nleite/sling,ffromm/sling,SylvesterAbreu/sling,ieb/sling,Sivaramvt/sling,nleite/sling,ffromm/sling,labertasch/sling,gutsy/sling,SylvesterAbreu/sling,awadheshv/sling,ist-dresden/sling,dulvac/sling,awadheshv/sling,mikibrv/sling,tmaret/sling,wimsymons/sling,ist-dresden/sling,mmanski/sling,anchela/sling,tmaret/sling,sdmcraft/sling,tteofili/sling,wimsymons/sling,tmaret/sling,cleliameneghin/sling,trekawek/sling,roele/sling,cleliameneghin/sling,Nimco/sling,tteofili/sling,mcdan/sling,vladbailescu/sling,anchela/sling,klcodanr/sling,tyge68/sling,dulvac/sling,trekawek/sling,klcodanr/sling,Nimco/sling,plutext/sling,SylvesterAbreu/sling,wimsymons/sling,klcodanr/sling,vladbailescu/sling,vladbailescu/sling,ist-dresden/sling,dulvac/sling,ieb/sling,ffromm/sling
|
/*
* 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.sling.servlets.post.impl.operations;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletContext;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.servlets.HtmlResponse;
import org.apache.sling.servlets.post.AbstractSlingPostOperation;
import org.apache.sling.servlets.post.SlingPostConstants;
import org.apache.sling.servlets.post.impl.helper.DateParser;
import org.apache.sling.servlets.post.impl.helper.NodeNameGenerator;
import org.apache.sling.servlets.post.impl.helper.RequestProperty;
import org.apache.sling.servlets.post.impl.helper.SlingFileUploadHandler;
import org.apache.sling.servlets.post.impl.helper.SlingPropertyValueHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>ModifyOperation</code> class implements the default operation
* called by the Sling default POST servlet if no operation is requested by the
* client. This operation is able to create and/or modify content.
*/
public class ModifyOperation extends AbstractSlingPostOperation {
/** default log */
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* utility class for generating node names
*/
private final NodeNameGenerator nodeNameGenerator;
private final DateParser dateParser;
/**
* handler that deals with file upload
*/
private final SlingFileUploadHandler uploadHandler;
public ModifyOperation(NodeNameGenerator nodeNameGenerator,
DateParser dateParser, ServletContext servletContext) {
this.nodeNameGenerator = nodeNameGenerator;
this.dateParser = dateParser;
this.uploadHandler = new SlingFileUploadHandler(servletContext);
}
@Override
protected void doRun(SlingHttpServletRequest request, HtmlResponse response)
throws RepositoryException {
Map<String, RequestProperty> reqProperties = collectContent(request,
response);
// do not change order unless you have a very good reason.
Session session = request.getResourceResolver().adaptTo(Session.class);
// ensure root of new content
processCreate(session, reqProperties, response);
// write content from existing content (@Move/CopyFrom parameters)
processMoves(session, reqProperties, response);
processCopies(session, reqProperties, response);
// cleanup any old content (@Delete parameters)
processDeletes(session, reqProperties, response);
// write content from form
writeContent(session, reqProperties, response);
// order content
String path = response.getPath();
orderNode(request, session.getItem(path));
}
@Override
protected String getItemPath(SlingHttpServletRequest request) {
// calculate the paths
StringBuffer rootPathBuf = new StringBuffer();
String suffix;
Resource currentResource = request.getResource();
if (ResourceUtil.isSyntheticResource(currentResource)) {
// no resource, treat the missing resource path as suffix
suffix = currentResource.getPath();
} else {
// resource for part of the path, use request suffix
suffix = request.getRequestPathInfo().getSuffix();
// and preset the path buffer with the resource path
rootPathBuf.append(currentResource.getPath());
}
// check for extensions or create suffix in the suffix
boolean doGenerateName = false;
if (suffix != null) {
// cut off any selectors/extension from the suffix
int dotPos = suffix.indexOf('.');
if (dotPos > 0) {
suffix = suffix.substring(0, dotPos);
}
// and check whether it is a create request (trailing /)
if (suffix.endsWith(SlingPostConstants.DEFAULT_CREATE_SUFFIX)) {
suffix = suffix.substring(0, suffix.length()
- SlingPostConstants.DEFAULT_CREATE_SUFFIX.length());
doGenerateName = true;
// or with the star suffix /*
} else if (suffix.endsWith(SlingPostConstants.STAR_CREATE_SUFFIX)) {
suffix = suffix.substring(0, suffix.length()
- SlingPostConstants.STAR_CREATE_SUFFIX.length());
doGenerateName = true;
}
// append the remains of the suffix to the path buffer
rootPathBuf.append(suffix);
}
String path = rootPathBuf.toString();
if (doGenerateName) {
try {
path = generateName(request, path);
} catch (RepositoryException re) {
throw new SlingException("Failed to generate name", re);
}
}
return path;
}
private String generateName(SlingHttpServletRequest request, String basePath)
throws RepositoryException {
// If the path ends with a *, create a node under its parent, with
// a generated node name
basePath += "/"
+ nodeNameGenerator.getNodeName(request.getRequestParameterMap(),
requireItemPathPrefix(request));
// if resulting path exists, add a suffix until it's not the case
// anymore
Session session = request.getResourceResolver().adaptTo(Session.class);
// if resulting path exists, add a suffix until it's not the case
// anymore
if (session.itemExists(basePath)) {
for (int idx = 0; idx < 1000; idx++) {
String newPath = basePath + "_" + idx;
if (!session.itemExists(newPath)) {
basePath = newPath;
break;
}
}
}
// if it still exists there are more than 1000 nodes ?
if (session.itemExists(basePath)) {
throw new RepositoryException(
"Collision in generated node names for path=" + basePath);
}
return basePath;
}
/**
* Create node(s) according to current request
*
* @throws RepositoryException if a repository error occurs
*/
private void processCreate(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
String path = response.getPath();
if (!session.itemExists(path)) {
deepGetOrCreateNode(session, path, reqProperties, response);
response.setCreateRequest(true);
}
}
/**
* Moves all repository content listed as repository move source in the
* request properties to the locations indicated by the resource properties.
*/
private void processMoves(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
for (RequestProperty property : reqProperties.values()) {
if (property.hasRepositoryMoveSource()) {
processMovesCopiesInternal(property, true, session,
reqProperties, response);
}
}
}
/**
* Copies all repository content listed as repository copy source in the
* request properties to the locations indicated by the resource properties.
*/
private void processCopies(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
for (RequestProperty property : reqProperties.values()) {
if (property.hasRepositoryCopySource()) {
processMovesCopiesInternal(property, false, session,
reqProperties, response);
}
}
}
/**
* Internal implementation of the
* {@link #processCopies(Session, Map, HtmlResponse)} and
* {@link #processMoves(Session, Map, HtmlResponse)} methods taking into
* account whether the source is actually a property or a node.
* <p>
* Any intermediary nodes to the destination as indicated by the
* <code>property</code> path are created using the
* <code>reqProperties</code> as indications for required node types.
*
* @param property The {@link RequestProperty} identifying the source
* content of the operation.
* @param isMove <code>true</code> if the source item is to be moved.
* Otherwise the source item is just copied.
* @param session The repository session to use to access the content
* @param reqProperties All accepted request properties. This is used to
* create intermediary nodes along the property path.
* @param response The <code>HtmlResponse</code> into which successfull
* copies and moves as well as intermediary node creations are
* recorded.
* @throws RepositoryException May be thrown if an error occurrs.
*/
private void processMovesCopiesInternal(RequestProperty property,
boolean isMove, Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
String propPath = property.getPath();
String source = property.getRepositorySource();
// only continue here, if the source really exists
if (session.itemExists(source)) {
// if the destination item already exists, remove it
// first, otherwise ensure the parent location
if (session.itemExists(propPath)) {
session.getItem(propPath).remove();
response.onDeleted(propPath);
} else {
deepGetOrCreateNode(session, property.getParentPath(),
reqProperties, response);
}
// move through the session and record operation
Item sourceItem = session.getItem(source);
if (sourceItem.isNode()) {
// node move/copy through session
if (isMove) {
session.move(source, propPath);
} else {
Node sourceNode = (Node) sourceItem;
Node destParent = (Node) session.getItem(property.getParentPath());
CopyOperation.copy(sourceNode, destParent,
property.getName());
}
} else {
// property move manually
Property sourceProperty = (Property) sourceItem;
// create destination property
Node destParent = (Node) session.getItem(property.getParentPath());
CopyOperation.copy(sourceProperty, destParent, null);
// remove source property (if not just copying)
if (isMove) {
sourceProperty.remove();
}
}
// make sure the property is not deleted even in case for a given
// property both @MoveFrom and @Delete is set
property.setDelete(false);
// record successful move
if (isMove) {
response.onMoved(source, propPath);
} else {
response.onCopied(source, propPath);
}
}
}
/**
* Removes all properties listed as {@link RequestProperty#isDelete()} from
* the repository.
*
* @param session The <code>javax.jcr.Session</code> used to access the
* repository to delete the properties.
* @param reqProperties The map of request properties to check for
* properties to be removed.
* @param response The <code>HtmlResponse</code> to be updated with
* information on deleted properties.
* @throws RepositoryException Is thrown if an error occurrs checking or
* removing properties.
*/
private void processDeletes(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
for (RequestProperty property : reqProperties.values()) {
if (property.isDelete()) {
String propPath = property.getPath();
if (session.itemExists(propPath)) {
session.getItem(propPath).remove();
response.onDeleted(propPath);
}
}
}
}
/**
* Writes back the content
*
* @throws RepositoryException if a repository error occurs
* @throws ServletException if an internal error occurs
*/
private void writeContent(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
SlingPropertyValueHandler propHandler = new SlingPropertyValueHandler(
dateParser, response);
for (RequestProperty prop : reqProperties.values()) {
if (prop.hasValues()) {
Node parent = deepGetOrCreateNode(session,
prop.getParentPath(), reqProperties, response);
// skip jcr special properties
if (prop.getName().equals("jcr:primaryType")
|| prop.getName().equals("jcr:mixinTypes")) {
continue;
}
if (prop.isFileUpload()) {
uploadHandler.setFile(parent, prop, response);
} else {
propHandler.setProperty(parent, prop);
}
}
}
}
/**
* Collects the properties that form the content to be written back to the
* repository.
*
* @throws RepositoryException if a repository error occurs
* @throws ServletException if an internal error occurs
*/
private Map<String, RequestProperty> collectContent(
SlingHttpServletRequest request, HtmlResponse response) {
boolean requireItemPrefix = requireItemPathPrefix(request);
// walk the request parameters and collect the properties
Map<String, RequestProperty> reqProperties = new HashMap<String, RequestProperty>();
for (Map.Entry<String, RequestParameter[]> e : request.getRequestParameterMap().entrySet()) {
final String paramName = e.getKey();
// do not store parameters with names starting with sling:post
if (paramName.startsWith(SlingPostConstants.RP_PREFIX)) {
continue;
}
// SLING-298: skip form encoding parameter
if (paramName.equals("_charset_")) {
continue;
}
// skip parameters that do not start with the save prefix
if (requireItemPrefix && !hasItemPathPrefix(paramName)) {
continue;
}
// ensure the paramName is an absolute property name
String propPath = toPropertyPath(paramName, response);
// @TypeHint example
// <input type="text" name="./age" />
// <input type="hidden" name="./age@TypeHint" value="long" />
// causes the setProperty using the 'long' property type
if (propPath.endsWith(SlingPostConstants.TYPE_HINT_SUFFIX)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.TYPE_HINT_SUFFIX);
final RequestParameter[] rp = e.getValue();
if (rp.length > 0) {
prop.setTypeHint(rp[0].getString());
}
continue;
}
// @DefaultValue
if (propPath.endsWith(SlingPostConstants.DEFAULT_VALUE_SUFFIX)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.DEFAULT_VALUE_SUFFIX);
prop.setDefaultValues(e.getValue());
continue;
}
// SLING-130: VALUE_FROM_SUFFIX means take the value of this
// property from a different field
// @ValueFrom example:
// <input name="./Text@ValueFrom" type="hidden" value="fulltext" />
// causes the JCR Text property to be set to the value of the
// fulltext form field.
if (propPath.endsWith(SlingPostConstants.VALUE_FROM_SUFFIX)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.VALUE_FROM_SUFFIX);
// @ValueFrom params must have exactly one value, else ignored
if (e.getValue().length == 1) {
String refName = e.getValue()[0].getString();
RequestParameter[] refValues = request.getRequestParameters(refName);
if (refValues != null) {
prop.setValues(refValues);
}
}
continue;
}
// SLING-458: Allow Removal of properties prior to update
// @Delete example:
// <input name="./Text@Delete" type="hidden" />
// causes the JCR Text property to be deleted before update
if (propPath.endsWith(SlingPostConstants.SUFFIX_DELETE)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath, SlingPostConstants.SUFFIX_DELETE);
prop.setDelete(true);
continue;
}
// SLING-455: @MoveFrom means moving content to another location
// @MoveFrom example:
// <input name="./Text@MoveFrom" type="hidden" value="/tmp/path" />
// causes the JCR Text property to be set by moving the /tmp/path
// property to Text.
if (propPath.endsWith(SlingPostConstants.SUFFIX_MOVE_FROM)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.SUFFIX_MOVE_FROM);
// @MoveFrom params must have exactly one value, else ignored
if (e.getValue().length == 1) {
String sourcePath = e.getValue()[0].getString();
prop.setRepositorySource(sourcePath, true);
}
continue;
}
// SLING-455: @CopyFrom means moving content to another location
// @CopyFrom example:
// <input name="./Text@CopyFrom" type="hidden" value="/tmp/path" />
// causes the JCR Text property to be set by copying the /tmp/path
// property to Text.
if (propPath.endsWith(SlingPostConstants.SUFFIX_COPY_FROM)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.SUFFIX_COPY_FROM);
// @MoveFrom params must have exactly one value, else ignored
if (e.getValue().length == 1) {
String sourcePath = e.getValue()[0].getString();
prop.setRepositorySource(sourcePath, false);
}
continue;
}
// plain property, create from values
RequestProperty prop = getOrCreateRequestProperty(reqProperties,
propPath, null);
prop.setValues(e.getValue());
}
return reqProperties;
}
/**
* Returns the <code>paramName</code> as an absolute (unnormalized)
* property path by prepending the response path (<code>response.getPath</code>)
* to the parameter name if not already absolute.
*/
private String toPropertyPath(String paramName, HtmlResponse response) {
if (!paramName.startsWith("/")) {
paramName = response.getPath() + "/" + paramName;
}
return paramName;
}
/**
* Returns the request property for the given property path. If such a
* request property does not exist yet it is created and stored in the
* <code>props</code>.
*
* @param props The map of already seen request properties.
* @param paramName The absolute path of the property including the
* <code>suffix</code> to be looked up.
* @param suffix The (optional) suffix to remove from the
* <code>paramName</code> before looking it up.
* @return The {@link RequestProperty} for the <code>paramName</code>.
*/
private RequestProperty getOrCreateRequestProperty(
Map<String, RequestProperty> props, String paramName, String suffix) {
if (suffix != null && paramName.endsWith(suffix)) {
paramName = paramName.substring(0, paramName.length()
- suffix.length());
}
RequestProperty prop = props.get(paramName);
if (prop == null) {
prop = new RequestProperty(paramName);
props.put(paramName, prop);
}
return prop;
}
/**
* Checks the collected content for a jcr:primaryType property at the
* specified path.
*
* @param path path to check
* @return the primary type or <code>null</code>
*/
private String getPrimaryType(Map<String, RequestProperty> reqProperties,
String path) {
RequestProperty prop = reqProperties.get(path + "/jcr:primaryType");
return prop == null ? null : prop.getStringValues()[0];
}
/**
* Checks the collected content for a jcr:mixinTypes property at the
* specified path.
*
* @param path path to check
* @return the mixin types or <code>null</code>
*/
private String[] getMixinTypes(Map<String, RequestProperty> reqProperties,
String path) {
RequestProperty prop = reqProperties.get(path + "/jcr:mixinTypes");
return prop == null ? null : prop.getStringValues();
}
/**
* Deep gets or creates a node, parent-padding with default nodes nodes. If
* the path is empty, the given parent node is returned.
*
* @param path path to node that needs to be deep-created
* @return node at path
* @throws RepositoryException if an error occurs
* @throws IllegalArgumentException if the path is relative and parent is
* <code>null</code>
*/
private Node deepGetOrCreateNode(Session session, String path,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
if (log.isDebugEnabled()) {
log.debug("Deep-creating Node '{}'", path);
}
if (path == null || !path.startsWith("/")) {
throw new IllegalArgumentException("path must be an absolute path.");
}
// get the starting node
String startingNodePath = path;
Node startingNode = null;
while (startingNode == null) {
if (startingNodePath.equals("/")) {
startingNode = session.getRootNode();
} else if (session.itemExists(startingNodePath)) {
startingNode = (Node) session.getItem(startingNodePath);
} else {
int pos = startingNodePath.lastIndexOf('/');
if (pos > 0) {
startingNodePath = startingNodePath.substring(0, pos);
} else {
startingNodePath = "/";
}
}
}
// is the searched node already existing?
if (startingNodePath.length() == path.length()) {
return startingNode;
}
// create nodes
int from = (startingNodePath.length() == 1
? 1
: startingNodePath.length() + 1);
Node node = startingNode;
while (from > 0) {
final int to = path.indexOf('/', from);
final String name = to < 0 ? path.substring(from) : path.substring(
from, to);
// although the node should not exist (according to the first test
// above)
// we do a sanety check.
if (node.hasNode(name)) {
node = node.getNode(name);
} else {
final String tmpPath = to < 0 ? path : path.substring(0, to);
// check for node type
final String nodeType = getPrimaryType(reqProperties, tmpPath);
if (nodeType != null) {
node = node.addNode(name, nodeType);
} else {
node = node.addNode(name);
}
// check for mixin types
final String[] mixinTypes = getMixinTypes(reqProperties,
tmpPath);
if (mixinTypes != null) {
for (String mix : mixinTypes) {
node.addMixin(mix);
}
}
response.onCreated(node.getPath());
}
from = to + 1;
}
return node;
}
}
|
servlets/post/src/main/java/org/apache/sling/servlets/post/impl/operations/ModifyOperation.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.sling.servlets.post.impl.operations;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletContext;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.servlets.HtmlResponse;
import org.apache.sling.servlets.post.AbstractSlingPostOperation;
import org.apache.sling.servlets.post.SlingPostConstants;
import org.apache.sling.servlets.post.impl.helper.DateParser;
import org.apache.sling.servlets.post.impl.helper.NodeNameGenerator;
import org.apache.sling.servlets.post.impl.helper.RequestProperty;
import org.apache.sling.servlets.post.impl.helper.SlingFileUploadHandler;
import org.apache.sling.servlets.post.impl.helper.SlingPropertyValueHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>ModifyOperation</code> class implements the default operation
* called by the Sling default POST servlet if no operation is requested by the
* client. This operation is able to create and/or modify content.
*/
public class ModifyOperation extends AbstractSlingPostOperation {
/** default log */
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* utility class for generating node names
*/
private final NodeNameGenerator nodeNameGenerator;
private final DateParser dateParser;
/**
* handler that deals with file upload
*/
private final SlingFileUploadHandler uploadHandler;
public ModifyOperation(NodeNameGenerator nodeNameGenerator,
DateParser dateParser, ServletContext servletContext) {
this.nodeNameGenerator = nodeNameGenerator;
this.dateParser = dateParser;
this.uploadHandler = new SlingFileUploadHandler(servletContext);
}
@Override
protected void doRun(SlingHttpServletRequest request, HtmlResponse response)
throws RepositoryException {
Map<String, RequestProperty> reqProperties = collectContent(request,
response);
// do not change order unless you have a very good reason.
Session session = request.getResourceResolver().adaptTo(Session.class);
// ensure root of new content
processCreate(session, reqProperties, response);
// cleanup any old content (@Delete parameters)
processDeletes(session, reqProperties, response);
// write content from existing content (@Move/CopyFrom parameters)
processMoves(session, reqProperties, response);
processCopies(session, reqProperties, response);
// write content from form
writeContent(session, reqProperties, response);
// order content
String path = response.getPath();
orderNode(request, session.getItem(path));
}
@Override
protected String getItemPath(SlingHttpServletRequest request) {
// calculate the paths
StringBuffer rootPathBuf = new StringBuffer();
String suffix;
Resource currentResource = request.getResource();
if (ResourceUtil.isSyntheticResource(currentResource)) {
// no resource, treat the missing resource path as suffix
suffix = currentResource.getPath();
} else {
// resource for part of the path, use request suffix
suffix = request.getRequestPathInfo().getSuffix();
// and preset the path buffer with the resource path
rootPathBuf.append(currentResource.getPath());
}
// check for extensions or create suffix in the suffix
boolean doGenerateName = false;
if (suffix != null) {
// cut off any selectors/extension from the suffix
int dotPos = suffix.indexOf('.');
if (dotPos > 0) {
suffix = suffix.substring(0, dotPos);
}
// and check whether it is a create request (trailing /)
if (suffix.endsWith(SlingPostConstants.DEFAULT_CREATE_SUFFIX)) {
suffix = suffix.substring(0, suffix.length()
- SlingPostConstants.DEFAULT_CREATE_SUFFIX.length());
doGenerateName = true;
// or with the star suffix /*
} else if (suffix.endsWith(SlingPostConstants.STAR_CREATE_SUFFIX)) {
suffix = suffix.substring(0, suffix.length()
- SlingPostConstants.STAR_CREATE_SUFFIX.length());
doGenerateName = true;
}
// append the remains of the suffix to the path buffer
rootPathBuf.append(suffix);
}
String path = rootPathBuf.toString();
if (doGenerateName) {
try {
path = generateName(request, path);
} catch (RepositoryException re) {
throw new SlingException("Failed to generate name", re);
}
}
return path;
}
private String generateName(SlingHttpServletRequest request, String basePath)
throws RepositoryException {
// If the path ends with a *, create a node under its parent, with
// a generated node name
basePath += "/"
+ nodeNameGenerator.getNodeName(request.getRequestParameterMap(),
requireItemPathPrefix(request));
// if resulting path exists, add a suffix until it's not the case
// anymore
Session session = request.getResourceResolver().adaptTo(Session.class);
// if resulting path exists, add a suffix until it's not the case
// anymore
if (session.itemExists(basePath)) {
for (int idx = 0; idx < 1000; idx++) {
String newPath = basePath + "_" + idx;
if (!session.itemExists(newPath)) {
basePath = newPath;
break;
}
}
}
// if it still exists there are more than 1000 nodes ?
if (session.itemExists(basePath)) {
throw new RepositoryException(
"Collision in generated node names for path=" + basePath);
}
return basePath;
}
/**
* Create node(s) according to current request
*
* @throws RepositoryException if a repository error occurs
*/
private void processCreate(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
String path = response.getPath();
if (!session.itemExists(path)) {
deepGetOrCreateNode(session, path, reqProperties, response);
response.setCreateRequest(true);
}
}
/**
* Moves all repository content listed as repository move source in the
* request properties to the locations indicated by the resource properties.
*/
private void processMoves(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
for (RequestProperty property : reqProperties.values()) {
if (property.hasRepositoryMoveSource()) {
processMovesCopiesInternal(property, true, session,
reqProperties, response);
}
}
}
/**
* Copies all repository content listed as repository copy source in the
* request properties to the locations indicated by the resource properties.
*/
private void processCopies(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
for (RequestProperty property : reqProperties.values()) {
if (property.hasRepositoryCopySource()) {
processMovesCopiesInternal(property, false, session,
reqProperties, response);
}
}
}
/**
* Internal implementation of the
* {@link #processCopies(Session, Map, HtmlResponse)} and
* {@link #processMoves(Session, Map, HtmlResponse)} methods taking into
* account whether the source is actually a property or a node.
* <p>
* Any intermediary nodes to the destination as indicated by the
* <code>property</code> path are created using the
* <code>reqProperties</code> as indications for required node types.
*
* @param property The {@link RequestProperty} identifying the source
* content of the operation.
* @param isMove <code>true</code> if the source item is to be moved.
* Otherwise the source item is just copied.
* @param session The repository session to use to access the content
* @param reqProperties All accepted request properties. This is used to
* create intermediary nodes along the property path.
* @param response The <code>HtmlResponse</code> into which successfull
* copies and moves as well as intermediary node creations are
* recorded.
* @throws RepositoryException May be thrown if an error occurrs.
*/
private void processMovesCopiesInternal(RequestProperty property,
boolean isMove, Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
String propPath = property.getPath();
String source = property.getRepositorySource();
// only continue here, if the source really exists
if (session.itemExists(source)) {
// if the destination item already exists, remove it
// first, otherwise ensure the parent location
if (session.itemExists(propPath)) {
session.getItem(propPath).remove();
response.onDeleted(propPath);
} else {
deepGetOrCreateNode(session, property.getParentPath(),
reqProperties, response);
}
// move through the session and record operation
Item sourceItem = session.getItem(source);
if (sourceItem.isNode()) {
// node move/copy through session
if (isMove) {
session.move(source, propPath);
} else {
Node sourceNode = (Node) sourceItem;
Node destParent = (Node) session.getItem(property.getParentPath());
CopyOperation.copy(sourceNode, destParent,
property.getName());
}
} else {
// property move manually
Property sourceProperty = (Property) sourceItem;
// create destination property
Node destParent = (Node) session.getItem(property.getParentPath());
CopyOperation.copy(sourceProperty, destParent, null);
// remove source property (if not just copying)
if (isMove) {
sourceProperty.remove();
}
}
// record successful move
if (isMove) {
response.onMoved(source, propPath);
} else {
response.onCopied(source, propPath);
}
}
}
/**
* Removes all properties listed as {@link RequestProperty#isDelete()} from
* the repository.
*
* @param session The <code>javax.jcr.Session</code> used to access the
* repository to delete the properties.
* @param reqProperties The map of request properties to check for
* properties to be removed.
* @param response The <code>HtmlResponse</code> to be updated with
* information on deleted properties.
* @throws RepositoryException Is thrown if an error occurrs checking or
* removing properties.
*/
private void processDeletes(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
for (RequestProperty property : reqProperties.values()) {
if (property.isDelete()) {
String propPath = property.getPath();
if (session.itemExists(propPath)) {
session.getItem(propPath).remove();
response.onDeleted(propPath);
}
}
}
}
/**
* Writes back the content
*
* @throws RepositoryException if a repository error occurs
* @throws ServletException if an internal error occurs
*/
private void writeContent(Session session,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
SlingPropertyValueHandler propHandler = new SlingPropertyValueHandler(
dateParser, response);
for (RequestProperty prop : reqProperties.values()) {
if (prop.hasValues()) {
Node parent = deepGetOrCreateNode(session,
prop.getParentPath(), reqProperties, response);
// skip jcr special properties
if (prop.getName().equals("jcr:primaryType")
|| prop.getName().equals("jcr:mixinTypes")) {
continue;
}
if (prop.isFileUpload()) {
uploadHandler.setFile(parent, prop, response);
} else {
propHandler.setProperty(parent, prop);
}
}
}
}
/**
* Collects the properties that form the content to be written back to the
* repository.
*
* @throws RepositoryException if a repository error occurs
* @throws ServletException if an internal error occurs
*/
private Map<String, RequestProperty> collectContent(
SlingHttpServletRequest request, HtmlResponse response) {
boolean requireItemPrefix = requireItemPathPrefix(request);
// walk the request parameters and collect the properties
Map<String, RequestProperty> reqProperties = new HashMap<String, RequestProperty>();
for (Map.Entry<String, RequestParameter[]> e : request.getRequestParameterMap().entrySet()) {
final String paramName = e.getKey();
// do not store parameters with names starting with sling:post
if (paramName.startsWith(SlingPostConstants.RP_PREFIX)) {
continue;
}
// SLING-298: skip form encoding parameter
if (paramName.equals("_charset_")) {
continue;
}
// skip parameters that do not start with the save prefix
if (requireItemPrefix && !hasItemPathPrefix(paramName)) {
continue;
}
// ensure the paramName is an absolute property name
String propPath = toPropertyPath(paramName, response);
// @TypeHint example
// <input type="text" name="./age" />
// <input type="hidden" name="./age@TypeHint" value="long" />
// causes the setProperty using the 'long' property type
if (propPath.endsWith(SlingPostConstants.TYPE_HINT_SUFFIX)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.TYPE_HINT_SUFFIX);
final RequestParameter[] rp = e.getValue();
if (rp.length > 0) {
prop.setTypeHint(rp[0].getString());
}
continue;
}
// @DefaultValue
if (propPath.endsWith(SlingPostConstants.DEFAULT_VALUE_SUFFIX)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.DEFAULT_VALUE_SUFFIX);
prop.setDefaultValues(e.getValue());
continue;
}
// SLING-130: VALUE_FROM_SUFFIX means take the value of this
// property from a different field
// @ValueFrom example:
// <input name="./Text@ValueFrom" type="hidden" value="fulltext" />
// causes the JCR Text property to be set to the value of the
// fulltext form field.
if (propPath.endsWith(SlingPostConstants.VALUE_FROM_SUFFIX)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.VALUE_FROM_SUFFIX);
// @ValueFrom params must have exactly one value, else ignored
if (e.getValue().length == 1) {
String refName = e.getValue()[0].getString();
RequestParameter[] refValues = request.getRequestParameters(refName);
if (refValues != null) {
prop.setValues(refValues);
}
}
continue;
}
// SLING-458: Allow Removal of properties prior to update
// @Delete example:
// <input name="./Text@Delete" type="hidden" />
// causes the JCR Text property to be deleted before update
if (propPath.endsWith(SlingPostConstants.SUFFIX_DELETE)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath, SlingPostConstants.SUFFIX_DELETE);
prop.setDelete(true);
continue;
}
// SLING-455: @MoveFrom means moving content to another location
// @MoveFrom example:
// <input name="./Text@MoveFrom" type="hidden" value="/tmp/path" />
// causes the JCR Text property to be set by moving the /tmp/path
// property to Text.
if (propPath.endsWith(SlingPostConstants.SUFFIX_MOVE_FROM)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.SUFFIX_MOVE_FROM);
// @MoveFrom params must have exactly one value, else ignored
if (e.getValue().length == 1) {
String sourcePath = e.getValue()[0].getString();
prop.setRepositorySource(sourcePath, true);
}
continue;
}
// SLING-455: @CopyFrom means moving content to another location
// @CopyFrom example:
// <input name="./Text@CopyFrom" type="hidden" value="/tmp/path" />
// causes the JCR Text property to be set by copying the /tmp/path
// property to Text.
if (propPath.endsWith(SlingPostConstants.SUFFIX_COPY_FROM)) {
RequestProperty prop = getOrCreateRequestProperty(
reqProperties, propPath,
SlingPostConstants.SUFFIX_COPY_FROM);
// @MoveFrom params must have exactly one value, else ignored
if (e.getValue().length == 1) {
String sourcePath = e.getValue()[0].getString();
prop.setRepositorySource(sourcePath, false);
}
continue;
}
// plain property, create from values
RequestProperty prop = getOrCreateRequestProperty(reqProperties,
propPath, null);
prop.setValues(e.getValue());
}
return reqProperties;
}
/**
* Returns the <code>paramName</code> as an absolute (unnormalized)
* property path by prepending the response path (<code>response.getPath</code>)
* to the parameter name if not already absolute.
*/
private String toPropertyPath(String paramName, HtmlResponse response) {
if (!paramName.startsWith("/")) {
paramName = response.getPath() + "/" + paramName;
}
return paramName;
}
/**
* Returns the request property for the given property path. If such a
* request property does not exist yet it is created and stored in the
* <code>props</code>.
*
* @param props The map of already seen request properties.
* @param paramName The absolute path of the property including the
* <code>suffix</code> to be looked up.
* @param suffix The (optional) suffix to remove from the
* <code>paramName</code> before looking it up.
* @return The {@link RequestProperty} for the <code>paramName</code>.
*/
private RequestProperty getOrCreateRequestProperty(
Map<String, RequestProperty> props, String paramName, String suffix) {
if (suffix != null && paramName.endsWith(suffix)) {
paramName = paramName.substring(0, paramName.length()
- suffix.length());
}
RequestProperty prop = props.get(paramName);
if (prop == null) {
prop = new RequestProperty(paramName);
props.put(paramName, prop);
}
return prop;
}
/**
* Checks the collected content for a jcr:primaryType property at the
* specified path.
*
* @param path path to check
* @return the primary type or <code>null</code>
*/
private String getPrimaryType(Map<String, RequestProperty> reqProperties,
String path) {
RequestProperty prop = reqProperties.get(path + "/jcr:primaryType");
return prop == null ? null : prop.getStringValues()[0];
}
/**
* Checks the collected content for a jcr:mixinTypes property at the
* specified path.
*
* @param path path to check
* @return the mixin types or <code>null</code>
*/
private String[] getMixinTypes(Map<String, RequestProperty> reqProperties,
String path) {
RequestProperty prop = reqProperties.get(path + "/jcr:mixinTypes");
return prop == null ? null : prop.getStringValues();
}
/**
* Deep gets or creates a node, parent-padding with default nodes nodes. If
* the path is empty, the given parent node is returned.
*
* @param path path to node that needs to be deep-created
* @return node at path
* @throws RepositoryException if an error occurs
* @throws IllegalArgumentException if the path is relative and parent is
* <code>null</code>
*/
private Node deepGetOrCreateNode(Session session, String path,
Map<String, RequestProperty> reqProperties, HtmlResponse response)
throws RepositoryException {
if (log.isDebugEnabled()) {
log.debug("Deep-creating Node '{}'", path);
}
if (path == null || !path.startsWith("/")) {
throw new IllegalArgumentException("path must be an absolute path.");
}
// get the starting node
String startingNodePath = path;
Node startingNode = null;
while (startingNode == null) {
if (startingNodePath.equals("/")) {
startingNode = session.getRootNode();
} else if (session.itemExists(startingNodePath)) {
startingNode = (Node) session.getItem(startingNodePath);
} else {
int pos = startingNodePath.lastIndexOf('/');
if (pos > 0) {
startingNodePath = startingNodePath.substring(0, pos);
} else {
startingNodePath = "/";
}
}
}
// is the searched node already existing?
if (startingNodePath.length() == path.length()) {
return startingNode;
}
// create nodes
int from = (startingNodePath.length() == 1
? 1
: startingNodePath.length() + 1);
Node node = startingNode;
while (from > 0) {
final int to = path.indexOf('/', from);
final String name = to < 0 ? path.substring(from) : path.substring(
from, to);
// although the node should not exist (according to the first test
// above)
// we do a sanety check.
if (node.hasNode(name)) {
node = node.getNode(name);
} else {
final String tmpPath = to < 0 ? path : path.substring(0, to);
// check for node type
final String nodeType = getPrimaryType(reqProperties, tmpPath);
if (nodeType != null) {
node = node.addNode(name, nodeType);
} else {
node = node.addNode(name);
}
// check for mixin types
final String[] mixinTypes = getMixinTypes(reqProperties,
tmpPath);
if (mixinTypes != null) {
for (String mix : mixinTypes) {
node.addMixin(mix);
}
}
response.onCreated(node.getPath());
}
from = to + 1;
}
return node;
}
}
|
SLING-474 Move @Delete handling after @Move/CopyFrom handling and ensure the
moved/copied property is not removed after a successfull move/copy.
git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@660415 13f79535-47bb-0310-9956-ffa450edef68
|
servlets/post/src/main/java/org/apache/sling/servlets/post/impl/operations/ModifyOperation.java
|
SLING-474 Move @Delete handling after @Move/CopyFrom handling and ensure the moved/copied property is not removed after a successfull move/copy.
|
<ide><path>ervlets/post/src/main/java/org/apache/sling/servlets/post/impl/operations/ModifyOperation.java
<ide> // ensure root of new content
<ide> processCreate(session, reqProperties, response);
<ide>
<del> // cleanup any old content (@Delete parameters)
<del> processDeletes(session, reqProperties, response);
<del>
<ide> // write content from existing content (@Move/CopyFrom parameters)
<ide> processMoves(session, reqProperties, response);
<ide> processCopies(session, reqProperties, response);
<add>
<add> // cleanup any old content (@Delete parameters)
<add> processDeletes(session, reqProperties, response);
<ide>
<ide> // write content from form
<ide> writeContent(session, reqProperties, response);
<ide> }
<ide> }
<ide>
<add> // make sure the property is not deleted even in case for a given
<add> // property both @MoveFrom and @Delete is set
<add> property.setDelete(false);
<add>
<ide> // record successful move
<ide> if (isMove) {
<ide> response.onMoved(source, propPath);
|
|
Java
|
apache-2.0
|
cc8c23ddfb50f19016a97233a0b97bb6d0adb023
| 0 |
micrometer-metrics/micrometer,micrometer-metrics/micrometer,micrometer-metrics/micrometer
|
/**
* Copyright 2017 Pivotal Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.metrics.boot;
import org.aspectj.lang.JoinPoint;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.metrics.instrument.MeterRegistry;
import org.springframework.metrics.instrument.TagFormatter;
import org.springframework.metrics.instrument.scheduling.MetricsSchedulingAspect;
import org.springframework.web.client.RestTemplate;
/**
* Metrics configuration for Spring 4/Boot 1.x
*
* @author Jon Schneider
*/
@Configuration
// this class didn't exist until Spring 5
@ConditionalOnMissingClass("org.springframework.web.server.WebFilter") // TODO got to be a better way...
@Import({
InstrumentRestTemplateConfiguration.class,
RecommendedMeterBinders.class,
MeterBinderRegistration.class
})
class MetricsBoot1Configuration {
@Bean
@ConditionalOnMissingBean(TagFormatter.class)
public TagFormatter tagFormatter() {
return new TagFormatter() {};
}
@Configuration
@ConditionalOnWebApplication
@Import(InstrumentServletRequestConfiguration.class)
static class WebMvcConfiguration {}
/**
* If AOP is not enabled, scheduled interception will not work.
*/
@Bean
@ConditionalOnClass(name = {"org.springframework.web.client.RestTemplate", "org.aopalliance.intercept.JoinPoint"})
@ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true)
public MetricsSchedulingAspect metricsSchedulingAspect(MeterRegistry registry) {
return new MetricsSchedulingAspect(registry);
}
/**
* If AOP is not enabled, client request interception will still work, but the URI tag
* will always be evaluated to "none".
*/
@Configuration
@ConditionalOnClass(name = {"org.springframework.web.client.RestTemplate", "org.aopalliance.intercept.JoinPoint"})
@ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true)
static class MetricsRestTemplateAspectConfiguration {
@Bean
RestTemplateUrlTemplateCapturingAspect restTemplateUrlTemplateCapturingAspect() {
return new RestTemplateUrlTemplateCapturingAspect();
}
}
}
|
src/main/java/org/springframework/metrics/boot/MetricsBoot1Configuration.java
|
/**
* Copyright 2017 Pivotal Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.metrics.boot;
import org.aspectj.lang.JoinPoint;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.metrics.instrument.MeterRegistry;
import org.springframework.metrics.instrument.TagFormatter;
import org.springframework.metrics.instrument.scheduling.MetricsSchedulingAspect;
import org.springframework.web.client.RestTemplate;
/**
* Metrics configuration for Spring 4/Boot 1.x
*
* @author Jon Schneider
*/
@Configuration
@ConditionalOnMissingClass("org.springframework.web.server.WebFilter") // TODO got to be a better way...
@Import({
InstrumentRestTemplateConfiguration.class,
RecommendedMeterBinders.class,
MeterBinderRegistration.class
})
class MetricsBoot1Configuration {
@Bean
@ConditionalOnMissingBean(TagFormatter.class)
public TagFormatter tagFormatter() {
return new TagFormatter() {};
}
@Configuration
@ConditionalOnWebApplication
@Import(InstrumentServletRequestConfiguration.class)
static class WebMvcConfiguration {}
/**
* If AOP is not enabled, scheduled interception will not work.
*/
@Bean
@ConditionalOnClass({RestTemplate.class, JoinPoint.class})
@ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true)
public MetricsSchedulingAspect metricsSchedulingAspect(MeterRegistry registry) {
return new MetricsSchedulingAspect(registry);
}
/**
* If AOP is not enabled, client request interception will still work, but the URI tag
* will always be evaluated to "none".
*/
@Configuration
@ConditionalOnClass({RestTemplate.class, JoinPoint.class})
@ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true)
static class MetricsRestTemplateAspectConfiguration {
@Bean
RestTemplateUrlTemplateCapturingAspect restTemplateUrlTemplateCapturingAspect() {
return new RestTemplateUrlTemplateCapturingAspect();
}
}
}
|
Fix boot 1 configuration to not require AOP
|
src/main/java/org/springframework/metrics/boot/MetricsBoot1Configuration.java
|
Fix boot 1 configuration to not require AOP
|
<ide><path>rc/main/java/org/springframework/metrics/boot/MetricsBoot1Configuration.java
<ide> * @author Jon Schneider
<ide> */
<ide> @Configuration
<add>// this class didn't exist until Spring 5
<ide> @ConditionalOnMissingClass("org.springframework.web.server.WebFilter") // TODO got to be a better way...
<ide> @Import({
<ide> InstrumentRestTemplateConfiguration.class,
<ide> * If AOP is not enabled, scheduled interception will not work.
<ide> */
<ide> @Bean
<del> @ConditionalOnClass({RestTemplate.class, JoinPoint.class})
<add> @ConditionalOnClass(name = {"org.springframework.web.client.RestTemplate", "org.aopalliance.intercept.JoinPoint"})
<ide> @ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true)
<ide> public MetricsSchedulingAspect metricsSchedulingAspect(MeterRegistry registry) {
<ide> return new MetricsSchedulingAspect(registry);
<ide> * will always be evaluated to "none".
<ide> */
<ide> @Configuration
<del> @ConditionalOnClass({RestTemplate.class, JoinPoint.class})
<add> @ConditionalOnClass(name = {"org.springframework.web.client.RestTemplate", "org.aopalliance.intercept.JoinPoint"})
<ide> @ConditionalOnProperty(value = "spring.aop.enabled", havingValue = "true", matchIfMissing = true)
<ide> static class MetricsRestTemplateAspectConfiguration {
<ide> @Bean
|
|
JavaScript
|
apache-2.0
|
7b8f485493e5ba30f8fb13e12527be40efda087d
| 0 |
jadman02/testphonegap,jadman02/testphonegap
|
var refreshIntervalId;
var desktoparray = ['media/dateicon.png','media/duckicon.png','media/datetongue.png','media/dateorducklogo.png']
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function sendNotification(targetto,param){
firebase.auth().currentUser.getToken().then(function(idToken) {
var titlestring;
var bodystring;
if (param == 1){titlestring = 'New match created';bodystring='With ' + f_first;}
if (param == 2){titlestring = 'New date request received';bodystring='From ' + f_first;}
if (param == 3){titlestring = 'New date confirmed';bodystring='By ' + f_first;}
if (param == 4){titlestring = 'New message received';bodystring='From ' + f_first;}
if (param == 5){titlestring = 'New photo received';bodystring='From ' + f_first;}
if (param == 6){titlestring = 'Date cancelled';bodystring='With ' + f_first;}
var typesend;
if (d_type){typesend = d_type;}
else {typesend = 'date';}
$.post( "http://www.dateorduck.com/sendnotification.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,target:targetto,titlestring:titlestring,bodystring:bodystring,param:param,type:typesend,firstname:f_first,senderid:f_uid} )
.done(function( data ) {
//alert(JSON.stringify(data));
});
});
}
function sharePop(){
facebookConnectPlugin.showDialog({
method: "share",
href: "http://www.dateorduck.com/",
hashtag: "#dateorduck"
//share_feedWeb: true, // iOS only
}, function (response) {}, function (response) {})
}
function appLink(){
facebookConnectPlugin.appInvite(
{
url: "https://fb.me/1554148374659639",
picture: "https://scontent-syd2-1.xx.fbcdn.net/v/t1.0-9/20708231_1724210881205783_3080280387189012101_n.png?oh=105b6d85f2f4bb0e33f3e4909113cdc7&oe=5A3348E7"
},
function(obj){
if(obj) {
if(obj.completionGesture == "cancel") {
// user canceled, bad guy
} else {
// user really invited someone :)
}
} else {
// user just pressed done, bad guy
}
},
function(obj){
// error
// alert(JSON.stringify(obj));
}
);
}
function fcm(){
NativeKeyboard.showMessenger({
onSubmit: function(text) {
//console.log("The user typed: " + text);
}
});
}
var displaySuggestions = function(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
myApp.alert('Could not confirm your hometown.', 'Error');
clearHometown();
} else{
var predictionsarray = [];
$('.hometownprediction').remove();
predictions.forEach(function(prediction) {
predictionsarray.push(prediction.description);
});
}
var hometownpicker = myApp.picker({
input: '#homesearch',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } },
onChange:function (p, values, displayValues){$( '#homesearch' ).addClass("profilevaluechosen");},
onClose:function (p){hometownpicker.destroy();},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'hometown\')">' +
'<a href="#" class="link close-picker" onclick="clearHometown();" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: predictionsarray
}
]
});
hometownpicker.open();
};
function checkHometown(){
var hometownquery = $('#homesearch').val();
if (hometownquery == ''){
return false;}
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({ input: hometownquery,types: ['(cities)'] }, displaySuggestions);
}
function clearHometown(){
$('#homesearch').val('');
}
function newHometown(){
$('#homesearch').remove();
$('.hometown-input').append('<textarea class="resizable" id="homesearch" onclick="newHometown()" onblur="checkHometown()" placeholder="Hide" style="min-height:60px;max-height:132px;"></textarea>');
$('#homesearch').focus();
}
function fQuery(){
$.ajax({
url: "https://graph.facebook.com/v2.4/784956164912201?fields=context.fields(friends_using_app)",
type: "get",
data: { access_token: f_token},
success: function (response, textStatus, jqXHR) {
$.ajax({
url: "https://graph.facebook.com/v2.4/"+response.context.id+"/friends_using_app?summary=1",
type: "get",
data: { access_token: f_token},
success: function (response1, textStatus, jqXHR) {
try {
response1.summary.total_count;
var friendstring;
if (response1.summary.total_count ==0) {friendstring = 'No friends use this app'}
if (response1.summary.total_count ==1) {friendstring = '1 friend uses this app' }
if (response1.summary.total_count >1) {friendstring = response1.summary.total_count + ' friends use this app' }
if (response1.summary.total_count > 9){
nearbyshare = true;
recentshare = true;
$('.nearby-title').html('Nearby First');
$('.recent-title').html('Recently Online');
$('.nearby-helper').hide();
$('.recent-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.recent-wrapper').css("-webkit-filter","none");
firebase.database().ref('users/' + f_uid).update({
recentfriends:'Y'
}).then(function() {});
}
if ((response1.summary.total_count > 4) && (response1.summary.total_count <10)){
if ($('.no-results-div').length > 0) {$('.nearby-helper').hide();
$('.recent-helper').hide();}
else{
nearbyshare = true;
$('.nearby-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.nearby-title').html('Nearby First');
$('.recent-title').html('<i class="pe-7s-lock pe-lg"></i> Recently Online (Locked)');
recentshare = false;
$('.recent-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-helper').show();
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
//$('.recent-helper').html('<p style="margin-top:-10px;padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to <br/>unlock this feature.</p>');
//$('.summary-helper').html('<p style="font-weight:bold;">'+friendstring+'</p><div class="row"><div class="col-50"><a class="button active external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? ">Send SMS</a></div><div class="col-50"><a class="button active external" href="#" onclick="appLink()">Invite Friends</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">We appreciate your help to grow this app!</p>');
}
}
if (response1.summary.total_count < 5){
if ($('.no-results-div').length > 0) {$('.nearby-helper').hide();
$('.recent-helper').hide();}
else{
nearbyshare = false;
recentshare = false;
$('.nearby-helper').show();
$('.recent-helper').show();
$('.nearby-title').html('<i class="pe-7s-lock pe-lg"></i> Nearby First (Locked)');
$('.recent-title').html('<i class="pe-7s-lock pe-lg"></i> Recently Online (Locked)');
$('.nearby-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
$('.nearby-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">5</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
//$('.recent-helper').html('<p style="margin-top:-10px;padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to <br/>unlock this feature.</p>');
// $('.nearby-helper').html('<p style=margin-top:-10px;"padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">5</span> or more friends on Facebook to <br/>unlock this feature.</p>');
// $('.summary-helper').html('<p style="font-weight:bold;"></p><div class="row"><div class="col-50"><a class="button active external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? ">Send SMS</a></div><div class="col-50"><a class="button active external" href="#" onclick="appLink()">Invite Friends</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">We appreciate your help to grow this app!</p>');
}
}
} catch(err) {
$('.nearby-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">Invite friends to use this app</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="getFriends()">Find friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">5</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">Invite friends to use this app</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="getFriends()">Find friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
// $('.recent-helper').html('<p style="padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to unlock this feature.</p>');
// $('.nearby-helper').html('<p style="padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">5</span> or more friends on Facebook to unlock this feature.</p>');
//$('.summary-helper').html('<p style="font-weight:bold;">Invite friends to unlock features</p><div class="row"><div class="col-100"><a class="button active" href="#" onclick="getFriends">Unlock</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">Features are locked based on how many friends you invite to use the app.</p>');
// caught the reference error
// code here will execute **only** if variable was never declared
}
$( ".summary-helper" ).show();
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(errorThrown);
},
complete: function () {
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(errorThrown);
},
complete: function () {
}
});
}
function setWant(val){
$( ".homedate" ).addClass("disabled");
$( ".homeduck" ).addClass("disabled");
if (val == 0){
if ($( ".homedate" ).hasClass( "active" )){$( ".homedate" ).removeClass("active");
if ($( ".homeduck" ).hasClass( "active" )){homewant = 'duck';updateWant();
}else {homewant = 'offline';updateWant();
}
}
else{$( ".homedate" ).addClass("active");
if ($( ".homeduck" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'date';updateWant(); }
}
}
if (val == 1){
if ($( ".homeduck" ).hasClass( "active" )){$( ".homeduck" ).removeClass("active");
if ($( ".homedate" ).hasClass( "active" )){homewant = 'date';updateWant(); }else {homewant = 'offline';updateWant(); }
}
else{$( ".homeduck" ).addClass("active");
if ($( ".homedate" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'duck';updateWant(); }
}
}
}
function updateWant(){
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.update();
nearbyswiper.update();
recentswiper.update();
if (homewant == 'offline'){
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
}
firebase.database().ref('users/' + f_uid).update({
homewant:homewant
}).then(function() {});
//Will update firebase user homewant
//Check if updateuser function is in go daddy file
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatewant.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,want:homewant} )
.done(function( data ) {
//getMatches();
});
}).catch(function(error) {
// Handle error
});
}
function startCamera(){
navigator.camera.getPicture(conSuccess, conFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI,sourceType:Camera.PictureSourceType.PHOTOLIBRARY});
}
function conSuccess(imageURI) {
//var image = document.getElementById('myImage');
//image.src = imageURI;
}
function conFail(message) {
// alert('Failed because: ' + message);
}
function doSomething() {
var i = Math.floor(Math.random() * 4) + 0;
$(".desktopimage").attr("src", desktoparray[i]);
}
var myFunction = function() {
doSomething();
var rand = Math.round(Math.random() * (1000 - 700)) + 700;
refreshIntervalId = setTimeout(myFunction, rand);
}
myFunction();
var mobile = 0;
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {mobile = 1;}
else{
mobile = 0;
$('.login-loader').hide();
$('.dateduckdesktop').append('<div style="clear:both;width:100%;text-align:center;border-top:1px solid #ccc;margin-top:10px;"><p>Meet people nearby for a date or a <strike>fu**</strike> duck.</br></br>Open on your phone.</p></div>');
}
//if (mobile===1){
try {
// try to use localStorage
localStorage.test = 2;
} catch (e) {
// there was an error so...
myApp.alert('You are in Privacy Mode\.<br/>Please deactivate Privacy Mode in your browser', 'Error');
}
function directUser(id,type,firstname){
if ($('.chatpop').length > 0) {myApp.closeModal('.chatpop');}
if (type =='date'){createDate1(id,firstname,0);}
else {createDuck(id,firstname,0);}
}
// Initialize your app
var myApp = new Framework7({dynamicNavbar: true,modalActionsCloseByOutside:true,init: false});
// Export selectors engine
var $$ = Dom7;
var datatap, tapid, taptype, tapname;
var view1, view2, view3, view4;
var updatecontinuously = false;
var initialload = false;
var allowedchange = true;
var view3 = myApp.addView('#view-3');
var view4 = myApp.addView('#view-4');
var myMessages, myMessagebar, f_description,existingchatnotifications, message_history = false, message_historyon, datealertvar = false, datealert = false, latitudep, longitudep, incommondate, incommonduck,f_uid,f_name,f_first,f_gender,f_age,f_email,image_url,f_image,f_token, f_upper, f_lower, f_interested,sexuality;
var f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = [];
var f_auth_id;
var blocklist;
var lastkey,ftokenset = false;
var distancepicker;
var pickerDescribe,pickerDescribe2, pickerCustomToolbar;
var existingmessages;
var additions = 0;
var myPhotoBrowser;
var singlePhotoBrowser;
var calendarInline;
var keepopen;
var userpref;
var loadpref= false;
var loadpref2= false;
var loaded = false;
var myList;
var myphotosarray;
var matcheslistener;
var noresultstimeout;
var timeoutactive = false;
var radiussize = '100';
var radiusunit = 'Kilometres';
var sortby,offsounds;
var industry_u,hometown_u,status_u,politics_u,eyes_u,body_u,religion_u,zodiac_u,ethnicity_u,height_u,weight_u,recentfriends;
var descriptionslist = [];
var nameslist = [];
var fdateicon = '<img src="media/dateicon.png" style="width:28px;margin-right:5px;">';
var fduckicon = '<img src="media/duckicon.png" style="width:28px;margin-right:5px;">';
var notifcount;
var swiperPhotos;
var swiperQuestions;
var myswiperphotos;
var flargedateicon = '<img src="media/dateicon.png" style="width:60px;">';
var flargeduckicon = '<img src="media/duckicon.png" style="width:60px;">';
var mySwiper;
myApp.init();
var f_projectid;
var canloadchat;
var viewphotos = false;
var viewscroll = false;
var homewant;
var singlefxallowed = true;
var photoresponse;
var targetpicture;
/*
* 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.
*/
var firebaseinit;
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
//soNow();
FCMPlugin.onNotification(function(data){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);
cordova.plugins.notification.badge.set(data.ev4);
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
if (latitudep){directUser(data.ev1,data.ev2,data.ev3);}
else{
datatap = true;
tapid = data.ev1;
taptype = data.ev2;
tapname = data.ev3;
}
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
myApp.addNotification({
title: 'Date or Duck',
subtitle:data.aps.alert.title,
message: data.aps.alert.body,
hold:2000,
closeOnClick:true,
onClick:function(){directUser(data.ev1,data.ev2,data.ev3);},
media: '<img width="44" height="44" style="border-radius:100%" src="media/icon-76.png">'
});
// alert( JSON.stringify(data) );
}
});
// Add views
view1 = myApp.addView('#view-1');
view2 = myApp.addView('#view-2', {
// Because we use fixed-through navbar we can enable dynamic navbar
dynamicNavbar: true
});
view3 = myApp.addView('#view-3');
view4 = myApp.addView('#view-4');
//setTimeout(function(){ alert("Hello");
//FCMPlugin.onTokenRefresh(function(token){
// alert( token );
//});
//alert("Hello2");
// }, 10000);
//authstatechanged user only
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var checkbadge = false;
if (f_projectid){checkbadge = false;}
else{checkbadge = true;}
cordova.plugins.notification.badge.get(function (badge) {
if (badge >0){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);}
else {$( ".notifspan" ).hide();}
});
//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
//Keep in mind the function will return null if the token has not been established yet.
f_projectid = firebase.auth().currentUser.toJSON().authDomain.substr(0, firebase.auth().currentUser.toJSON().authDomain.indexOf('.'))
f_uid = user.providerData[0].uid;
f_auth_id = user.uid;
f_name = user.providerData[0].displayName;
f_image = user.providerData[0].photoURL;
f_first = f_name.substr(0,f_name.indexOf(' '));
f_email = user.providerData[0].email;
// if (subscribeset){}
// else{
// FCMPlugin.subscribeToTopic( f_uid, function(msg){
// alert( msg );
//}, function(err){
// alert( err );
//} );
//}
//subscribeset = true;
if (checkbadge){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/setbadge.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data1 ) {
var result1 = JSON.parse(data1);
cordova.plugins.notification.badge.set(result1[0].notificationcount);
if (result1[0].notificationcount >0){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);}
else {$( ".notifspan" ).hide();}
});
});
}
var originalid = window.localStorage.getItem("originalid");
if (!originalid) {window.localStorage.setItem("originalid", f_uid);}
// $( ".userimagetoolbar" ).css("background-image","url(\'https://graph.facebook.com/"+f_uid+"/picture?type=normal\')");
// $( "#profilepic" ).empty();
// $( "#profilepic" ).append('<div style="float:left;height:70px;width:70px;border-radius:50%;margin:0 auto;background-size:cover;background-position:50% 50%;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');"></div>');
firebase.database().ref('users/' + f_uid).update({
auth_id : f_auth_id
}).then(function() {getPreferences();});
} else {
$( ".ploader" ).show();
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
var originalid = window.localStorage.getItem("originalid");
if (originalid) {$( ".secondlogin" ).show();}
else {$( ".loginbutton" ).show();}
// No user is signed in.
}
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
function clearBadge(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/clearnotifications.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
});
});
$( ".notifspan" ).hide();
cordova.plugins.notification.badge.set(0);
}
function startApp(){
firebaseinit = localStorage.getItem('tokenStore');
if (firebaseinit){
var credential = firebase.auth.FacebookAuthProvider.credential(firebaseinit);
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
if (error){
myApp.alert('Error', 'Error message: ' + errorMessage + '(code:' + errorCode + ')');
}
});
}
else {
alert('77');
//alert('no tokenStore');
}
}
//document.addEventListener("screenshot", function() {
// alert("Screenshot");
//}, false);
$$('.panel-right').on('panel:opened', function () {
leftPanel();
});
$$('.panel-right').on('panel:open', function () {
$( ".upgradeli" ).slideDown();
clearBadge();
});
$$('.panel-right').on('panel:closed', function () {
myList.deleteAllItems();
myList.clearCache();
clearBadge();
//firebase.database().ref('notifications/' + f_uid).off('value', notificationlist);
});
function compare(a,b) {
if (a.chat_expire < b.chat_expire)
return -1;
if (a.chat_expire > b.chat_expire)
return 1;
return 0;
}
$$('.panel-left').on('panel:closed', function () {
$(".timeline").empty();
});
$$('.panel-left').on('panel:open', function () {
rightPanel();
});
$$('.panel-right').on('panel:closed', function () {
$( ".upgradeli" ).hide();
});
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content-1');
var geoupdate = Math.round(+new Date()/1000);
var firstupdate = false;
// Add 'refresh' listener on it
ptrContent.on('ptr:refresh', function (e) {
// Emulate 2s loading
//loaded = false;
if ($('.no-results-div').length > 0) {myApp.pullToRefreshDone();return false;}
var timesincelastupdate = Math.round(+new Date()/1000) - geoupdate;
if (firstupdate === false){getPreferences();firstupdate = true;}
else{
if (timesincelastupdate > 10){getPreferences();geoupdate = Math.round(+new Date()/1000);}
else {
random_all = shuffle(random_all);
randomswiper.removeAllSlides();
for (i = 0; i < random_all.length; i++) {
var index1 = f_date_match.indexOf(random_all[i].id);
var index2 = f_duck_match.indexOf(random_all[i].id);
var index3 = f_duck_me.indexOf(random_all[i].id);
var index4 = f_date_me.indexOf(random_all[i].id);
var slidewidth = $( document ).width() / 2.5;
var imagestyle;
imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;';
var randomid = Math.floor(Math.random() * (1000000000 - 0 + 1));
var slidecontent;
if (index1 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:-2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" class="swiper-lazy pp photo_'+random_all[i].id+' photo_'+randomid+'" data-src="'+random_all[i].profilepicstringsmall+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/datefaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index2 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/duckfaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index3 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/duckfaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index4 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/datefaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else {slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;"></p></div></div>';
}
randomswiper.appendSlide(slidecontent);
if (i == 0 || i==1 || i==2){
$(".photo_"+random_all[i].id).attr("src", random_all[i].profilepicstringsmall);
}
}
$( ".results-loader" ).show();
$( ".swiper-random" ).hide();
$( ".swiper-nearby" ).hide();
$( ".swiper-recent" ).hide();
$( ".home-title" ).hide();
$( ".nearby-helper" ).hide();
$( ".recent-helper" ).hide();
$( ".summary-helper" ).hide();
setTimeout(function(){
$( ".results-loader" ).hide();
$( ".swiper-random" ).show();
$( ".swiper-nearby" ).show();
$( ".swiper-recent" ).show();
$( ".home-title" ).show();
$( ".nearby-helper" ).show();
$( ".recent-helper" ).show();
$( ".summary-helper" ).show();
}, 2000);
}
}
setTimeout(function () {
// Random image
myApp.pullToRefreshDone();
}, 1000);
});
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content-2');
// Add 'refresh' listener on it
ptrContent.on('ptr:refresh', function (e) {
myList.deleteAllItems();
myList.clearCache();
setTimeout(function () {
// Random image
leftPanel();
myApp.pullToRefreshDone();
}, 1000);
});
var onSuccess = function(position) {
latitudep = position.coords.latitude;
longitudep = position.coords.longitude;
//alert(latitudep);
//alert(longitudep);
if (datatap === true){
targetid = tapid;
targetname = tapname;
directUser(tapid,taptype,tapname);
datatap = false; tapid = false; taptype = false; tapname = false;
}
updateGeo();
$( ".age-header" ).remove();
$( ".swiper-container-loaded" ).remove();
};
function onError(error) {
if (error.code == '1'){
myApp.alert('we are using your approximate location, to improve accuracy go to location settings', 'Oops we cannot find you');
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
})
.done(function() {
//alert('done');
})
.fail(function(err) {
myApp.alert('You must share your location on date or duck', 'Oops we cannot find you');
});
}
if ((error.code == '2') || (error.code == '3')){
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
})
.done(function() {
//alert('done');
})
.fail(function(err) {
myApp.alert('There has been an error.', 'Oops we cannot find you');
});
}
}
function showtext(){
$( ".showtext" ).show();
}
function getWifilocation(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
var apiGeolocationSuccess = function(position) {
latitudep = position.coords.latitude;
longitudep = position.coords.longitude;
//alert(latitudep);
//alert(longitudep);
if (datatap === true){
targetid = tapid;
targetname = tapname;
directUser(tapid,taptype,tapname);
datatap = false; tapid = false; taptype = false; tapname = false;
}
updateGeo();
$( ".age-header" ).remove();
$( ".swiper-container-loaded" ).remove();
};
function mainLoaded(id,pid){
$( ".iconpos_" + id ).show();
$( ".default_" + pid).hide();
$( ".photo_"+ pid ).show();
var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + id);
indivNotif.once('value', function(snapshot) {
if (snapshot.val()){
var obj = snapshot.val();
if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".maindivhome_" + pid).html('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');}
else{$( ".maindivhome_" + pid ).empty();}
}
});
}
var all_matches_photos=[];
var new_all = [];
var main_all = [];
var random_all = [];
var nearby_all = [];
var recent_all = [];
var nearbyshare = false, recentshare = false;
var randomswiper = myApp.swiper('.swiper-random', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = random_all;
photoBrowser(randomswiper.clickedIndex);}
});
var nearbyswiper = myApp.swiper('.swiper-nearby', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = nearby_all;
if (nearbyshare){
photoBrowser(nearbyswiper.clickedIndex);
}
else{}
}
});
var recentswiper = myApp.swiper('.swiper-recent', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = recent_all;
if (recentshare){
photoBrowser(recentswiper.clickedIndex);
}
else{}
}
});
function getMatches(){
$( ".content-here" ).empty();
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.update();
nearbyswiper.update();
recentswiper.update();
$( ".results-loader" ).show();
$( ".home-title" ).hide();
$( ".nearby-helper" ).hide();
$( ".recent-helper" ).hide();
$( ".summary-helper" ).hide();
//alert('getmatch trigger' + homewant);
//can put any ads here
if ((initialload === false) && (availarray.length === 0)){
}
if (!homewant || homewant =='offline'){
$('.content-here').empty();
$( ".statusbar-overlay" ).css("background-color","#ccc");
$( ".buttons-home" ).hide();
$( ".toolbar" ).hide();
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
var swiperheight = $( window ).height() - 378;
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:44px;left:50%;margin-left:-150px;margin-top:54px;">'+
'<div class="topdiv">'+
// '<h3>Get Quacking!</h3>'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:15px;margin-left:0px;">Get Quacking, It\'s Easy</div>'+
'<div class="row" style="padding-top:10px;padding-bottom:10px;">'+
'<div class="col-30" style="padding-top:5px;"><img src="media/datefaceonly.png" style="width:80px;margin:0 auto;"></div>'+
// '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:20px;">date</span> if you want to find something more serious like a relationship.</div>'+
'<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:26px;">date</span> to find love <br/>(or at least try)</div>'+
'</div>'+
'<div class="row" style="padding-top:10px;padding-bottom:10px;margin-bottom:10px;">'+
'<div class="col-30" style="padding-top:5px;"><img src="media/duckfaceonly.png" style="width:80px;margin:0 auto;"></div>'+
// '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:20px;">duck</span> if you want to get down to...ahem...business (replace the D with another letter). </div>'+
'<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:26px;">duck</span> to find fun <br/>(replace the D with another letter)</div>'+
'</div>'+
'</div>'+
'<div class="list-block-label" style="color:#666;margin-bottom:10px;">Choose one, or both. Your profile is hidden until you decide.</div>'+
'<div class="swiper-container swiper-helper-info" style="z-index:99999999999999;background-color:#ccc;color:#6d6d72;margin-left:-10px;margin-right:-10px;padding-top:10px;">'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:15px;margin-left:0px;">How this App Works</div>'+
' <div class="swiper-wrapper">'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px;"><i class="twa twa-4x twa-coffee" style="margin-top:5px;"></i><h2>Find your next<br/> coffee date...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-wave" style="margin-top:5px;"></i><h2>Or invite someone over<br/> tonight...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-heart-eyes" style="margin-top:5px;"></i><h2>When you like someone, <br/>they can see...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-calendar" style="margin-top:5px;"></i><h2>Once you both agree on</br> a time to meet...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-clock12" style="margin-top:5px;"></i><h2>Chat is enabled until <br/>midnight of your date...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-bomb" style="margin-top:5px;"></i><h2>You can send photos that delete after 24 hours...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-watch" style="margin-top:5px;"></i><h2>You can share availability<br/> to easily schedule dates</h2></div></div>'+
' </div>'+
'<div class="swiper-pagination-p" style="margin-top:-20px;margin-bottom:20px;"></div>'+
'</div>'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:20px;margin-bottom:10px;margin-left:0px;">Support this app</div>'+
'<a href="#" class="button-big button active" style="margin-bottom:10px;" onclick="appLink()">Invite Friends</a>'+
'<a href="#" class="button-big button" style="margin-bottom:10px;" onclick="sharePop()">Share</a>'+
'<a class="button-big button external" href="sms:&body=Check out this new a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? " style="margin-bottom:10px;">Send SMS</a>'+
'</div>');
$( ".ploader" ).hide();
var homeswiperhelper = myApp.swiper('.swiper-helper-info', {
pagination:'.swiper-pagination-p'
});
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
setTimeout(function(){
$( ".homedate" ).removeClass("disabled");
$( ".homeduck" ).removeClass("disabled");
}, 2000);
return false;
}
$( ".statusbar-overlay" ).css("background-color","#2196f3");
initialload = true;
if (recentfriends){
nearbyshare = true;
recentshare = true;
$('.nearby-title').html('Nearby First');
$('.recent-title').html('Recently Online');
$('.nearby-helper').hide();
$('.recent-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.recent-wrapper').css("-webkit-filter","none");
}
else{
//check permission first
readPermissions();
}
if (updatecontinuously){}
else {setInterval(function(){ justGeo(); }, 599999);updatecontinuously=true;}
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
if (timeoutactive === true) {clearTimeout(noresultstimeout);}
timeoutactive = true;
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/locations.php", { want:homewant,projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,upper:f_upper,lower:f_lower,radius:radiussize,radiusunit:radiusunit,sexuality:sexuality,sortby:'random',latitudep:latitudep,longitudep:longitudep} )
.done(function( data ) {
dbCall('random');
dbCall('distance');
dbCall('activity');
function dbCall(fetch){
var resultall = JSON.parse(data);
var result;
if (fetch == 'random'){result = resultall[2];}
if (fetch == 'distance'){result = resultall[1];}
if (fetch == 'activity'){result = resultall[0];}
var slidewidth = $( document ).width() / 2.5;
var halfwidth = -Math.abs(slidewidth / 2.23);
$( ".swiper-recent" ).css("height",slidewidth + "px");
$( ".swiper-nearby" ).css("height",slidewidth + "px");
$( ".swiper-random" ).css("height",slidewidth + "px");
var slide_number = 0;
descriptionslist = [];
nameslist = [];
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
if (result == 77 ||(result.length ===1 && result[0].uid == f_uid ) ){
$( ".home-title" ).hide();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
else {
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (i = 0; i < result.length; i++) {
var photosstringarray =[];
var photocount;
var photostring;
var blocked = 0;
var subtract = result[i].age;
var laston = result[i].timestamp;
var hometown_d = result[i].hometown;
var industry_d = result[i].industry;
var status_d = result[i].status;
var politics_d = result[i].politics;
var eyes_d = result[i].eyes;
var body_d = result[i].body;
var religion_d = result[i].religion;
var zodiac_d = result[i].zodiac;
var ethnicity_d = result[i].ethnicity;
var height_d = result[i].height;
var weight_d = result[i].weight;
var namescount = result[i].displayname.split(' ').length;
var matchname;
var minphotowidth = $( document ).width();
var imagestyle;
imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;';
var availarraystring='';
var availnotexpired = false;
if(result[i].availstring && (result[i].availstring != '[]') && (result[i].uid != f_uid)){
//console.log(result[i].availstring);
var availablearrayindividual = JSON.parse(result[i].availstring);
//console.log(availablearrayindividual);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
}
if (availnotexpired){availarraystring = result[i].availstring;}
}
var profilepicstring;
var photoarrayuserlarge;
var photoarrayusersmall;
if(result[i].largeurl){
var heightarray = result[i].heightslides.split(",");
var widtharray = result[i].widthslides.split(",");
//console.log(heightarray[0]);
//console.log(widtharray[0]);
if (heightarray[0] > widtharray[0]) {imagestyle = 'width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'}
if (widtharray[0] > heightarray[0]) {imagestyle = 'height:100%;max-width:' + slidewidth + 'px;overflow:hidden;'}
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[i].largeurl + '" class="swiper-lazy"></div></div>';
photocount = result[i].largeurl.split(",").length;
photoarrayuserlarge = result[i].largeurl.split(",");
photoarrayusersmall = result[i].smallurl.split(",");
profilepicstringlarge = photoarrayuserlarge[0];
profilepicstringsmall = photoarrayusersmall[0];
photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="')
}
else{
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+result[i].uid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>';
profilepicstringlarge = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=828&height=828';
profilepicstringsmall = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=368&height=368';
photocount = 1;
}
//console.log(photostring);
if(namescount === 1){matchname = result[i].displayname;}
else {matchname = result[i].name.substr(0,result[i].displayname.indexOf(' '));}
var matchdescription = result[i].description;
var swipernumber = subtract - f_lower;
var graphid = result[i].uid;
var distance = parseFloat(result[i].distance).toFixed(1);
var distancerounded = parseFloat(result[i].distance).toFixed(0);
if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'}
if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'}
if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'}
if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'}
if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'}
if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'}
if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'}
if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'}
if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'}
if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'}
if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'}
if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'}
var zz = new Date();
var mmn = zz.getTimezoneOffset();
//console.log(result[i].timestamp);
var timestampyear = result[i].timestamp.substring(0,4);
var timestampmonth = result[i].timestamp.substring(5,7);
var timestampday = result[i].timestamp.substring(8,10);
var timestamphour = result[i].timestamp.substring(11,13);
var timestampminute = result[i].timestamp.substring(14,16);
var timestampsecond = result[i].timestamp.substring(17,20);
var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800;
var d_unix = Math.round(+new Date()/1000);
var diff = (d_unix - timestampunix)/60;
var activecircle='';
//if (diff<11){activecircle = '<span style="position:absolute;left:10px;height:10px;width:10px;border-radius:50%;bottom:10px;background-color:#4cd964"></span>';}
//else{activecircle = '<span style="position:absolute;left:10px;bottom:10px;height:10px;width:10px;border-radius:50%;background-color:transparent;border:1px solid #ccc;"></span>';}
if ($('.slide_' + graphid).length){
}
if (graphid != f_uid){
$('.swiper-' + subtract).show();
$('.header_' + subtract).show();
}
var blockedid = blocklist.indexOf(graphid);
//Do not show the users profile to themselves, and do not show profiles older than 1 month
if ((graphid != f_uid) && (blockedid < 0) && (diff < 43800)){
var index1 = f_date_match.indexOf(graphid);
var index2 = f_duck_match.indexOf(graphid);
var index3 = f_duck_me.indexOf(graphid);
var index4 = f_date_me.indexOf(graphid);
var randomid = Math.floor(Math.random() * (1000000000 - 0 + 1));
var slidecontent;
if (index1 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:-2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" class="swiper-lazy pp photo_'+graphid+' photo_'+randomid+'" data-src="'+profilepicstringsmall+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index2 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index3 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index4 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;"></p></div></div>';
}
if (fetch == 'random'){randomswiper.appendSlide(slidecontent);
random_all.push({profilepicstringsmall:profilepicstringsmall,hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (random_all[0].id == graphid || random_all[1].id == graphid || random_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
if (fetch == 'distance'){nearbyswiper.appendSlide(slidecontent);
nearby_all.push({hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (nearby_all[0].id == graphid || nearby_all[1].id == graphid || nearby_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
if (fetch == 'activity'){recentswiper.appendSlide(slidecontent);
recent_all.push({hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (recent_all[0].id == graphid || recent_all[1].id == graphid || recent_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
}
}
}
//if (nearbyshare){
//remove blur, unlock swiper
//}
//else{ $( ".nearby-helper" ).show();}
//if (recentshare){
//remove blur, unlock swiper
//}
//else{ $( ".recent-helper" ).show();}
setTimeout(function(){
$( ".homedate" ).removeClass("disabled");
$( ".homeduck" ).removeClass("disabled");
}, 2000);
if (random_all.length === 0){
if ($('.no-results-div').length > 0) {}
else{
$( ".home-title" ).hide();
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
}
else {$( ".home-title" ).show(); $('.content-here').empty();}
}
});
//here is the id token call
}).catch(function(error) {
// Handle error
});
$( ".ploader" ).hide();
$( ".toolbar" ).show();
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
//$('.no-results-div').empty();
clearInterval(refreshIntervalId);
deletePhotos();
}
function justGeo(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} )
.done(function( data ) {
//console.log('updatedtimestamp');
});
}).catch(function(error) {
// Handle error
});
}
function updateGeo(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} )
.done(function( data ) {
getMatches();
});
}).catch(function(error) {
// alert('error' + error);
});
}
function getPreferences(){
// Test if user exists
if(userpref) {firebase.database().ref('users/' + f_uid).off('value', userpref);}
userpref = firebase.database().ref('users/' + f_uid).on("value",function(snapshot) {
var userexists = snapshot.child('lower').exists(); // true
if (userexists) {
// var matchessetting = firebase.database().ref("users/" + f_uid).on("value",function(snapshot) {
// if (!snapshot.child("to_date").val()) {f_to_date = [];}
// else{f_to_date = snapshot.child("to_date").val();}
// if (!snapshot.child("to_duck").val()) {f_to_duck = [];}
// else{f_to_duck = snapshot.child("to_duck").val();}
// if (!snapshot.child("date_me").val()) {f_date_me = [];}
// else{f_date_me = snapshot.child("date_me").val();}
// if (!snapshot.child("duck_me").val()) {f_duck_me=[];}
// else{f_duck_me = snapshot.child("duck_me").val();}
// incommondate = f_to_date.filter(function(n) {
// return f_date_me.indexOf(n) != -1;
//});
//incommonduck = f_to_duck.filter(function(n) {
// return f_duck_me.indexOf(n) != -1;
//});
// });
hometown_u = snapshot.child("hometown").val();
industry_u = snapshot.child("industry").val();
status_u = snapshot.child("status").val();
politics_u = snapshot.child("politics").val();
eyes_u = snapshot.child("eyes").val();
body_u = snapshot.child("body").val();
religion_u = snapshot.child("religion").val();
zodiac_u = snapshot.child("zodiac").val();
ethnicity_u = snapshot.child("ethnicity").val();
height_u = snapshot.child("height").val();
weight_u = snapshot.child("weight").val();
homewant = snapshot.child("homewant").val();
recentfriends = snapshot.child("recentfriends").val();
//f_image = snapshot.child("image_url").val();
image_url = f_image;
if (snapshot.child("photoresponse").val()){
if (snapshot.child("photoresponse").val() == 'Y'){photoresponse = 'Y';imageurl = snapshot.child("image_url").val();}
}
else{
photoresponse = 'N';
image_url = f_image;
}
sortby = snapshot.child("sort").val();
if (sortby){
if (sortby == 'random'){sortBy(1);}
if (sortby == 'distance'){sortBy(2);}
if (sortby == 'activity'){sortBy(3);}
$( ".sortbutton" ).removeClass( "active" );
$( "#sort" + sortby ).addClass( "active" );
}
if (snapshot.child("offsounds").val()){offsounds = snapshot.child("offsounds").val();}
if (snapshot.child("availstring").val()){ availarray = JSON.parse(snapshot.child("availstring").val());}
f_description = snapshot.child("description").val();
f_lower = snapshot.child("lower").val();
radiussize = snapshot.child("radius").val();
if(snapshot.child("radiusunit").val()){radiusunit = snapshot.child("radiusunit").val();}
else{radiusunit = "Kilometres";}
if (ftokenset){
firebase.database().ref('users/' + f_uid).update({
token: f_token
});
}
else{f_token = snapshot.child("token").val();}
f_upper = snapshot.child("upper").val();
f_interested = snapshot.child("interested").val();
f_gender = snapshot.child("gender").val();
f_age = snapshot.child("age").val();
if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';}
if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';}
if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';}
if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';}
if (loadpref=== false){
if(homewant){
if (homewant == 'offline'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).removeClass('active'); }
if (homewant == 'dateduck'){$( ".homedate" ).addClass('active');$( ".homeduck" ).addClass('active'); }
if (homewant == 'duck'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).addClass('active'); }
if (homewant == 'date'){$( ".homedate" ).addClass('active');$( ".homeduck" ).removeClass('active');}
}
loadpref = true;
establishNotif();
}
matchesListener();
}
else if (!userexists) {
addUser();
if (loadpref=== false){
firebase.database().ref('users/' + f_uid).once("value",function(snapshot) {
f_token = snapshot.child("token").val();
swipePopup(1);
});
//preferencesPopup();
}
loadpref = true;
}
});
}
function matchesListener(){
if (loaded === true){
firebase.database().ref("matches/" + f_uid).off('value', matcheslistener);
}
matcheslistener = firebase.database().ref("matches/" + f_uid).on("value",function(snapshot) {
f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = [];
blocklist = [];
if (snapshot.val()){
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if ((obj.first_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.second_number);}
if ((obj.second_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.first_number);}
if(obj.firstnumberdate){
//f_to_date
if ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y')) {f_to_date.push(obj.second_number);}
//f_date_me
if ((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) {f_date_me.push(obj.first_number);}
}
if(obj.firstnumberduck){
//f_duck_me
if ((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) {f_duck_me.push(obj.first_number);}
//f_to_duck
if ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y')) {f_to_duck.push(obj.second_number);}
}
if(obj.secondnumberdate){
//f_to_date
if ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y')) {f_to_date.push(obj.first_number);}
//f_date_me
if ((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) {f_date_me.push(obj.second_number);}
}
if(obj.secondnumberduck){
//f_to_duck
if ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y')) {f_to_duck.push(obj.first_number);}
//f_duck_me
if ((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) {f_duck_me.push(obj.second_number);}
}
if(obj.firstnumberdate && obj.secondnumberdate){
//f_date_match
if(((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y'))){f_date_match.push(obj.first_number);f_date_match_data.push({uid:obj.first_number,name:obj.first_name});}
if(((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y'))){f_date_match.push(obj.second_number);f_date_match_data.push({uid:obj.second_number,name:obj.second_name});}
}
if(obj.firstnumberduck && obj.secondnumberduck){
//f_duck_match
if(((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y'))){f_duck_match.push(obj.first_number);f_duck_match_data.push({uid:obj.first_number,name:obj.first_name});}
if(((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y'))){f_duck_match.push(obj.second_number);f_duck_match_data.push({uid:obj.second_number,name:obj.second_name});}
}
});
updatePhotos();
loaded = true;
}
else{
updatePhotos();
loaded = true;
}
});
getWifilocation();
}
function addUser() {
if (f_token){firebase.database().ref('users/' + f_uid).update({
name: f_name,
email: f_email,
image_url : f_image,
uid:f_uid,
token:f_token,
auth_id : f_auth_id
});}
else{
firebase.database().ref('users/' + f_uid).update({
name: f_name,
email: f_email,
image_url : f_image,
uid:f_uid,
auth_id : f_auth_id
});
}
}
function clickMe() {
pickerDescribe.open();
}
function keyUp(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
var inputlength = $( "#userdescription" ).val().length;
$( "#maxdescription" ).empty();
$( "#maxdescription" ).append(inputlength + " / 100");
}
function updateUser(){
if ((pickerDescribe.initialized === false && !f_age) || (pickerDescribe2.initialized === false && !f_lower)) {
myApp.alert('Please complete more profile information.', 'Missing Information');
return false;}
if (myswiperphotos){
myswiperphotos.destroy();
myswiperphotos = false;
}
var newage,newinterested,newgender;
if (pickerDescribe.initialized === false) {newage = f_age;newgender = f_gender;}
else {newage = pickerDescribe.value[1];newgender = pickerDescribe.value[0];}
if (pickerDescribe2.initialized === false) {newinterested = f_interested;}
else {newinterested = pickerDescribe2.value[0];}
var userzdescription;
if ($( "#userdescription" ).val()) {userzdescription = $( "#userdescription" ).val();}
else {userzdescription = '';}
//Need to delete old reference
if (pickerDescribe.initialized === true) {f_age = pickerDescribe.value[1];f_gender = pickerDescribe.value[0];}
if (pickerDescribe2.initialized === true) {f_interested = pickerDescribe2.value[0];}
if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';}
if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';}
if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';}
if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';}
var lowerage,upperage;
if (pickerDescribe2.initialized === true) {
if (pickerDescribe2.value[1] > pickerDescribe2.value[2]) {lowerage = pickerDescribe2.value[2];upperage = pickerDescribe2.value[1];}
else {lowerage = pickerDescribe2.value[1];upperage = pickerDescribe2.value[2];}
}
else {lowerage = f_lower;upperage = f_upper;}
//if ($( "#distance_10" ).hasClass( "active" )){radiussize = '10';}
//if ($( "#distance_25" ).hasClass( "active" )){radiussize = '25';}
//if ($( "#distance_50" ).hasClass( "active" )){radiussize = '50';}
//if ($( "#distance_100" ).hasClass( "active" )){radiussize = '100';}
availarray = [];
$( ".availrec" ).each(function() {
if ($( this ).hasClass( "selecrec" )){
var availinputid = $(this).attr('id').replace('aa_', '');
var valueinputted = $( "#picker"+availinputid ).val();
var supdate = $( ".suppdate_"+availinputid ).val();
if (valueinputted == 'Now'){daysaved ='Now';timesaved='';}
else{
valueinputted = valueinputted.split(' ');
var daysaved = valueinputted[0];
var timesaved = valueinputted[1];
}
availarray.push({id:availinputid,day:daysaved,time:timesaved,fulldate:supdate});
}
});
var availstring = JSON.stringify(availarray);
var availstringn = availstring.toString();
if ($('#soundnotif').prop('checked')) {offsounds = 'Y'} else {offsounds = 'N'}
//User Profile details
var hometown_u = $( "#homesearch" ).val();
var industry_u = $( "#industry-input" ).val();
var status_u = $( "#status-input" ).val();
var politics_u = $( "#politics-input" ).val();
var eyes_u = $( "#eyes-input" ).val();
var body_u = $( "#body-input" ).val();
var religion_u = $( "#religion-input" ).val();
var zodiac_u = $( "#zodiac-input" ).val();
var ethnicity_u = $( "#ethnicity-input" ).val();
var height_u = $( "#height-input" ).val().substring(0,3);
var weight_pre = $( "#weight-input" ).val();
var weight_u = weight_pre.substr(0, weight_pre.indexOf(' '));
var uploadurl = '';
photoresponse = 'N';
if (f_largeurls.length > 0){photoresponse = 'Y';uploadurl = f_largeurls[0];}
else{photoresponse='N';uploadurl = '';}
firebase.database().ref('users/' + f_uid).update({
gender: newgender,
industry:industry_u,
hometown:hometown_u,
status:status_u,
politics: politics_u,eyes: eyes_u,body: body_u,religion: religion_u,zodiac: zodiac_u,ethnicity: ethnicity_u,
height: height_u,
weight: weight_u,
age: newage,
interested: newinterested,
lower: lowerage,
upper: upperage,
description:userzdescription,
radius:radiussize,
radiusunit:radiusunit,
availstring:availstring,
offsounds:offsounds,
photoresponse:photoresponse,
uploadurl:uploadurl
});
if (deletedphoto){
var newsmall = f_smallurls.toString();
var newlarge = f_largeurls.toString();
var newwidth = addedwidth.toString();
var newheight = addedheight.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
});
}).catch(function(error) {
// Handle error
});
}
var hometown_u = $( "#homesearch" ).val();
var industry_u = $( "#industry-input" ).val();
var status_u = $( "#status-input" ).val();
var politics_u = $( "#politics-input" ).val();
var eyes_u = $( "#eyes-input" ).val();
var body_u = $( "#body-input" ).val();
var religion_u = $( "#religion-input" ).val();
var zodiac_u = $( "#zodiac-input" ).val();
var ethnicity_u = $( "#ethnicity-input" ).val();
var height_u = $( "#height-input" ).val().substring(0,3);
var weight_pre = $( "#weight-input" ).val();
var weight_u = weight_pre.substr(0, weight_pre.indexOf(' '));
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatedetails.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,sexuality:sexuality,uid:f_uid,name:f_name,description:userzdescription,age:newage,availstring:availstringn,industry:industry_u,hometown:hometown_u,status:status_u,politics:politics_u,eyes:eyes_u,body:body_u,religion:religion_u,zodiac:zodiac_u,ethnicity:ethnicity_u,height:height_u,weight:weight_u} )
.done(function( data ) {
//if (f_gender && (f_gender != newgender)){
//deleteDatabase();
//}
//if (f_interested && (f_interested != newinterested)){
//deleteDatabase();
//}
});
}).catch(function(error) {
// Handle error
});
f_lower = lowerage;
f_upper = upperage;
//if (loadpref2===true){getWifilocation();}
loadpref2 = true;
myApp.closeModal();
$( ".popup-overlay" ).remove();
}
function processUpdate(){
$( '.donechange' ).show();
$( '.doneunchange' ).hide();
}
function processDupdate(){
var unixnow = Math.round(+new Date()/1000);
var middaystamp = new Date();
middaystamp.setHours(12,00,00,000);
var middaystamp_timestamp = Math.round(middaystamp/1000);
var threestamp = new Date();
threestamp.setHours(12,00,00,000);
var threestamp_timestamp = Math.round(threestamp/1000);
var fivestamp = new Date();
fivestamp.setHours(17,00,00,000);
var fivestamp_timestamp = Math.round(fivestamp/1000);
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if (d_chat_expire){
var datemessageq = $( '#datemessageq' ).val();
var interestnewarray = [];
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestnewarray.push(interestadd);
}
});
var comparedinterest;
var compareninterest;
if (d_interest != null) {
comparedinterest = d_interest.toString();
}
else {comparedinterest = '';}
if (typeof interestnewarray == 'undefined' && interestnewarray.length === 0){compareninterest = '';}else{compareninterest = interestnewarray.toString();}
if ((d_day == pickerCustomToolbar.cols[0].displayValue) && (d_time ==pickerCustomToolbar.cols[1].displayValue) && (datemessageq == '' ) && (compareninterest == comparedinterest))
{
if (d_response=='Y'){noChange();}
else if (d_response=="W"){reverseRequest();dateConfirmationPage();}
}
else{dateRequest();}
}
else {dateRequest();}
}
var mynotifs = [];
function leftPanel(){
canscrollnotif = true;
mynotifs = [];
notifadditions=0;
if(!myList){
myList = myApp.virtualList('.virtual-notifications', {
// Array with plain HTML items
items: [],
height:89,
renderItem: function (index, item) {
var backgroundnotifcolor;
if(item.colordot == ''){backgroundnotifcolor = 'white';}else{backgroundnotifcolor = 'transparent';}
if(item.from_uid == f_uid){
return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' +
'<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+
'</div>' +
'<div class="item-inner" onclick="'+item.func+'('+item.targetid+',\''+item.targetname+'\')" style="margin-left:10px;" >' +
'<div class="item-title-row" >'+
'<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+'</div>'+
'<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+
'</div>'+
'<div class="item-subtitle">'+ item.icon + item.title + ' </div>' +
'<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' +
'</div>' +
'</li>';
}
else{
//onclick="singleBrowser('+item.targetid+')"
return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' +
'<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+
'</div>' +
'<div class="item-inner" onclick="'+item.func+'(\''+item.targetid+'\',\''+item.targetname+'\')" style="margin-left:10px;" >' +
'<div class="item-title-row" >'+
'<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+item.colordot+'</div>'+
'<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+
'</div>'+
'<div class="item-subtitle" style="color:black;">'+ item.icon + item.title + ' </div>' +
'<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' +
'</div>' +
'</li>';
}
}
});
}
var notificationlist = firebase.database().ref('notifications/' + f_uid).once('value', function(snapshot) {
if (snapshot.val() === null){
// $('.title-notify').remove();
// $('.virtual-notifications').append('<div class="content-block-title title-notify" style="margin-top:54px;">No notifications</div>');
$('.nonefound').remove();
$('.virtual-notifications').prepend('<div class="content-block-title nonefound" style="margin: 0 auto;margin-top:10px;text-align:center;">No Matches Yet</div>');
}
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$('.nonefound').remove();
var objs = snapshot.val();
var obg = [];
$.each(objs, function(i, obk) {obg.push (obk)});
//console.log(obg);
function compare(a,b) {
if (a.timestamp > b.timestamp)
return -1;
if (a.timestamp < b.timestamp)
return 1;
return 0;
}
obg.sort(compare);
$.each(obg, function(i, obj) {
var typetype = obj.type.substring(0, 4);
var correctimage;
var correctname;
var iconhtml;
var colordot;
var message_text;
var func;
var picturesrc;
var mediaicon;
var dateseenresponse;
if (typetype == 'date') {mediaicon = fdateicon;}
if (typetype == 'duck') {mediaicon = fduckicon;}
//need to see if a match still and then create function based on tha
var timestamptitle;
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - obj.timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = '1 minute ago';}
else if (tunixminago == 1) {timestamptitle = '1 minute ago';}
else if (tunixminago < 2) {timestamptitle = '1 minute ago';}
else if (tunixminago < 60) {timestamptitle = Math.round(tunixminago)+' minutes ago';}
else if (tunixminago == 60) {timestamptitle = '1 hour ago';}
else if (tunixminago < 120) {timestamptitle = '1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = '1 day ago';}
else if (tunixminago < 2880) {timestamptitle = '1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = Math.round(tunixminago / 1440) +' days ago';}
else if (tunixminago == 10080) {timestamptitle = '1 week ago';}
else if (tunixminago < 20160) {timestamptitle = '1 week ago';}
else if (tunixminago >= 20160) {timestamptitle = Math.round(tunixminago / 10080) +' weeks ago';}
else if (tunixminago == 525600) {timestamptitle = '1 week ago';}
else if (tunixminago < (525600*2)) {timestamptitle = '1 week ago';}
else if (tunixminago >= (525600*2)) {timestamptitle = Math.round(tunixminago / 525600) +' years ago';}
// onclick="singleBrowser('+targetid+')"
if (obj.param=='message'){message_text = obj.message; iconhtml = '<i class="pe-7s-mail pe-lg" style="margin-right:5px;z-index:9999;"></i>'}
if (obj.param=='image'){
if (obj.from_uid == f_uid){message_text = obj.message + 'sent';}
else {message_text = obj.message + 'received';}
iconhtml = '<i class="pe-7s-camera pe-lg" style="margin-right:5px;z-index:9999;"></i>';}
if (obj.param=='daterequest'){
if (obj.from_uid == f_uid){message_text = obj.message + ' sent';}
else {message_text = obj.message + ' received';}
iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='datedeleted'){
if (obj.from_uid == f_uid){message_text = obj.message;}
else {message_text = obj.message;}
iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='newmatch'){
if (obj.from_uid == f_uid){message_text = obj.message;}
else {message_text = obj.message;}
iconhtml = '<i class="pe-7s-like pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='dateconfirmed'){
message_text = obj.message;
iconhtml = '<i class="pe-7f-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
// if(obj.received=='N' && (obj.param=='datedeleted' || obj.param=='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'ssage_count+'</span>';} else{colordot = '';}
// if(obj.received=='N' && (obj.param!='datedeleted' && obj.param!='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';} else{colordot = '';}
if(obj.received=='N' && (obj.param=='message' || obj.param=='image')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';}
else if(obj.received=='N'){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;width:12px;height:12px;"></span>';}
else{colordot = '';}
if (obj.from_uid == f_uid){correctimage = String(obj.to_uid);correctname = String(obj.to_name);colordot = '';}
else {correctimage = String(obj.from_uid);correctname = String(obj.from_name);image_after = 'received';}
datemeinarray=0;
duckmeinarray=0;
datetoinarray=0;
ducktoinarray=0;
if (obj.from_uid == f_uid){picturesrc = obj.to_picture;}
else{picturesrc = obj.from_picture;}
var datesto = f_to_date.indexOf(correctimage);
if (datesto > -1) {
datetoinarray=1;
}
var datesme = f_date_me.indexOf(correctimage);
if (datesme > -1) {
datemeinarray=1;
}
var duckto = f_to_duck.indexOf(correctimage);
if (duckto > -1) {
ducktoinarray=1;
}
var duckme = f_duck_me.indexOf(correctimage);
if (duckme > -1) {
duckmeinarray=1;
}
if ((datemeinarray==1 && datetoinarray==1) || (duckmeinarray==1 && ducktoinarray==1)) {
if (typetype == 'date') {func = 'createDate1';}
if (typetype == 'duck') {func = 'createDuck';}
}
else{func = 'singleUser'}
mynotifs.push({
title: message_text,
targetid:correctimage,
targetname:correctname,
picture:picturesrc,
from_name: obj.from_name,
to_name: obj.to_name,
from_uid: obj.from_uid,
to_uid: obj.to_uid,
icon:iconhtml,
colordot:colordot,
func:func,
type:typetype,
timestamptitle:timestamptitle
});
});
var notif2load = mynotifs.length;
if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;}
for (i = 0; i < notifletsload; i++) {
myList.appendItem({
title: mynotifs[i].title,
targetid:mynotifs[i].targetid,
targetname:mynotifs[i].targetname,
picture:mynotifs[i].picture,
from_name: mynotifs[i].from_name,
to_name: mynotifs[i].to_name,
from_uid:mynotifs[i].from_uid,
to_uid: mynotifs[i].to_uid,
icon:mynotifs[i].icon,
colordot:mynotifs[i].colordot,
func:mynotifs[i].func,
type:mynotifs[i].type,
timestamptitle:mynotifs[i].timestamptitle
});
}
}
});
}
function rightPanel(){
$('.timeline-upcoming').empty();
myApp.sizeNavbars();
var rightdates = [];
var month = [];
month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";
month[3] = "APR";
month[4] = "MAY";
month[5] = "JUN";
month[6] = "JUL";
month[7] = "AUG";
month[8] = "SEP";
month[9] = "OCT";
month[10] = "NOV";
month[11] = "DEC";
var weekday = [];
weekday[0] = "SUN";
weekday[1] = "MON";
weekday[2] = "TUE";
weekday[3] = "WED";
weekday[4] = "THU";
weekday[5] = "FRI";
weekday[6] = "SAT";
var timelinedates = firebase.database().ref('/dates/' + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
$('.timeline-upcoming').empty();
if (snapshot.val() === null){
$('.timeline').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;">Calendar is empty</div>');
}
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
rightdates.push(obj);
});
rightdates.sort(compare);
for (i = 0; i < rightdates.length; i++) {
var correctname;
var correctid;
var picturesrc;
if (rightdates[i].created_uid == f_uid) {picturesrc = rightdates[i].to_picture;correctname = rightdates[i].received_name;correctid = rightdates[i].received_uid;}
if (rightdates[i].created_uid != f_uid) {picturesrc = rightdates[i].from_picture;correctname = rightdates[i].created_name;correctid = rightdates[i].created_uid;}
var unix = Math.round(+new Date()/1000);
var c = new Date(rightdates[i].chat_expire*1000 - 1);
var cday = weekday[c.getDay()];
if ((rightdates[i].created_uid == f_uid || rightdates[i].received_uid == f_uid) && (rightdates[i].chat_expire > Number(unix)) ){
var d = new Date(rightdates[i].chat_expire*1000 - 3600);
var timehere;
if (rightdates[i].time) {timehere = ', ' + rightdates[i].time;}
else {timehere='';}
var timestamptitle;
var datetype = rightdates[i].type.capitalize();
var datesidetitle;
var dayday = d.getDate();
var monthmonth = month[d.getMonth()];
var subtitletext,confirmtext;
if (rightdates[i].response =='Y') {
if (rightdates[i].type=='date' ){datesidetitle = 'Date';}
if (rightdates[i].type=='duck' ){datesidetitle = 'Duck';}
timestamptitle = datesidetitle + ' Confirmed';
var name_accepted;
if (rightdates[i].received_uid == f_uid) {name_accepted = 'you ';}
else {name_accepted = rightdates[i].received_name;}
subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#4cd964;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-check pe-lg" style="color:white"></i></div>';
confirmtext='Date confirmed by '+name_accepted+' on '+cday;
}
if (rightdates[i].response =='W') {
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - rightdates[i].timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = 'Sent now';}
else if (tunixminago == 1) {timestamptitle = 'Sent 1 min ago';}
else if (tunixminago < 2) {timestamptitle = 'Sent 1 min ago';}
else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' mins ago';}
else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 120) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';}
if (rightdates[i].created_uid == f_uid) {confirmtext = 'Waiting for '+rightdates[i].received_name+' to respond.';}
if (rightdates[i].created_uid != f_uid){confirmtext = rightdates[i].created_name + ' is waiting for your response.';}
if (rightdates[i].type=='date' ){datesidetitle = 'Date Request';}
if (rightdates[i].type=='duck' ){datesidetitle = 'Duck Request';}
subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#ff9500;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-help1 pe-lg" style="color:white"></i></div>';}
if ($(".time_line_" + dayday)[0]){
} else {
$('.timeline').append('<div class="timeline-item" style="margin-bottom">'+
'<div class="timeline-item-date" style="margin-right:10px;">'+cday+'<br/>'+dayday+' <small> '+monthmonth+' </small></div>'+
//'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content time_line_'+dayday+'">'+
'</div>'+
'</div>');
}
$('.time_line_'+dayday).append(
'<a href="#" onclick="createDate(\''+correctid+'\',\''+correctname+'\')">'+
subtitletext+
// '<div class="timeline-item-time" style="padding:2px;margin-top:0px;background-color:white;border-bottom:1px solid #c4c4c4;text-align:center;padding-top:10px;"><i class="pe-7s-clock pe-lg"></i> //'+weekday[d.getDay()]+ timehere+'<div style="clear:both;" id="interestdatediv_'+correctid+'"></div></div>'+
'<div class="timeline-item-inner" style="min-width:136px;padding:7px;border-radius:0;">'+
'<div class="timeline-item-title" style="color:black;margin-top:5px;text-align:center;"><div style="width:50px;height:50px;margin:0 auto;border-radius:50%;background-size:cover;background-position:50% 50%;background-image:url(\''+picturesrc+'\')"></div><span style="clear:both;">'+correctname+'<span> </div>'+
// '<div style="padding:10px;font-size:13px;"><span style="color:#6d6d72;clear:both;padding-top:-5px;">'+confirmtext+'</span></div>'+
'<div style="text-align:center;clear:both;width:100%;color:#8e8e93;">'+timestamptitle+'</div>'+
'</div>'+
'</a>'
);
if(rightdates[i].type=='date'){
//for (k = 0; k < rightdates[i].interest.length; k++) {
// $( "#interestdatediv_" + correctid).append('<a href="#" style="margin-right:5px"><i class="twa twa-'+rightdates[i].interest[k]+'" style="margin-top:5px;margin-right:5px"></i></a>');
// }
}
}
}
}
});
}
function newAm(){
$( ".originalam" ).hide();
$( ".newam" ).show();
pickerDescribe.open();
}
function newMe(){
$( ".originalme" ).hide();
$( ".newme" ).show();
pickerDescribe2.open();
}
var deletedphoto;
function getData(){
deletedphoto = false;
if(photosloaded === false){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/userdata.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
var result = JSON.parse(data);
//console.log(result);
if (result!='77' && result[0].largeurl){
$( ".reorderbutton" ).removeClass('disabled');
$( ".deleteallbutton" ).removeClass('disabled');
f_smallurls = result[0].smallurl.split(',');
f_largeurls = result[0].largeurl.split(',');
//console.log(result[0].widthslides);
//console.log(result[0].heightslides);
addedwidth = result[0].widthslides.split(',');
addedheight = result[0].heightslides.split(',');
$( ".photosliderinfo" ).addClass('pictures');
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
for (i = 0; i < f_largeurls.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()">Remove</div></div>');
}
myswiperphotos = myApp.swiper('.container-photos', {
pagination:'.swiper-pagination',
paginationType:'progress',
direction:'vertical',
onInit:function(swiper){$( ".photoswiperloader" ).hide();},
onClick:function(swiper, event){
}
});
}
else {
f_smallurls = [];
f_largeurls = [];
addedheight = [];
addedwidth = [];
$( ".wrapper-photos" ).append('<div class="swiper-slide firsthere" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos = myApp.swiper('.container-photos', {
pagination:'.swiper-pagination',
paginationType:'progress',
onInit:function(swiper){$( ".photoswiperloader" ).hide();},
direction:'vertical'
});
}
});
}).catch(function(error) {
// Handle error
});
}
if (photosloaded === true){myswiperphotos.update();}
photosloaded = true;
}
function deleteIndividual(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
if ($( ".photosliderinfo" ).hasClass('pictures')){
myApp.confirm('Are you sure?', 'Delete Photo', function () {
myswiperphotos.removeSlide(myswiperphotos.clickedIndex);
f_largeurls.splice(myswiperphotos.clickedIndex, 1);
f_smallurls.splice(myswiperphotos.clickedIndex, 1);
addedwidth.splice(myswiperphotos.clickedIndex, 1);
addedheight.splice(myswiperphotos.clickedIndex, 1);
//console.log(addedwidth);
//console.log(addedheight);
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
deletedphoto = true;
myswiperphotos.update();
if (myswiperphotos.slides.length > 0){
firebase.database().ref('users/' + f_uid).update({
image_url:f_largeurls[0],
photoresponse:'Y'
}).then(function() {});
}
if (myswiperphotos.slides.length === 0){
firebase.database().ref('users/' + f_uid).update({
image_url:f_image,
photoresponse:'N'
}).then(function() {});
$( ".reorderbutton" ).addClass('disabled');
$( ".deleteallbutton" ).addClass('disabled');
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos.updatePagination();
myswiperphotos.update();
}
});
}
else {
photosPopup();
}
}
function openAvaill(availtime){
if ($( '.li_'+ availtime ).hasClass('selecrec')){$( '.li_'+ availtime ).removeClass('selecrec');$( '.li_'+ availtime ).css('selecrec','');$( '#picker'+ availtime ).val('');}
else{$( '.li_'+ availtime ).addClass('selecrec');$( '#picker'+ availtime ).val('Now');}
}
function openAvail(availtime){
$( '.li_'+ availtime ).addClass('selecrec');
}
function removeAvail(availtime,availname,availnameonly){
$( '.li_'+ availtime ).removeClass('selecrec');
$('#picker'+availtime ).remove();
$('.readd_'+availtime ).append('<input type="text" placeholder="'+availname+'" readonly id="picker'+availtime+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li>');
myApp.picker({
input: '#picker' + availtime,
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeAvail(\''+availtime+'\',\''+availname+'\',\''+availnameonly+'\');">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: (availnameonly + ',').split(',')
},
{
textAlign: 'left',
values: ('Anytime Morning Midday Afternoon Evening').split(' ')
},
]
});
}
var availarray = [];
function report(){
myApp.prompt('What is the problem?', 'Report '+targetname, function (value) {
if (value.length ===0){myApp.alert('You must provide a reason to report ' + targetname, 'What is the problem?');return false;}
targetreported = true;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:value,
response:'N',
timestamp: t_unix,
};
var updates = {};
updates['reports/' + f_uid + '/' + targetid + '/' + newPostKey] = targetData;
if (f_uid == first_number){
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
firstnumberreport:newPostKey,
firstnumberreporttime:t_unix
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
firstnumberreport:newPostKey,
firstnumberreporttime:t_unix
});
}
else{
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
secondnumberreport:newPostKey,
secondnumberreporttime:t_unix
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
secondnumberreport:newPostKey,
secondnumberreporttime:t_unix
});
}
return firebase.database().ref().update(updates).then(function() {
myApp.alert('We will review your report. We encourage you to block offensive users.', 'Report sent');});
});
$(".modal-text-input").prop('maxlength','50');
}
function more(){
var swiperno = 0;
myApp.confirm('Are you sure?', 'Block '+targetname, function () {
var blockindex = myPhotoBrowser.swiper.activeIndex;
targetid = new_all[blockindex].id;
myPhotoBrowser.swiper.removeSlide(blockindex);
myPhotoBrowser.swiper.updateSlidesSize();
swiperQuestions.removeSlide(blockindex);
swiperQuestions.updateSlidesSize();
new_all = new_all.slice(0,blockindex).concat(new_all.slice(blockindex+1));
if (new_all.length>0){
for (var i = 0; i < random_all.length; i++) {
if (random_all[i].id == targetid){
randomswiper.removeSlide(i);
randomswiper.updateSlidesSize();
random_all = random_all.slice(0,i).concat(random_all.slice(i+1));
}
}
for (var i = 0; i < nearby_all.length; i++) {
if (nearby_all[i].id == targetid){
nearbyswiper.removeSlide(i);
nearbyswiper.updateSlidesSize();
nearby_all = nearby_all.slice(0,i).concat(nearby_all.slice(i+1));
}
}
for (var i = 0; i < recent_all.length; i++) {
if (recent_all[i].id == targetid){
recentswiper.removeSlide(i);
recentswiper.updateSlidesSize();
recent_all = recent_all.slice(0,i).concat(recent_all.slice(i+1));
}
}
}
else {
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.destroy();
nearbyswiper.destroy();
recentswiper.destroy();
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
}
var firstpos;
var lastpos;
myApp.closeModal('.actions-modal');
allowedchange = false;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var theirnotifs = firebase.database().ref('notifications/' + targetid + '/' + f_uid);
theirnotifs.remove().then(function() {
//console.log("their notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("their notifs failed: " + error.message)
});
var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
mynotifs.remove().then(function() {
//console.log("my notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("my notifs failed: " + error.message)
});
var theirdates = firebase.database().ref('dates/' + targetid + '/' + f_uid);
theirdates.remove().then(function() {
//console.log("their dates Remove succeeded.")
})
.catch(function(error) {
//console.log("their dates failed: " + error.message)
});
var mydates = firebase.database().ref('dates/' + f_uid + '/' + targetid);
mydates.remove().then(function() {
//console.log("my dates Remove succeeded.")
})
.catch(function(error) {
//console.log("my dates failed: " + error.message)
});
var ourchats = firebase.database().ref('chats/' + first_number + '/' + second_number);
ourchats.remove().then(function() {
//console.log("Chats Remove succeeded.")
})
.catch(function(error) {
//console.log("Chats Remove failed: " + error.message)
});
var ourphotochats = firebase.database().ref('photochats/' + first_number + '/' + second_number);
ourphotochats.remove().then(function() {
//console.log("PhotoChats Remove succeeded.")
})
.catch(function(error) {
//console.log("PhotoChats Remove failed: " + error.message)
});
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
secondnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
secondnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
firstnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
second_name:targetname,
second_number:second_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
firstnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
second_name:targetname,
second_number:second_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
}
if (new_all.length>1){
if (blockindex == (new_all.length-1)){lastpos = 'Y';} else {lastpos ='N';}
if (blockindex == 0){firstpos = 'Y';} else{firstpos ='N';}
if (firstpos == 'Y'){myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();swiperQuestions.slideNext();swiperQuestions.slidePrev(); }
else if (lastpos == 'Y'){myPhotoBrowser.swiper.slidePrev();allowedchange = true;myPhotoBrowser.swiper.slideNext();swiperQuestions.slidePrev();swiperQuestions.slideNext(); }
else {myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();swiperQuestions.slideNext();swiperQuestions.slidePrev(); }
}
//myPhotoBrowser.swiper.slideTo(blockindex);
// console.log(all_matches_photos[swipertarget]);
// console.log(new_all);
if (new_all.length === 0){
myPhotoBrowser.close();myApp.closeModal();
$( ".home-title" ).hide();
$( ".results-loader" ).hide();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
// myPhotoBrowser.swiper.slideTo(blockindex);
if (new_all.length===1){
$( ".availyo_"+ new_all[0].id ).show();
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var targetdescription= new_all[0].description;
targetname = new_all[0].name;
var targetage = new_all[0].age;
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
}
if (new_all.length>0){
checkMatch(targetid);
}
});
}
var canscrollnotif = true;
function scrollNotifications(){
//console.log($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top);
if ((($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top) - 1 < $( document ).height())&& (canscrollnotif)) {
if (notifletsload < 12){$( "#notiflistdiv" ).append('<div class="loadnotifsloader" style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;"><div class="preloader " style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv");
objDiv.scrollTop = objDiv.scrollHeight;
setTimeout(function(){ $( ".loadnotifsloader" ).remove();objDiv.scrollTop = objDiv.scrollHeight-44;}, 2000);
}
else{$( "#notiflistdiv" ).append('<div style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;" class="loadnotifsloader"><div class="preloader" style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv");
objDiv.scrollTop = objDiv.scrollHeight;setTimeout(function(){ getmoreNotifs();}, 2000);}
}
}
function scrollMessages(){
if ((($( ".scrolldetect" ).offset().top) == 120) && (canloadchat)) {if (letsload < 20 || existingmessages < 20){$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ $( ".loadmessagesloader" ).hide(); }, 500);}else{$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ getPrevious(); }, 500);}}
}
function showDecide(){
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
$( ".toolbardecide" ).show();
}
function closeCreate(){
myApp.closeModal('.actions-modal');
myApp.closeModal('.chatpop');
singlefxallowed = true;
}
function createDate(messageid,messagename,redirect){
if (redirect===0) {}
else { if ($('.chatpop').length > 0){return false;}}
var centerdiv;
if (messageid) {targetid = messageid;}
if (messagename) {targetname = messagename;}
singleUser(targetid,targetname,88);
existingchatnotifications = firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.to_uid == f_uid) && (obj.from_uid == targetid) && (obj.received=='N')){
cordova.plugins.notification.badge.get(function (badge) {
var newcount = badge-obj.new_message_count;
if (newcount < 1){
$( ".notifspan" ).hide();
}
else {
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);
}
});
firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
}
});
}
});
if (messageid) {centerdiv = '<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;"><div class="navbarphoto"></div>'+targetname+'</div>';}
else{centerdiv = '<div class="center center-date close-popup" onclick="clearchatHistory();"><div class="navbarphoto"></div>'+targetname+'</div>';}
var divcentrecontent;
if (redirect === 0){divcentrecontent='<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;color:white;"><div class="navbarphoto"></div>'+targetname+'</div>';}
else {divcentrecontent='<span id="centerholder" style="color:white;z-index:99999999999999999999999999999999;color:white;"></span>';}
var popupHTML = '<div class="popup chatpop">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<a href="#" class="link icon-only date-back" onclick="closeCreate()" style="margin-left:-10px;color:white;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date-close" onclick="reverseRequest();" style="color:white;font-weight:bold;display:none;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date2-close" onclick="noChange();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date1-close" onclick="reverseRequest();dateConfirmationPage();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'</div>'+
divcentrecontent+
' <div class="right" onclick="actionSheet()" style="font-size:14px;">'+
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor" style="color:white"></i>'+
' </a></div>'+
'</div>'+
'</div>'+
'<div class="pages" style="margin-top:-44px;">'+
'<div data-page="datepopup" class="page">'+
'<div class="toolbar messagebar datetoolbar" style="display:none;background-color:transparent;">'+
' <div class="toolbar-inner yes-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px;display:none;text-align:center;">'+
'<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 33%;"><span style="margin: 0 auto;">Cancel</span></a>'+
'<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width:33%;"><span style="margin: 0 auto;">Change</span></a>'+
'<a href="#" onclick="acceptDate()" class="link" style="height:44px;color:white;background-color:#4cd964;width:33%;"><span style="margin: 0 auto;">Confirm</span></a>'+
'</div>'+
' <div class="toolbar-inner sender-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px; display:none;text-align:center;">'+
'<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 50%;"><span style="margin: 0 auto;">Cancel</span></a>'+
'<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width: 50%;"><span style="margin: 0 auto;">Change</span></a>'+
'</div>'+
' <div class="toolbar-inner date-inner" style="padding-left:0px;padding-right:0px;display:none;text-align:center;background-color:white;border-top:1px solid #2196f3;">'+
'<input id="datemessageq" placeholder="Add message..(optional)" style="width: calc(100% - 70px);margin-left:5px;background-color:white;max-height:44px;border-color:transparent;" type="text">'+
'<a href="#" style="z-index:99999999;height:44px;background-color:#2196f3;float:left;line-height:44px;width:70px;" onclick="processDupdate();"><span style="margin: 0 auto;padding-right:10px;padding-left:10px;color:white;">Send</span></a>'+
'</div>'+
' <div class="toolbar-inner message-inner" style="display:none;background-color:white;padding-left:0px;padding-right:0px;border-top:1px solid #2196f3;">'+
'<a href="#" class="link icon-only" style="margin-left:5px;"><i class="pe-7s-camera pe-lg" style="color:#2196f3;font-size:28px;"></i><i class="twa twa-bomb" style="z-index:999;margin-left:-10px;margin-top:-15px;"></i></a> <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:54px;width:50px;z-index:1;opacity:0;margin-top:-12px;margin-left:-50px;"><textarea id="messagebararea messagearea" type="text" placeholder="Type your message.." style="border-color:transparent;"></textarea><a href="#" class="link sendbutton" onclick="sendMessage();" style="margin-right:10px;margin-left:10px;">Send</a>'+
'</div>'+
'</div>'+
'<div class="datedetailsdiv date-button" onclick="noMessages();setDate();dateConfirmationPage(1);" style="display:none;position:absolute;top:44px;text-align:center;height:44px;width:100%;z-index:999999;">'+
'</div>'+
'<div class="page-content messages-content" onscroll="scrollMessages();" id="messagediv" style="background-color:#f7f7f8">'+
'<span class="preloader login-loader messages-loader" style="width:42px;height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;"></span>'+
'<div class="datearea" style="text-align:center;"></div>'+
'<div class="messages scrolldetect" style="margin-top:100px;">'+
'</div></div></div>'+
'</div></div>';
myApp.popup(popupHTML);
var closedvar = $$('.chatpop').on('popup:close', function () {
clearchatHistory();
});
//existingDate();
//setDate();
$( "#centerholder" ).append(centerdiv);
myApp.sizeNavbars();
//$( "#centerholder" ).remove();
if (datealertvar === false) {
datealertvar = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
datealert = firebase.database().ref("dates/" + f_uid +'/' + targetid).on('value', function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists) {
var unix = Math.round(+new Date()/1000);
if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) {
d_type = snapshot.child('type').val();
d_chat_expire = snapshot.child('chat_expire').val();
d_interest = snapshot.child('interest').val();
d_day = snapshot.child('day').val();
d_time = snapshot.child('time').val();
d_response = snapshot.child('response').val();
if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();}
d_created_uid = snapshot.child('created_uid').val();
d_timestamp = snapshot.child('timestamp').val();
d_dateseen = snapshot.child('dateseen').val();
d_dateseentime = snapshot.child('dateseentime').val();
d_message = snapshot.child('message').val();
var newtonight = new Date();
newtonight.setHours(23,59,59,999);
var newtonight_timestamp = Math.round(newtonight/1000);
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var chatdaystring;
var expiredateobject = new Date((d_chat_expire * 1000) - 86400);
var unixleft = d_chat_expire - newtonight_timestamp;
var daysleft = unixleft / 86400;
//console.log('daysleft' + daysleft);
var weekdaynamew = weekday[expiredateobject.getDay()];
if(daysleft <= 0){chatdaystring = 'Today';}
else if(daysleft === 1){chatdaystring = 'Tomorrow';}
else chatdaystring = weekdaynamew;
//console.log(unixleft);
//console.log(daysleft);
var hoursleft = unixleft / 3600;
var salut;
if (daysleft <=0){
salut='tonight';
}
else if (daysleft ==1) {salut = 'in ' + Math.round(daysleft)+' day';}
else{salut = 'in ' + daysleft+' days';}
var aftertag;
$( ".datedetailsdiv" ).empty();
$( ".datedetailsdiv" ).append('<div class="list-block media-list" style="margin-top:0px;border-bottom:1px solid #c4c4c4;">'+
'<ul style="background-color:#4cd964">'+
'<li>'+
' <div class="item-content" style="padding-left:15px;">'+
'<div class="item-media">'+
'<img src="media/'+d_type+'faceonly.png" style="height:36px;">'+
'</div>'+
'<div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title" style="font-size:15px;color:white;">See you <span class="chatdaystringdiv">'+chatdaystring+'</span><span class="chatafternavbar"></span></div>'+
' <div class="item-after" style="margin-top:-10px;margin-right:-15px;color:white;"><i class="pe-7s-angle-right pe-3x"></i></div>'+
' </div>'+
'<div class="item-subtitle" style="font-size:12px;text-align:left;color:white;">Chat will end '+salut+' (at midnight)</div>'+
// '<div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div> ' );
if (d_time){
var lowertime = d_time.toLowerCase()
if (chatdaystring == 'today'){$( ".chatdaystringdiv").empty();$( ".chatafternavbar").append('this ' + lowertime);}
else {
$( ".chatafternavbar").append(' ' + d_time);}
}
//if (d_interest && d_type =='duck'){
// if ((d_interest == 'my') && (d_created_uid == f_uid)){aftertag = 'At '+f_first+'\'s place';}
// if ((d_interest == 'your') && (d_created_uid == f_uid)){aftertag = 'At '+targetname+'\'s place';}
//}
//if (d_interest && d_type =='date'){
//for (i = 0; i < d_interest.length; i++) {
// $( ".chatafternavbar").append('<a href="#" style="margin-left:5px"><i class="twa twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>');
//}
//}
if (d_response == 'Y') {chatShow();}
else {
noMessages();
setDate();
dateConfirmationPage();
}
$( ".messages-loader" ).hide();
}
else{
cancelDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
}
else{
d_interest = false;
d_chat_expire = false;
d_day = false;
d_time = false;
d_response = false;
d_timeaccepted = false;
d_timestamp = false;
d_message = false;
d_dateseen = false;
d_dateseentime = false;
if (keepopen === 0){myApp.closeModal('.chatpop');clearchatHistory();}
noMessages();
setDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
//need to check if still matched
}
//alert('triggered');
// if (snapshot.val().response == 'W') {noMessages();
// setDate();dateConfirmationPage();}
// else {chatShow();}
//dateConfirmationPage();
keepopen = 0;
});
}
else {}
}
function scrollBottom(){
var objDiv = document.getElementById("messagediv");
objDiv.scrollTop = objDiv.scrollHeight;
//$("").animate({ scrollTop: $('#messagediv').prop("scrollHeight")}, 300);
}
function noMessages(){
$( ".messages" ).hide();
$( ".datearea" ).empty();
$( ".datearea" ).append(
'<div class="nomessages" style="margin:0 auto;margin-top:44px;text-align:center;background-color:white;">'+
//'<div class="profileroundpic" style="margin:0 auto;margin-top:5px;height:70px;width:70px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
'<div class="dateheader" style="display:none;background-color:#ccc;padding:11px;text-align:center;font-size:24px;color:white;font-family: \'Pacifico\', cursive;"></div>'+
'<div class="requesticon" style="padding-top:20px;"></div>'+
'<a href="#" onclick="request()" class="button dr requestbutton" style="width:150px;margin: 0 auto;margin-top:10px;font-family: \'Pacifico\', cursive;font-size:20px;"></a>'+
'<div class="dr infop" style="padding:10px;background-color:white;color:#666;"><h3 class="titleconfirm" style="margin-top:10px;display:none;"></h3><p class="infoconfirm">Once you agree on a time to meet you can send instant chat messages to each other.</p></div>'+
'<div class="waitingreply"></div>'+
'<div id="createdatepicker" style="clear:both;border-bottom:1px solid #c4c4c4;margin-top:10px;"></div>'+
'<div class="row date-row" style="display:none;clear:both;margin-top:5px;padding:10px;background-color:#white;">'+
' <div class="col-16.67 coffee_i interestbutton" onclick="interests(\'coffee\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-coffee" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 beers_i interestbutton" onclick="interests(\'beers\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-beers" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 wine-glass_i interestbutton" onclick="interests(\'wine-glass\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-wine-glass" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 movie-camera_i interestbutton" onclick="interests(\'movie-camera\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-movie-camera" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 tada_i interestbutton" onclick="interests(\'tada\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-tada" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 fork-and-knife_i interestbutton" onclick="interests(\'fork-and-knife\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-fork-and-knife" style="margin-top:5px;"></i></div>'+
'</div> '+
'<div class="row duck-row" style="display:none;clear:both;margin-top:10px;">'+
'<div class="buttons-row" style="width:100%;padding-left:10px;padding-right:10px;">'+
' <a href="#tab1" class="button button-big button-place button-my" onclick="duckClass(1);">My Place</a>'+
'<a href="#tab2" class="button button-big button-place button-your" onclick="duckClass(2);">Your Place</a>'+
'</div>'+
'</div> '+
'<div class="profileyomain profileyo_'+ targetid+'" style="border-top:1px solid #c4c4c4;"></div>'+
'<span class="preloader preloader-white avail-loader" style="margin-top:20px;clear:both;margin-bottom:10px;"></span>'+
'</div>');
if (d_type == 'date') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargedateicon);$( ".requestbutton" ).text('Request Date');$( ".dateheader" ).text('Let\'s Date');}
if (d_type == 'duck') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargeduckicon);$( ".requestbutton" ).text('Request Duck');$( ".dateheader" ).text('Let\'s Duck');}
}
function setDate(){
var dateset = 'N';
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var n = weekday[d.getDay()];
var alldays_values = [];
var alldays_names = [];
var tonight = new Date();
tonight.setHours(23,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
alldays_values.push(tonight_timestamp - 1);
alldays_values.push(tonight_timestamp);
alldays_names.push('Now');
alldays_names.push('Today');
var tomorrow_timestamp = tonight_timestamp + 86400;
alldays_values.push(tomorrow_timestamp);
alldays_names.push('Tomorrow');
for (i = 1; i < 6; i++) {
var newunix = tomorrow_timestamp + (86400 * i);
alldays_values.push(newunix);
var dat_number = i + 1;
var datz = new Date(Date.now() + dat_number * 24*60*60*1000);
n = weekday[datz.getDay()];
alldays_names.push(n);
}
pickerCustomToolbar = myApp.picker({
container: '#createdatepicker',
rotateEffect: true,
inputReadOnly: true,
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");},
toolbar:false,
onChange:function(p, value, displayValue){
setTimeout(function(){
var unixnow = Math.round(+new Date()/1000);
var middaystamp = new Date();
middaystamp.setHours(12,00,00,000);
var middaystamp_timestamp = Math.round(middaystamp/1000);
var threestamp = new Date();
threestamp.setHours(12,00,00,000);
var threestamp_timestamp = Math.round(threestamp/1000);
var fivestamp = new Date();
fivestamp.setHours(17,00,00,000);
var fivestamp_timestamp = Math.round(fivestamp/1000);
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
}, 1000);
if (p.cols[0].displayValue == 'Now' && (dateset == 'Y')){p.cols[1].setValue('');}
},
cols: [
{
displayValues: alldays_names,
values: alldays_values,
},
{
textAlign: 'left',
values: (' Morning Afternoon Midday Evening').split(' ')
},
]
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid);
ref.once("value")
.then(function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists){
var timecol = pickerCustomToolbar.cols[1];
timecol.setValue(snapshot.child('time').val());
var daycol = pickerCustomToolbar.cols[0];
daycol.setValue(snapshot.child('chat_expire').val());
}
dateset = 'Y';
if (d_interest && d_type =='date') {
for (i = 0; i < d_interest.length; i++) {
$( "." + d_interest[i] +"_i" ).addClass('interestchosen');
}
}
if (d_interest && d_type =='duck') {
if (d_interest == 'my' && d_created_uid == f_uid){ $( ".button-my" ).addClass("active");}
if (d_interest == 'my' && d_created_uid != f_uid){{ $( ".button-your" ).addClass("active");}}
if (d_interest == 'your' && d_created_uid == f_uid){{ $( ".button-your" ).addClass("active");}}
if (d_interest == 'your' && d_created_uid != f_uid){{ $( ".button-my" ).addClass("active");}}
}
});
$( "#createdatepicker" ).hide();
}
function infoPopup(){
var popupHTML = '<div class="popup">'+
'<div class="content-block">'+
'<p>Popup created dynamically.</p>'+
'<p><a href="#" class="close-popup">Close me</a></p>'+
'</div>'+
'</div>';
myApp.popup(popupHTML);
}
function dateUser(){
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
if ($( ".duckbutton" ).hasClass( "active" )&& $( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();}
if (
$( ".datebutton" ).hasClass( "active" )){$( ".datebutton" ).removeClass( "active" );
$( ".notifback" ).show();
$( ".mainback" ).hide();
if ($( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();}
removetoDate();
}
else{
if ($( ".datebutton" ).hasClass( "likesme" )){matchNotif();}
//clicked date
$( ".datebutton" ).addClass( "active" );$( ".duckbutton" ).removeClass( "active" );
addtoDate();
}
}
function addtoDate(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'Y',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'Y',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'Y',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'Y',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
}
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if ($('.photo-browser-slide').length > 1){
var potentialdate = f_date_me.indexOf(targetid);
if (potentialdate == -1) { myPhotoBrowser.swiper.slideNext(true,1000);
if ($('.infopopup').length > 0) {
if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}
}
}
//if button has blue border change the color
}
function removetoDate(){
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
}
function duckUser(){
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
if ($( ".datebutton" ).hasClass( "active" ) && $( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();}
if (
$( ".duckbutton" ).hasClass( "active" )){$( ".duckbutton" ).removeClass( "active" );
if ($( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();}
$( ".notifback" ).show();
$( ".mainback" ).hide();
removetoDuck();
}
else{
if ($( ".duckbutton" ).hasClass( "likesme" )){matchNotif();}
//clicked duck
$( ".duckbutton" ).addClass( "active" );$( ".datebutton" ).removeClass( "active" );
addtoDuck();
}
}
function removetoDuck(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
}
function markMe(){
var mearray = ["4"];
firebase.database().ref('users/' + f_uid).update({
//add this user to my list
date_me:mearray
});
}
function addtoDuck(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberduck:'Y',
secondnumberdate:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_number:first_number,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberduck:'Y',
secondnumberdate:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberduck:'Y',
firstnumberdate:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberduck:'Y',
firstnumberdate:'N',
created:f_uid,
received:targetid
});
}
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if ($('.photo-browser-slide').length > 1){
var potentialduck = f_duck_me.indexOf(targetid);
if (potentialduck == -1) { myPhotoBrowser.swiper.slideNext(true,1000);
if ($('.infopopup').length > 0) {
if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}}
}
}
var singleuserarray = [];
function singleUser(idw,idname,origin){
if (singleuserarray[0] != null){
$(".avail-loader").hide();
if (singleuserarray[0].availarraystring !== ''){
$(".availabilitylistblock_"+singleuserarray[0].id).remove();
$(".availtitle").remove();
$( ".profileyo_" + singleuserarray[0].id ).append(
'<div class="content-block-title availtitle" style="padding-top:0px;clear:both;margin-top:15px;">'+targetname+'\'s Availability</div>'+
'<div class="list-block media-list availabilitylistblock_'+singleuserarray[0].id+'" style="z-index:99999999999999;margin-top:0px;clear:both;margin-bottom:-40px;width:100%;">'+
'<ul style="background-color:transparent" style="width:100%;">'+
' </ul></div>');
var availablearrayindividual = JSON.parse(singleuserarray[0].availarraystring);
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){
$( ".availabilitylistblock_"+singleuserarray[0].id ).append(
' <li style="list-style-type:none;width:100%;" onclick="request(\''+availablearrayindividual[k].id+'\',\''+availablearrayindividual[k].time+'\')">'+
'<div class="item-content">'+
'<i class="pe-7s-angle-right pe-3x" style="position:absolute;right:5px;color:#007aff;"></i>'+
'<div class="item-media">'+
'<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+
' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+
' </div>'+
' </div>'+
'</div></li>'
);
}
}
}
if (origin){photoBrowser(0,singleuserarray[0].age,1,1);}
else{photoBrowser(0,singleuserarray[0].age);}
}
else{
if (singlefxallowed === false){return false;}
singlefxallowed = false;
targetid = String(idw);
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/singleuser.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,latitudep:latitudep,longitudep:longitudep} )
.done(function( data ) {
//console.log(data);
var result = JSON.parse(data);
var availarraystring='';
var availnotexpired = false;
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
if(result[0].availstring && (result[0].availstring != '[]') && (result[0].uid != f_uid)){
var availablearrayindividual = JSON.parse(result[0].availstring);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
}
if (availnotexpired){availarraystring = result[0].availstring;}
}
var timestampyear = result[0].timestamp.substring(0,4);
var timestampmonth = result[0].timestamp.substring(5,7);
var timestampday = result[0].timestamp.substring(8,10);
var timestamphour = result[0].timestamp.substring(11,13);
var timestampminute = result[0].timestamp.substring(14,16);
var timestampsecond = result[0].timestamp.substring(17,20);
var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800;
var d_unix = Math.round(+new Date()/1000);
var diff = (d_unix - timestampunix)/60;
var photosstringarray =[];
var photocount;
var photostring;
var profilepicstring;
var photoarrayuserlarge;
var photoarrayusersmall;
if(result[0].largeurl){
var heightarray = result[0].heightslides.split(",");
var widtharray = result[0].widthslides.split(",");
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[0].largeurl + '" class="swiper-lazy"></div></div>';
photocount = result[0].largeurl.split(",").length;
photoarrayuserlarge = result[0].largeurl.split(",");
photoarrayusersmall = result[0].smallurl.split(",");
profilepicstringlarge = photoarrayuserlarge[0];
profilepicstringsmall = photoarrayusersmall[0];
targetpicture = photoarrayuserlarge[0];
$( ".navbarphoto" ).html(' <div style="width:29px;height:29px;border-radius:50%;background-image:url(\''+profilepicstringlarge+'\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>');
photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="')
}
else{
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+targetid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>';
profilepicstringlarge = 'https://graph.facebook.com/'+targetid+'/picture?width=828&height=828';
profilepicstringsmall = 'https://graph.facebook.com/'+targetid+'/picture?width=368&height=368';
$( ".navbarphoto" ).html(' <div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?width=100&height=100\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>');
targetpicture = 'https://graph.facebook.com/'+targetid+'/picture?width=100&height=100';
photocount = 1;
}
var distance = parseFloat(result[0].distance).toFixed(1);
var distancerounded = parseFloat(result[0].distance).toFixed(0);
if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'}
if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'}
if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'}
if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'}
if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'}
if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'}
if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'}
if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'}
if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'}
if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'}
if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'}
if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'}
var namescount = result[0].displayname.split(' ').length;
var matchname;
if(namescount === 1){matchname = result[0].displayname;}
else {matchname = result[0].name.substr(0,result[0].displayname.indexOf(' '));}
singleuserarray.push({widthslides:result[0].widthslides,heightslides:result[0].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:result[0].age,description:result[0].description,id:targetid,url:'https://graph.facebook.com/'+targetid+'/picture?width=828',caption:'...',industry: result[0].industry, status: result[0].status, politics:result[0].politics,eyes:result[0].eyes,body:result[0].body,religion:result[0].religion,zodiac:result[0].zodiac,ethnicity:result[0].ethnicity,height:result[0].height,weight:result[0].weight});
// console.log(singleuserarray);
main_all = new_all;
new_all = singleuserarray;
$(".avail-loader").hide();
if (singleuserarray[0].availarraystring !== ''){
$(".availabilitylistblock_"+singleuserarray[0].id).remove();
$(".availtitle").remove();
$( ".profileyo_" + singleuserarray[0].id ).append(
'<div class="content-block-title availtitle" style="padding-top:0px;clear:both;margin-top:15px;">'+targetname+'\'s Availability</div>'+
'<div class="list-block media-list availabilitylistblock_'+singleuserarray[0].id+'" style="margin-top:0px;clear:both;margin-bottom:-40px;">'+
'<ul style="background-color:transparent">'+
' </ul></div>');
var availablearrayindividual = JSON.parse(singleuserarray[0].availarraystring);
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){
$( ".availabilitylistblock_"+singleuserarray[0].id ).append(
' <li style="list-style-type:none;" class="item-link item-content" onclick="request(\''+availablearrayindividual[k].id+'\',\''+availablearrayindividual[k].time+'\')">'+
'<div class="item-content">'+
'<i class="pe-7s-angle-right pe-3x" style="position:absolute;right:5px;color:#007aff;"></i>'+
'<div class="item-media">'+
'<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+
' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
}
}
if (origin == 88){
//alert('88');
}
else if (origin == 1){
//alert('99');
photoBrowser(0,singleuserarray[0].age,1,1);
}
else if (!origin){
//alert('100');
photoBrowser(0,singleuserarray[0].age);
}
});
});
}
}
function request(dayw,timeq){
$( ".profileyomain" ).hide();
canloadchat = false;
$( '.picker-items-col-wrapper' ).css("width", "auto");
$( ".requesticon" ).hide();
$( ".dateheader" ).show();
$( ".sender-inner" ).hide();
$( ".yes-inner" ).hide();
conversation_started = false;
if (d_response == 'Y') {
$( ".date-close" ).hide();
$( ".date2-close" ).show();
$( ".date1-close" ).hide();
}
if (d_response == 'W') {
$( ".date-close" ).hide();
$( ".date1-close" ).show();
$( ".date2-close" ).hide();
}
if(!d_response){
$( ".date-close" ).show();
$( ".date2-close" ).hide();
$( ".date1-close" ).hide();
}
$( ".messages" ).hide();
$( ".date-button" ).hide();
$( "#createdatepicker" ).show();
$( ".dr" ).hide();
$( ".date-back" ).hide();
if (d_type == 'date') {$( ".date-row" ).show();$( ".duck-row" ).hide();}
if (d_type == 'duck') {$( ".duck-row" ).show();$( ".date-row" ).hide();}
$( ".waitingreply" ).empty();
$( ".datetoolbar" ).slideDown();
$( ".message-inner" ).hide();
$( ".date-inner" ).show();
if (d_response=='Y'){$( "#datemessageq" ).val('');}
// $( ".center-date" ).empty();
// if (d_type=='date') {$( ".center-date" ).append('Date Details');}
// if (d_type=='duck') {$( ".center-date" ).append('Duck Details');}
myApp.sizeNavbars();
//$( "#createdatepicker" ).focus();
$( ".page-content" ).animate({ scrollTop: 0 }, "fast");
if (dayw){
var daycol = pickerCustomToolbar.cols[0];
daycol.setValue(dayw);
if (timeq != 'Anytime'){
var timecol = pickerCustomToolbar.cols[1];
timecol.setValue(timeq);
}
}
}
function noChange(){
myApp.closeModal('.actions-modal');
canloadchat = true;
$( ".sender-inner" ).hide();
$( ".messages" ).show();
$( ".date-close" ).hide();
$( ".date2-close" ).hide();
$( ".date1-close" ).hide();
$( ".message-inner" ).show();
$( ".date-inner" ).hide();
// $( ".center-date" ).empty();
$( "#createdatepicker" ).hide();
// $( ".center-date" ).append(targetname);
$( ".nomessages" ).hide();
$( ".date-back" ).show();
$( ".date-button" ).show();
scrollBottom();
myApp.sizeNavbars();
}
function reverseRequest(){
if ($('.availtitle').length > 0){$( ".datetoolbar" ).hide();}
myApp.closeModal('.actions-modal');
$( ".profileyomain" ).show();
$( ".dateheader" ).hide();
$( "#createdatepicker" ).hide();
$( ".dr" ).show();
$( ".date-back" ).show();
$( ".date-row" ).hide();
$( ".duck-row" ).hide();
$( ".date-close" ).hide();
$( ".requesticon" ).show();
$( ".date-inner" ).hide();
if (!d_day){
//$( ".center-date" ).empty();
// $( ".center-date" ).append(targetname);
myApp.sizeNavbars();
}
}
var message_count = 0;
var messages_loaded = false;
var conversation_started = false;
var prevdatetitle;
function chatShow(){
//fcm();
prevdatetitle = false;
letsload = 20;
canloadchat = true;
additions = 0;
$( ".yes-inner" ).hide();
$( ".sender-inner" ).hide();
$( ".datedetailsdiv" ).show();
message_count = 1;
image_count = 0;
$( ".messages" ).show();
$( ".datearea" ).empty();
$( ".date-back" ).show();
$( ".date-button" ).show();
$( ".date-close" ).hide();
$( ".date2-close" ).hide();
$( ".datetoolbar" ).show();
$( ".message-inner" ).show();
$( ".date-inner" ).hide();
// $( ".center-date" ).empty();
// $( ".center-date" ).append(targetname);
myApp.sizeNavbars();
myMessagebar = myApp.messagebar('.messagebar', {
maxHeight: 88
});
myMessages = myApp.messages('.messages', {
autoLayout: true,
scrollMessages:true
});
//if (myMessages) {myMessages.clean();}
if (message_history === true){}
if (message_history === false){
message_history = true;
//do the .on call here to keep receiving messages here
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) {
existingmessages = snapshot.numChildren();
// $( ".messages").append( '<a href="#" class="button scrollbutton" onclick="scrollBottom();" style="border:0;margin-top:10px;"><i class="pe-7s-angle-down-circle pe-2x" style="margin-right:5px;"></i> New Messages</a>');
// $( ".messages").append('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>');
// if (snapshot.numChildren() > 10) {$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>');}
}).then(function(result) {
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
message_historyon = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(20).on("child_added", function(snapshot) {
if (message_count ==1) {lastkey = snapshot.getKey();}
message_count ++;
var checkloaded;
if (existingmessages > 19){checkloaded = 20;}
else if (existingmessages < 20){checkloaded = existingmessages;}
if (message_count == checkloaded){messages_loaded = true;}
var obj = snapshot.val();
var datechatstring;
var messagedate = new Date((obj.timestamp * 1000));
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
//console.log('prevdatetitle does not exist');
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
//my messages
var unix = Math.round(+new Date()/1000);
if (obj.from_uid == f_uid) {
if (obj.param == 'dateset'){
$( ".messages" ).append(
'<div class="list-block media-list" style="margin-top:0px;">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-media">'+
' <img src="path/to/img.jpg">'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">Date Details</div>'+
' <div class="item-after">Element label</div>'+
' </div>'+
' <div class="item-subtitle">Subtitle</div>'+
' <div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>');
}
if (obj.param == 'message'){
myMessages.addMessage({
// Message text
text: obj.message,
// Random message type
type: 'sent',
// Avatar and name:
//avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
// Day
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
if (obj.photo_expiry){
if (obj.photo_expiry < Number(unix)){
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
}
else{
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// Avatar and name:
//avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
// Day
});
image_count ++;
}
}
else {
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// ' and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
}
}
if (conversation_started === true) {
$( ".message" ).last().remove();
$( ".message" ).last().addClass("message-last");
$('#buzzer')[0].play();
}
}
//received messages
if (obj.to_uid == f_uid) {
if (messages_loaded === true) {
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
if (snapshot.val()){
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
}
}
});
}
if (conversation_started === true) {
$('#buzzer')[0].play();
}
if (obj.param == 'dateset'){
$( ".messages" ).append(
'<div class="list-block media-list">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-media">'+
' <img src="path/to/img.jpg">'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">Element title</div>'+
' <div class="item-after">Element label</div>'+
' </div>'+
' <div class="item-subtitle">Subtitle</div>'+
' <div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>');
}
if (obj.param == 'message'){
myMessages.addMessage({
// Message text
text: obj.message,
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: targetname,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
if (!obj.photo_expiry){
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
var seentime = Math.round(+new Date()/1000);
var expirytime = Math.round(+new Date()/1000) + 86400;
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
firebase.database().ref('photostodelete/' + obj.from_uid + '/' +obj.to_uid+ '/' +obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
}
else {
if (obj.photo_expiry < Number(unix)){
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
}
else{
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
}
}
}
}
}, function (errorObject) {
});
});
}
//myMessages.layout();
//myMessages = myApp.messages('.messages', {
// autoLayout: true
//});
//myMessages.scrollMessages();
myApp.initPullToRefresh('.pull-to-refresh-content-9');
}
var notifadditions=0;
var notifletsload = 12;
function getmoreNotifs(){
notifadditions ++;
var notifsloaded = notifadditions * 12;
var notif2load = mynotifs.length - (notifadditions * 12);
if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;}
var lasttoaddnotif = notifsloaded + notifletsload;
$(".loadnotifsloader").remove();
for (i = notifsloaded; i < lasttoaddnotif; i++) {
myList.appendItem({
title: mynotifs[i].title,
targetid:mynotifs[i].targetid,
targetname:mynotifs[i].targetname,
picture:mynotifs[i].picture,
from_name: mynotifs[i].from_name,
to_name: mynotifs[i].to_name,
from_uid:mynotifs[i].from_uid,
to_uid: mynotifs[i].to_uid,
icon:mynotifs[i].icon,
colordot:mynotifs[i].colordot,
func:mynotifs[i].func,
type:mynotifs[i].type,
timestamptitle:mynotifs[i].timestamptitle
});
}
canscrollnotif = true;
}
var letsload = 20;
function getPrevious(){
if (existingmessages === false){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) {
existingmessages = snapshot.numChildren();
previousFunction();
})
}
else{previousFunction();}
function previousFunction(){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var prevarray = [];
message_count = 0;
additions ++;
$(".previouschats").remove();
var left2load = existingmessages - (additions * 20);
if (left2load > 20) {letsload = 20;} else {letsload = left2load;}
//console.log('existingmessages' + existingmessages);
//console.log('letsload' + letsload);
//console.log('additions' + additions);
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var newmessage_history = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(letsload).endAt(lastkey).on("child_added", function(snapshot) {
message_count ++;
if (message_count ==1) {lastkey = snapshot.getKey();}
var obj = snapshot.val();
var datechatstring;
var messagedate = new Date((obj.timestamp * 1000));
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today'}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){
//console.log($(".message").length);
if ((letsload < 20) && (message_count == 1) ){
if (messagedaytitle == todaystring){datechatstring = 'Today'}
if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
else {datechatstring='';}
}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today'}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
}
//my messages
if (obj.from_uid == f_uid) {
if (obj.param == 'message'){
prevarray.push({
// Message text
text: obj.message,
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
prevarray.push({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
}
}
//received messages
if (obj.to_uid == f_uid) {
if (obj.param == 'message'){
prevarray.push({
// Message text
text: obj.message,
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: targetname,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
prevarray.push({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
}
}
if (message_count == letsload) {
$(".loadmessagesloader").remove();
canloadchat = true;
myMessages.addMessages(prevarray.slice(0, -1), 'prepend');
//$(".scrollbutton").remove();
//$(".messages").prepend('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>');
//if (message_count == 20){$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>' );$( ".messages" ).css("margin-top","132px");}
}
}, function (errorObject) {
// console.log("The read failed: " + errorObject.code);
});
}
}
var targetid;
var targetname;
var targetreported;
var targetdatearray,targetduckarray;
var targetdate,targetduck;
var match;
var targetdatelikes, targetducklikes;
var slideheight = $( window ).height();
function getMeta(url){
$("<img/>",{
load : function(){
if (this.height > this.width){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height',$(document).height() + 'px');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
}
},
src : url
});
}
function backtoProfile(){
myApp.closeModal('.infopopup') ;
$( ".toolbarq" ).hide();
//getMeta(new_all[myPhotoBrowser.activeIndex].url);
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
//$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none');
//put original image here
$( ".greytag" ).addClass('bluetext');
//$( ".photo-browser-slide img" ).css("height","100%");
$( ".datebutton" ).addClass('imagelibrary');
$( ".duckbutton" ).addClass('imagelibrary');
//$( ".swiper-container-vertical" ).css("height",slideheight + "px");
//$( ".swiper-container-vertical" ).css("margin-top","0px");
//$( ".swiper-slide-active" ).css("height", "600px");
$( ".toolbarq" ).css("background-color","transparent");
$( ".datefloat" ).hide();
$( ".duckfloat" ).hide();
$( ".vertical-pag" ).show();
//$( ".infopopup" ).css("z-index","-100");
$( ".onlineblock" ).hide();
//$( ".orlink" ).show();
//$( ".uplink" ).hide();
//$( ".nextlink" ).hide();
//$( ".prevlink" ).hide();
$( ".prevphoto" ).show();
$( ".nextphoto" ).show();
$( ".nexts" ).hide();
$( ".prevs" ).hide();
$( ".photo-browser-slide" ).css("opacity","1");
//$( ".datebutton" ).css("height","40px");
//$( ".duckbutton" ).css("height","40px");
//$( ".datebutton img" ).css("height","30px");
//$( ".duckbutton img" ).css("height","30px");
//$( ".datebutton img" ).css("width","auto");
//$( ".duckbutton img" ).css("width","auto");
$( ".photobrowserbar" ).css("background-color","transparent");
}
var comingback;
function scrollQuestions(){
//console.log($( ".wrapper-questions" ).offset().top);
//console.log($( window ).height());
var offsetline = $( window ).height() - 88;
var offsetdiv = $( ".wrapper-questions" ).offset().top;
//if (offsetdiv > offsetline){$( ".photo-browser-slide" ).css("opacity",1);}
var setopacity = (($( ".wrapper-questions" ).offset().top +88) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity);
//if
// if (offsetdiv > offsetline) {$( ".photo-browser-slide" ).css("opacity","1");$( ".adown" ).css("opacity","1");}
//var setopacity = (($( ".wrapper-questions" ).offset().top +10) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity);
}
function delayYo(){
}
function scrolltoTop(){
$( ".swiper-questions" ).animate({ scrollTop: $( window ).height() - 130 });
}
function questions(origin){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
$( ".toolbarq" ).css("background-color","transparent");
$( ".photobrowserbar" ).css("background-color","#ccc");
$( ".greytag" ).removeClass('bluetext');
var targetplugin = new_all[myPhotoBrowser.activeIndex].id;
//may need to readd this
//checkMatch(targetplugin);
comingback = 0;
if (origin){comingback = 1;}
if (swiperQuestions){
swiperQuestions.removeAllSlides();
swiperQuestions.destroy();
}
//alert($('.photo-browser-slide img').css('height'));
if ($('.infopopup').length > 0) {
myApp.alert('Something went wrong. Try restarting the app and please report this to us.', 'Oops');
myApp.closeModal('.infopopup');return false;
}
$( ".vertical-pag" ).hide();
$( ".datefloat" ).show();
$( ".duckfloat" ).show();
$( ".datebutton" ).removeClass('imagelibrary');
$( ".duckbutton" ).removeClass('imagelibrary');
//$( ".swiper-container-vertical.swiper-slide-active img" ).css("height","-webkit-calc(100% - 115px)");
//$( ".swiper-container-vertical" ).css("margin-top","-27px");
//$( ".swiper-slide-active" ).css("height","100%");
//$( ".photo-browser-slide img" ).css("height","calc(100% - 80px)");
//$( ".orlink" ).hide();
//$( ".uplink" ).show();
//$( ".nextlink" ).show();
//$( ".prevlink" ).show();
$( ".onlineblock" ).show();
//$( ".datebutton" ).css("height","70px");
//$( ".duckbutton" ).css("height","70px");
//$( ".datebutton img" ).css("height","60px");
//$( ".duckbutton img" ).css("height","60px");
//$( ".datebutton img" ).css("width","auto");
//$( ".duckbutton img" ).css("width","auto");
//$( ".nametag" ).removeClass('whitetext');
var photobrowserHTML =
'<div class="popup infopopup" style="background-color:transparent;margin-top:44px;height:calc(100% - 127px);padding-bottom:20px;z-index:12000;" >'+
// ' <a href="#tab1" class="prevs button disabled" style="border-radius:5px;position:absolute;left:-37px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99;color:#2196f3;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-left pe-4x" style="margin-left:7px;margin-top:-1px;z-index:-1"></i></a>'+
// ' <a href="#tab3" class="nexts button" style="border-radius:5px;position:absolute;right:-37px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2196f3;border:0;z-index:99;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+
'<div class="swiper-container swiper-questions" style="height:100%;overflow-y:scroll;">'+
'<div style="height:100%;width:100%;overflow-x:hidden;" onclick="backtoProfile();">'+
'</div>'+
' <div class="swiper-wrapper wrapper-questions" style="">'+
' </div>'+
'</div>'+
'</div>'
myApp.popup(photobrowserHTML,true,false);
$( ".nexts" ).show();
$( ".prevs" ).show();
$( ".prevphoto" ).hide();
$( ".nextphoto" ).hide();
for (i = 0; i < new_all.length; i++) {
var boxcolor,displayavail,availabilityli,availabletext,iconavaill;
iconavaill='f';boxcolor = 'width:60px;color:#007aff;opacity:1;background-color:transparent';displayavail='none';availabletext='';
$( ".wrapper-questions" ).append('<div class="swiper-slide slideinfo_'+new_all[i].id+'" style="height:100%;">'+
//'<h3 class="availabilitytitle_'+new_all[i].id+'" style="color:white;font-size:16px;padding:5px;float:left;"><i class="pe-7-angle-down pe-3x"></i></h3>'+
'<h3 onclick="scrolltoTop()" class="adown arrowdown_'+new_all[i].id+' availyope availyo_'+ new_all[i].id+'" style="display:none;margin-top:-60px;right:0px;'+boxcolor+';font-size:14px;padding:0px;margin-left:10px;"><i class="pe-7f-angle-down pe-3x" style="float:left;"></i>'+
'</h3>'+
'<div onclick="scrolltoTop()" style="z-index:12000;margin-top:15px;background-color:white;border-radius:20px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;margin-bottom:20px;display:none;" class="prof_'+i+' infoprofile availyo_'+ new_all[i].id+'">'+
'<div class="content-block-title" style="padding-top:0px;clear:both;margin-top:0px;">About '+new_all[i].name+'</div>'+
'<div class="list-block" style="margin-top:0px;clear:both;">'+
'<ul class="profileul_'+new_all[i].id+'" style="background-color:transparent">'+
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Online</div>'+
' <div class="item-input">'+
'<div class="timetag_'+ new_all[i].id+'"></div>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Distance</div>'+
' <div class="item-input">'+
'<div class="distancetag_'+ new_all[i].id+'"></div>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' </ul></div>'+
'</div>'+
'</div>');
//put here
if (new_all[i].description){
$( ".profileul_"+new_all[i].id ).prepend(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <textarea class="resizable" name="name" style="max-height:200px;font-size:14px;" readonly>'+new_all[i].description+'</textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].hometown){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Hometown</div>'+
' <div class="item-input">'+
'<textarea class="resizable" style="min-height:60px;max-height:132px;" readonly>'+new_all[i].hometown+'</textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].industry){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Industry</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].industry+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].zodiac){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Zodiac</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].zodiac+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].politics){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Politics</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].politics+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].religion){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Religion</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].religion+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].ethnicity){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Ethnicity</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].ethnicity+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].eyes){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Eye Color</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].eyes+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].body){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Body Type</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].body+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].height != 0){
if (new_all[i].height == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (new_all[i].height == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (new_all[i].height == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (new_all[i].height == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (new_all[i].height == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (new_all[i].height == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (new_all[i].height == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (new_all[i].height == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (new_all[i].height == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (new_all[i].height == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (new_all[i].height == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (new_all[i].height == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (new_all[i].height == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (new_all[i].height == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (new_all[i].height == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (new_all[i].height == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (new_all[i].height == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (new_all[i].height == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (new_all[i].height == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (new_all[i].height == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (new_all[i].height == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (new_all[i].height == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (new_all[i].height == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (new_all[i].height == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (new_all[i].height == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (new_all[i].height == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (new_all[i].height == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (new_all[i].height == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (new_all[i].height == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (new_all[i].height == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (new_all[i].height == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (new_all[i].height == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (new_all[i].height == 203) {var heightset = '203 cm (6\' 8\'\')';}
$(".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Height</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+heightset+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].weight != 0){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Weight</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].weight+' kg (' + Math.round(new_all[i].weight* 2.20462262) + ' lbs)" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
var timestring;
var minutevalue;
if (new_all[i].minutes <= 0){timestring = 'Now';}
if (new_all[i].minutes == 1){timestring = '1 minute ago';}
if ((new_all[i].minutes >= 0) && (new_all[i].minutes <60)){timestring = Math.round(new_all[i].minutes) + ' minutes ago';}
if (new_all[i].minutes == 60){timestring = '1 hour ago';}
if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){
minutevalue = Math.round((new_all[i].minutes / 60));
if (minutevalue == 1) {timestring = '1 hour ago';}
else {timestring = minutevalue + ' hours ago';}
}
if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){timestring = Math.round((new_all[i].minutes / 60)) + ' hours ago';}
if (new_all[i].minutes == 1440){timestring = '1 day ago';}
if ((new_all[i].minutes >= 1440) && (new_all[i].minutes <10080)){
minutevalue = Math.round((new_all[i].minutes / 1440));
if (minutevalue == 1) {timestring = '1 day ago';}
else {timestring = minutevalue + ' days ago';}
}
if (new_all[i].minutes >= 10080){timestring = '1 week';}
if (new_all[i].minutes >= 20160){timestring = '2 weeks';}
if (new_all[i].minutes >= 30240){timestring = '3 weeks';}
$( ".timetag_" + new_all[i].id ).html(timestring);
$( ".distancetag_" + new_all[i].id ).html(new_all[i].distancestring);
}
swiperQuestions = myApp.swiper('.swiper-questions', {
nextButton:'.nexts',
prevButton:'.prevs',
onSetTranslate:function(swiper, translate){myPhotoBrowser.swiper.setWrapperTranslate(translate - (20 * swiper.activeIndex));},
onInit:function(swiper){
myPhotoBrowser.swiper.setWrapperTranslate(0);
$( ".infoprofile").hide();
$( ".adown" ).css( "opacity","1" );
var wrapperheightshould = $(".prof_" + swiper.activeIndex).height();
$( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px");
$( ".availyope").hide();
//$( ".availyo_"+ new_all[0].id ).show();
if (new_all.length === 1){swiper.lockSwipes();myPhotoBrowser.swiper.lockSwipes();}
//checkmatchwashere
//checkMatch(targetid);
},
onSlideChangeStart:function(swiper){
var wrapperheightshould = $(".prof_" + swiper.activeIndex).height();
$( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px");
if(comingback === 1){
if (swiper.activeIndex > swiper.previousIndex){myPhotoBrowser.swiper.slideNext();}
if (swiper.activeIndex < swiper.previousIndex){myPhotoBrowser.swiper.slidePrev();}
}
// if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" );
//}
// else{$( ".prevs" ).removeClass( "disabled" );}
// if (swiper.isEnd === true){$( ".nexts" ).addClass( "disabled" );}
// else{$( ".nexts" ).removeClass( "disabled" );}
//if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" );
// $(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show();
// }
//else if (swiper.isEnd === true){$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); }
//else{$(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); }
//$( ".adown" ).css( "opacity","1" );
$( ".camerabadge" ).text(new_all[swiper.activeIndex].photocount);
$( ".infoprofile").hide();
$( ".availyope").hide();
//$(".swiper-questions").css("background-image", "url("+new_all[swiper.activeIndex].url+")");
//$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-size", "cover");
//$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-position", "50% 50%");
//$(".swiper-questions".css("background", "transparent");
$( ".swiper-questions" ).scrollTop( 0 );
if ($('.toolbarq').css('display') == 'block')
{
if (((swiper.activeIndex - swiper.previousIndex) > 1) ||((swiper.activeIndex - swiper.previousIndex) < -1) ){
//alert(swiper.activeIndex - swiper.previousIndex);
//myPhotoBrowser.swiper.slideTo(0);
myPhotoBrowser.swiper.slideTo(swiper.activeIndex);
//swiper.slideTo(myPhotoBrowser.swiper.activeIndex);
}
}
//checkmatchwashere
//checkMatch(targetid);
}
});
//console.log(myPhotoBrowser.swiper.activeIndex);
swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex,0);
$( ".availyo_"+ new_all[swiperQuestions.activeIndex].id ).show();
$( ".toolbarq" ).show();
comingback = 1;
$( ".camerabadge" ).text(new_all[myPhotoBrowser.swiper.activeIndex].photocount);
$( ".distancetag" ).text(new_all[myPhotoBrowser.swiper.activeIndex].distancestring);
//if (myPhotoBrowser.swiper.activeIndex === 0){
//myPhotoBrowser.swiper.slideNext();
//myPhotoBrowser.swiper.slidePrev();
//}
//else {
//}
//swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex);
}
function checkMatch(targetid){
var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
indivNotif.once('value', function(snapshot) {
if (snapshot.val()){
var obj = snapshot.val();
if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');}
else{$( ".indivnotifcount" ).remove();}
}
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) {
$( ".availyo_"+ new_all[swiperQuestions.activeIndex].id ).show();
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".loaderlink" ).hide();
$( ".orlink" ).show();
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if (snapshot.val() === null) {}
else {
if (first_number == f_uid){
if (snapshot.val().firstnumberreport){targetreported = true;}else {targetreported = false;}
//Dates
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
if (first_number == targetid){
if (snapshot.val().secondnumberreport){targetreported = true;}else {targetreported = false;}
//Date
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
}
});
}
function unmatchDate(){
myApp.confirm('Are you sure?', 'Unmatch', function () {
dateUser();
});
}
function unmatchDuck(){
myApp.confirm('Are you sure?', 'Unmatch', function () {
duckUser();
});
}
function photoBrowser(openprofile,arraynumber,mainchange,chatorigin){
allowedchange = true;
photoresize = false;
if ($('.photo-browser').length > 0){return false;}
myApp.closeModal('.picker-sub');
//firebase.database().ref("users/" + f_uid).off('value', userpref);
var photobrowserclass="";
var duckfunction = ""
var datefunction = ""
if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","10000" );photobrowserclass="photo-browser-close-link";}
else{duckfunction = "createDuck()";datefunction = "createDate1()";}
var to_open = 0;
if ($('.chatpop').length > 0 || chatorigin) {}
else {
to_open = openprofile;
}
var hiddendivheight = $( window ).height() - 40;
//alert(JSON.stringify(new_all));
myPhotoBrowser = myApp.photoBrowser({
zoom: false,
expositionHideCaptions:true,
lazyLoading:true,
lazyLoadingInPrevNext:true,
lazyPhotoTemplate:
'<div class="photo-browser-slide photo-browser-slide-lazy swiper-slide" style="background-color:transparent;">'+
'<div class="preloader {{@root.preloaderColorClass}}">{{#if @root.material}}{{@root.materialPreloaderSvg}}{{/if}}</div>'+
'<div class="swiper-container swiper-vertical" style="height:100%;min-width:'+$(document).width()+'px;background-color:transparent;">'+
'<div class="swiper-wrapper vertical-wrapper-swiper">'+
'{{js "this.photos"}}'+
'</div><div class="swiper-pagination vertical-pag" style="top:0;left:0;z-index:999999;"></div></div>'+
'</div>',
exposition:false,
photos: new_all,
captionTemplate:'<div style="width:40px;height:40px;background-color:transparent;margin-top:-80px;margin-left:50px;float:right;display:none;"></div><div class="photo-browser-caption" data-caption-index="{{@index}}">{{caption}}</div>',
toolbarTemplate:'<div class="toolbar tabbar toolbarq" style="height:84px;background-color:transparent;">'+
' <div class="toolbar-inner date-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+
'<a href="#" onclick="unmatchDate();" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;margin-left:15px;">'+
' Unmatch'+
'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" onclick="'+datefunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-right:15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Date <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x" style="margin-left:10px;margin-top:2px;"></i></div></a></div>'+
' <div class="toolbar-inner duck-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+
'<a href="#" onclick="unmatchDuck()" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;margin-left:15px;">'+
' Unmatch'+
'</a>'+
'<a href="#" onclick="'+duckfunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-left:15px;margin-right:15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Duck <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x" style="margin-left:10px;margin-top:2px;"></i></div></a></div>'+
' <div class="toolbar-inner toolbardecide" style="padding-bottom:10px;padding-left:0px;padding-right:0px;">'+
'<a href="#tab3" onclick="dateUser();" class="datebutton disabled button link" style="border:1px solid white;border-right:0;border-radius:20px;border-top-right-radius:0px;border-top-left-radius:0px;border-bottom-right-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+
'<span class="datefloat" style="padding:10px;border-radius:5px;margin-right:20px;">Date</span>'+
' <div style="width:50px;overflow-x:hidden;position:absolute;right:1px;bottom:-8px;"><img src="media/datefaceonly.png" style="width:100px;margin-left:-1px;">'+
'</div>'+
' </a>'+
' <a href="#tab3" onclick="duckUser();" class="duckbutton disabled button link" style="border:1px solid white;border-left:0;border-radius:20px;border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-left-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+
'<span class="duckfloat" style="padding:10px;border-radius:5px;margin-left:20px;">Duck</span>'+
' <div style="width:54px;overflow-x:hidden;position:absolute;left:-1px;bottom:-8px;"> <img src="media/duckfaceonly.png" style="width:100px;margin-left:-51px;"></div>'+
'</a>'+
'<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+
' </div>'+
'</div>',
onClose:function(photobrowser){myApp.closeModal('.actions-modal');hideProfile();
singlefxallowed = true;
viewphotos = false;
viewscroll = false;
if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","20000" );if ($('.chatpop').length > 0){myApp.closeModal('.infopopup');}
if (swiperQuestions){
swiperQuestions.removeAllSlides();
swiperQuestions.destroy();swiperQuestions = false;}
}
else{myApp.closeModal(); }
if (mainchange){new_all = main_all;singleuserarray = [];}
//getPreferences();
},
swipeToClose:false,
// onClick:function(swiper, event){showProfile();},
nextButton:'.nextphoto',
prevButton:'.prevphoto',
onSlideChangeStart:function(swiper){
if (allowedchange){
if (photoresize){
if ($('.infopopup').length > 0){}
else{
//getMeta(new_all[swiper.activeIndex].url);
}
}
if (swiper.activeIndex != openprofile){ photoresize = true;}
//var windowheight = $( window ).height();
//$( ".photo-browser-slide img").css( "height", "100% - 144px)" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
myApp.closeModal('.actions-modal');
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".duckbutton" ).hide();
$( ".datebutton" ).hide();
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
targetid = new_all[myPhotoBrowser.activeIndex].id;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var activecircle;
var targetdescription= new_all[myPhotoBrowser.activeIndex].description;
targetname = new_all[myPhotoBrowser.activeIndex].name;
var targetage = new_all[myPhotoBrowser.activeIndex].age;
$( ".agecat" ).text(targetage);
$( ".nametag" ).empty();
$( ".nametag" ).append('<div class="rr r_'+targetid+'">'+targetname+', '+targetage+'</div>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
}
checkMatch(targetid);
},
backLinkText: '',
//expositionHideCaptions:true,
navbarTemplate:
// ' <a href="#tab1" class="prevphoto button disabled" style="border-radius:5px;position:absolute;left:-31px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99999;color:#2196f3;background-color:transparent;"><i class="pe-7s-angle-left pe-4x" style="margin-left:5px;margin-top:-1px;"></i></a>'+
// ' <a href="#tab3" class="nextphoto button" style="border-radius:5px;position:absolute;right:-33px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2186f3;border:0;z-index:99999;background-color:transparent"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+
// '<div style="position:absolute;bottom:80px;right:0px;margin-left:-26px;z-index:9999;color:white;"><i class="pe-7s-info pe-4x" style="margin-top:-10px;"></i></div>'+
'<div class="navbar photobrowserbar" style="background-color:#ccc">'+
' <div class="navbar-inner">'+
' <div class="left sliding">'+
' <a href="#" style="margin-left:-10px;"class="link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
'<i class="pe-7s-angle-left pe-3x matchcolor greytag"></i>'+
'<span class="badge agecat" style="margin-left:-10px;display:none;">'+arraynumber+'</span>'+
' </a>'+
' </div>'+
' <div class="center sliding nametag matchcolor greytag">'+
// ' <span class="photo-browser-current"></span> '+
// ' <span class="photo-browser-of">{{ofText}}</span> '+
// ' <span class="photo-browser-total"></span>'+
' </div>'+
' <div class="right" onclick="actionSheet()">' +
//'<a href="#" class="link"><div class="cameradivnum" style="background-color:transparent;border-radius:50%;opacity:0.9;float:left;z-index:999;"><i class="pe-7s-camera pe-lg matchcolor" style="margin-top:3px;margin-left:-5px;"></i><div class="camerabadge badge" style="position:absolute;right:0px;margin-right:-10px;top:5px;z-index:999;"></div></div></a>'+
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor greytag"></i>'+
' </a>'+
'</div>'+
'</div>'+
'</div> '
});
myPhotoBrowser.open();
targetid = new_all[myPhotoBrowser.activeIndex].id;
var mySwiperVertical = myApp.swiper('.swiper-vertical', {
direction: 'vertical',
zoom:'true',
pagination:'.swiper-pagination',
paginationType:'progress',
onSlideChangeStart:function(swiper){
var verticalheightarray = new_all[myPhotoBrowser.activeIndex].heightslides.split(",");
var verticalwidtharray = new_all[myPhotoBrowser.activeIndex].widthslides.split(",");
var trueh = verticalheightarray[swiper.activeIndex];
var truew = verticalwidtharray[swiper.activeIndex];;
if (trueh > truew){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
}
else if (trueh == trueh){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
}
else{
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none');
}
},
onImagesReady:function(swiper){
},
onInit:function(swiper){
//console.log(new_all[myPhotoBrowser.activeIndex]);
//
if (viewphotos){
setTimeout(function(){ backtoProfile();viewphotos = false; }, 100);
}
if (viewscroll){
setTimeout(function(){ scrolltoTop();viewscroll = false; }, 100);
}
},
onClick:function(swiper, event){
questions();
//if(myPhotoBrowser.exposed === true) {$( ".swiper-container-vertical img " ).css("margin-top","0px");}
//else {$( ".photo-browser-slide img " ).css("height","calc(100% - 120px)");$( ".photo-browser-slide img " ).css("margin-top","-35px");}
}
});
//var windowwidth = $( ".photo-browser-swiper-container" ).width();
$( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".photo-browser-caption" ).css( "margin-top", "-10px" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
myPhotoBrowser.swiper.slideTo(to_open,100);
checkMatch(targetid);
questions();
if (openprofile ===0){
if (myPhotoBrowser.swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );}
else{$( ".prevphoto" ).removeClass( "disabled" );}
if (myPhotoBrowser.swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );}
else{$( ".nextphoto" ).removeClass( "disabled" );}
//var windowheight = $( window ).height();
//$( ".photo-browser-slide img").css( "height", "100% - 144px)" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
var target = new_all[myPhotoBrowser.activeIndex].url;
var pretarget = target.replace("https://graph.facebook.com/", "");
targetid = String(pretarget.replace("/picture?width=828", ""));
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var activecircle;
var targetdescription= new_all[myPhotoBrowser.activeIndex].description;
targetname = new_all[myPhotoBrowser.activeIndex].name;
var targetage = new_all[myPhotoBrowser.activeIndex].age;
$( ".agecat" ).text(targetage);
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
//may need to readd
}
}
function showProfile(){
$( ".profile-info" ).show();
}
function hideProfile(){
$( ".profile-info" ).hide();
}
function dateRequest(){
$( ".dateheader" ).hide();
$( ".date-close" ).hide();
$( ".date-button" ).hide();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var ref = firebase.database().ref();
var datemessageq = $( '#datemessageq' ).val();
var unix = Math.round(+new Date()/1000);
var day = pickerCustomToolbar.cols[0].displayValue;
var time;
if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';}
else if (pickerCustomToolbar.cols[0].displayValue =='Today'){
var daterequestnow = new Date;
var hournow = daterequestnow.getHours();
if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';}
else{time = pickerCustomToolbar.cols[1].value;}
}
else{time = pickerCustomToolbar.cols[1].value;}
var chat_expire = pickerCustomToolbar.cols[0].value;
var interestarray = [];
if (d_type == 'date'){
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestarray.push(interestadd);
}
});
}
if (d_type == 'duck'){
if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'}
if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'}
}
firebase.database().ref("dates/" + f_uid +'/' + targetid).set({
created_uid: f_uid,
created_name: f_first,
received_uid:targetid,
received_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
timestamp:unix,
day:day,
time:time,
chat_expire:chat_expire,
seen:'N',
interest:interestarray,
response:'W',
type:d_type,
message:datemessageq,
authcheck:f_uid
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).set({
created_uid: f_uid,
created_name: f_first,
received_uid:targetid,
received_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
timestamp:unix,
day:day,
time:time,
chat_expire:chat_expire,
seen:'N',
interest:interestarray,
response:'W',
type:d_type,
message:datemessageq,
authcheck:f_uid
});
sendNotification(targetid,2);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'Duck request'}
if (d_type=='date'){smessage = 'Date request'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'daterequest',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
if(d_response=='Y') {chatShow();}
else {reverseRequest();}
});
}
}
var d_interest,d_day,d_chat_expire,d_time,d_response,d_type,d_timestamp,d_dateseen,d_dateseentime,d_timeaccepted;
function existingDate(){
$( ".datearea" ).empty();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
// Test if user exists
var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid);
ref.once("value")
.then(function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists) {
var unix = Math.round(+new Date()/1000);
if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) {
d_chat_expire = snapshot.child('chat_expire').val();
d_interest = snapshot.child('interest').val();
d_type = snapshot.child('type').val();
d_day = snapshot.child('day').val();
d_time = snapshot.child('time').val();
d_response = snapshot.child('response').val();
if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();}
d_created_uid = snapshot.child('created_uid').val();
d_timestamp = snapshot.child('timestamp').val();
d_dateseen = snapshot.child('dateseen').val();
d_dateseentime = snapshot.child('dateseentime').val();
d_message = snapshot.child('message').val();
if (d_response == 'Y') {chatShow();}
else {
noMessages();
setDate();
dateConfirmationPage();
}
$( ".messages-loader" ).hide();
}
else{
cancelDate();
//$( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
}
else{
d_chat_expire = false;
d_interest = false;
d_day = false;
d_time = false;
d_response = false;
d_message = false;
d_timeaccepted;
d_dateseen = false;
d_dateseentime = false;
d_timestamp = false;
noMessages();
setDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
});
}
function interests(id){
$( "." + id + "_i" ).toggleClass( "interestchosen" );
}
function sendMessage(){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var datechatstring;
var messagedate = new Date();
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
var newmessage = $( "#messagearea" ).val();
if (newmessage === ''){return false;}
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var t_unix = Math.round(+new Date()/1000);
firebase.database().ref("chats/" + first_number+ '/' + second_number).push({
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:newmessage,
seen:'N',
timestamp: t_unix,
type: d_type,
param:'message',
authcheck:f_uid
});
myMessages.addMessage({
// Message text
text: newmessage,
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
//myMessagebar.clear();
var messageq;
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
//alert('yo3');
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
//alert(obj.param);
// alert(obj.received);
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
// alert('param'+obj.param);
// alert('new_message_count'+obj.new_message_count);
if (obj.param =='message'){
messageq = obj.new_message_count;
messageq ++;}
else{
messageq = 1;
}
}
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
}
});
}
newNotification(messageq);
});
function newNotification(messagenum){
//alert('messagenum'+messagenum);
if (!messagenum) {messagenum = 1;}
//alert(messagenum);
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:newmessage,
timestamp: t_unix,
type:d_type,
param:'message',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates);
}
$( "#messagearea" ).val('');
$( ".sendbutton" ).removeClass('disabled');
sendNotification(targetid,4);
}
function clearchatHistory(){
singlefxallowed = true;
messages_loaded = false;
if (main_all[0] != null){
new_all = main_all;
}
singleuserarray = [];
letsload = 20;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
if (message_history){
//firebase.database().ref("notifications/" + f_uid).off('value', existingchatnotifications);
firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', message_historyon);
if(additions>0){
for (i = 0; i < additions.length; i++) {
firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', newmessage_history);
}
}
message_history = false;
message_count = 0;
additions = 0;
existingmessages = false;
conversation_started = false;
myMessages.clean();
myMessages.destroy();
}
if (datealertvar === true){
firebase.database().ref("dates/" + f_uid +'/' + targetid).off('value', datealert);
}
datealertvar = false;
if ($$('body').hasClass('with-panel-left-reveal')) {
$(".timeline").empty();
rightPanel();
}
if ($$('body').hasClass('with-panel-right-reveal')) {
myList.deleteAllItems();
myList.clearCache();
leftPanel();
}
}
function dateConfirmationPage(details){
$( ".messagebararea" ).css("height","44px");
$( ".messagebar" ).css("height","44px");
$( ".messages-content" ).css("padding-bottom","0px");
$( ".datetoolbar" ).show();
canloadchat = false;
var g = new Date(d_chat_expire*1000 - 3600);
$( ".profileyomain" ).hide();
$( ".avail-loader" ).hide();
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var gday = weekday[g.getDay()];
var proposeddate = g.getDate();
var month = [];
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var messageclass;
if (d_created_uid == f_uid){messageclass="message-sent";messagestyle="";}
else{messageclass = "message-received";messagestyle="margin-left:70px;";}
var proposedmonth = month[g.getMonth()];
var proposedyear = g.getFullYear();
var dending;
if (proposeddate == '1' || proposeddate == '21' || proposeddate == '31'){dending = 'st'}
else if (proposeddate == '2' || proposeddate == '22'){dending = 'nd'}
else if (proposeddate == '3' || proposeddate == '23'){dending = 'rd'}
else {dending = 'th'}
$( ".dateheader" ).hide();
$( ".profileroundpic" ).show();
$( ".date1-close" ).hide();
$( ".date2-close" ).hide();
$( ".message-inner" ).hide();
$( ".date-inner" ).hide();
$( ".date-back" ).show();
var timedisplay;
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname.capitalize());
var titleblock;
var namefromdate;
var nametodate;
if (d_created_uid == f_uid){namefromdate = f_first;nametodate = targetname;}
else{nametodate = f_first;namefromdate = targetname;}
var whatrow;
var dateseentitle;
var timestamptitle;
var capitalD;
if (d_type =='duck'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Duck Request</span>';whatrow = 'Duck';capitalD = 'Duck';}
if (d_type =='date'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Date Request</span>';whatrow = 'Date';capitalD = 'Date';}
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - d_timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = 'Sent less than 1 minute ago';}
else if (tunixminago == 1) {timestamptitle = 'Sent 1 minute ago';}
else if (tunixminago < 2) {timestamptitle = 'Sent 1 minute ago';}
else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' minutes ago';}
else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 120) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';}
if (d_dateseen){
var unixago = unixnow - d_dateseentime;
var unixminago = unixago / 60;
if (unixminago < 1) {dateseentitle = 'Seen less than 1 minute ago';}
else if (unixminago == 1) {dateseentitle = 'Seen 1 minute ago';}
else if (unixminago < 2) {dateseentitle = 'Seen 1 minute ago';}
else if (unixminago < 60) {dateseentitle = 'Seen '+Math.round(unixminago)+' minutes ago';}
else if (unixminago == 60) {dateseentitle = 'Seen 1 hour ago';}
else if (unixminago < 120) {timestamptitle = 'Seen 1 hour ago';}
else if (unixminago < 1440) {dateseentitle = 'Seen '+Math.round(unixminago / 60) +' hours ago';}
else if (unixminago == 1440) {dateseentitle = 'Seen 1 day ago';}
else if (unixminago < 2880) {dateseentitle = 'Seen 1 day ago';}
else if (unixminago >= 2880) {dateseentitle = 'Seen '+Math.round(unixminago / 1440) +' days ago';}
}
else{dateseentitle = 'Request not seen yet';}
myApp.sizeNavbars();
var messagedateblock;
if (d_message){
messagedateblock='<li><div class="item-content"><div class="item-inner"><div class="messages-content"><div class="messages messages-init" data-auto-layout="true" style="width:100%;clear:both;"> <div class="item-title label" style="width:80px;float:left;margin-top:10px;text-align:left;">Message</div><div class="message '+messageclass+' message-appear-from-top message-last message-with-tail" style="'+messagestyle+'clear:both;text-align:left;"><div class="message-text">'+d_message+'</div></div></div></div></div></div></li><li style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>';
}
else {messagedateblock='';}
if (d_time) {timedisplay = ', ' + d_time}
else {timedisplay='';}
if (details){
var junixago = unixnow - d_timeaccepted;
var junixminago = junixago / 60;
var acceptedtitle;
if (junixminago < 1) {acceptedtitle = 'Confirmed less than 1 minute ago';}
else if (junixminago == 1) {acceptedtitle = 'Confirmed 1 minute ago';}
else if (junixminago < 2) {acceptedtitle = 'Confirmed 1 minute ago';}
else if (junixminago < 60) {acceptedtitle = 'Confirmed '+Math.round(junixminago)+' minutes ago';}
else if (junixminago == 60) {acceptedtitle = 'Confirmed 1 hour ago';}
else if (junixminago < 120) {acceptedtitle = 'Confirmed 1 hour ago';}
else if (junixminago < 1440) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 60) +' hours ago';}
else if (junixminago == 1440) {acceptedtitle = 'Confirmed 1 day ago';}
else if (junixminago < 2880) {acceptedtitle = 'Confirmed 1 day ago';}
else if (junixminago >= 2880) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 1440) +' days ago';}
$( ".date1-close" ).hide();
$( ".date2-close" ).show();
$( ".date-close" ).hide();
$( ".date-back" ).hide();
$( ".datetoolbar" ).show();
$( ".sender-inner" ).show();
$( ".yes-inner" ).hide();
//$( ".datetoolbar" ).css("background-color","#ccc");
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".waitingreply" ).append(
'<div style="background-color:#4cd964;padding:10px;text-align:center;font-size:20px;color:white;"><span style="font-family: \'Pacifico\', cursive;">'+capitalD+' Details</span></div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+acceptedtitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html(capitalD + ' confirmed');
$( ".infoconfirm" ).html('You can continue chatting until midnight of your scheduled '+d_type);
}
else if (d_created_uid == f_uid) {
$( ".datetoolbar" ).show();
$( ".sender-inner" ).show();
$( ".yes-inner" ).hide();
//$( ".datetoolbar" ).css("background-color","#ccc");
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html('Waiting for '+targetname+' to respond');
$( ".waitingreply" ).append(
'<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
}
else{
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var unix = Math.round(+new Date()/1000);
firebase.database().ref("dates/" + f_uid +'/' + targetid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("notifications/" + f_uid +'/' + targetid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("notifications/" + targetid +'/' + f_uid).update({
dateseen:'Y',
dateseentime:unix
});
$( ".datetoolbar" ).show();
$( ".sender-inner" ).hide();
$( ".yes-inner" ).show();
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html(targetname+' is waiting for your response');
$( ".waitingreply" ).append(
'<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
}
if (d_interest && d_type =='duck'){
$( ".interestli").show();
if ((d_interest == 'my') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');}
if ((d_interest == 'my') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');}
if ((d_interest == 'your') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');}
if ((d_interest == 'your') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');}
}
if (d_interest && d_type =='date'){
for (i = 0; i < d_interest.length; i++) {
$( ".interestli").show();
$( ".interestdiv").append('<a href="#" style="margin-right:5px"><i class="twa twa-2x twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>');
}
}
}
function acceptDate(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var unix = Math.round(+new Date()/1000);
$( ".sender-inner" ).hide();
$( ".yes-inner" ).hide();
var datemessageq = $( '#datemessageq' ).val();
var unix = Math.round(+new Date()/1000);
var day = pickerCustomToolbar.cols[0].displayValue;
var time;
if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';}
else if (pickerCustomToolbar.cols[0].displayValue =='Today'){
var daterequestnow = new Date;
var hournow = daterequestnow.getHours();
if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';}
else{time = pickerCustomToolbar.cols[1].value;}
}
else{time = pickerCustomToolbar.cols[1].value;}
var chat_expire = pickerCustomToolbar.cols[0].value;
var interestarray = [];
if (d_type == 'date'){
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestarray.push(interestadd);
}
});
}
if (d_type == 'duck'){
if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'}
if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'}
}
firebase.database().ref("dates/" + f_uid +'/' + targetid).update({
response: 'Y',
time_accepted: unix,
uid_accepted: f_uid,
authcheck:f_uid
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).update({
response: 'Y',
time_accepted: unix,
uid_accepted: f_uid,
authcheck:f_uid
});
sendNotification(targetid,3);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
//console.log(snapshot.val());
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
//console.log(messageq);
messageq ++;
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:'Date scheduled',
timestamp: t_unix,
type:d_type,
param:'dateconfirmed',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {chatShow();});
}
}
function cancelDate(){
// Create a reference to the file to delete
$( ".dateheader" ).hide();
$( ".sender-inner" ).hide();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
// Delete the file
firebase.database().ref("dates/" + f_uid +'/' + targetid).remove().then(function() {
// File deleted successfully
$( ".datearea" ).empty();
d_chat_expire = false;
d_interest = false;
d_day = false;
d_time = false;
d_response = false;
d_timeaccepted = false;
d_created_uid = false;
d_timestamp = false;
d_dateseen = false;
d_dateseentime = false;
d_message = false;
noMessages();
setDate();
//console.log('deleted');
}).catch(function(error) {
// Uh-oh, an error occurred!
});
// Delete the file
firebase.database().ref("dates/" + targetid +'/' + f_uid).remove().then(function() {
// File deleted successfully
//console.log('deleted');
}).catch(function(error) {
// Uh-oh, an error occurred!
});
sendNotification(targetid,6);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'Duck cancelled'}
if (d_type=='date'){smessage = 'Date cancelled'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'datedeleted',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
//console.log('delete notification sent');
});
}
}
function getPicture(key){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var datechatstring;
var messagedate = new Date();
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
var t_unix = Math.round(+new Date()/1000);
var returned = 0;
var postkeyarray = [];
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var eventy = document.getElementById('takePictureField_').files[0];
// var number_of_pictures = $(".imageli").length + 1;
if (eventy == 'undefined') {}
if (eventy !== 'undefined') {
for (i = 0; i < document.getElementById('takePictureField_').files.length; i++) {
var photoname = t_unix + i;
var newValue = firebase.database().ref().push().key;
postkeyarray.push(newValue);
myMessages.addMessage({
// Message text
text: '<img class="disabled image_'+newValue+'" src="'+URL.createObjectURL($('#takePictureField_').prop('files')[i])+'" onload="$(this).fadeIn(700);scrollBottom();" onclick="imagesPopup(\''+newValue+'\');" style="display:none;-webkit-filter: blur(50px);">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
//$("#dealimagediv_"+imagenumber).attr("src",URL.createObjectURL(eventy));
image_count ++;
//$('.image_' + t_unix).onclick = function(){
// openPhoto(url);};
//var randomstring = (Math.random() +1).toString(36).substr(2, 30);
var photochatspath = 'photochats/' + first_number + '/' + second_number + '/'+ photoname;
var photostorage = 'images/' + f_auth_id + '/' + photoname;
var photochatsRef = storageRef.child(photostorage);
photochatsRef.put($('#takePictureField_').prop('files')[i]).then(function(snapshot) {
var photodownloadstorage = 'images/' + f_auth_id + '/' + snapshot.metadata.name;
var photodownloadRef = storageRef.child(photodownloadstorage);
photodownloadRef.getDownloadURL().then(function(url) {
returned ++;
var newPostKey = postkeyarray[(returned-1)];
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var chatvar = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:'<img src="'+url+'" onload="$(this).fadeIn(700);" style="display:none" >',
seen:'N',
timestamp: snapshot.metadata.name,
type:d_type,
param:'image',
downloadurl:url,
first_number:first_number,
second_number:second_number
};
var photovar1 = {
id:newPostKey,
uid: f_uid,
user_name: f_first,
photo_name:photostorage,
downloadurl:url,
to_uid:targetid,
from_uid: f_uid,
first_number:first_number,
second_number:second_number,
folder:f_auth_id
};
var photovar2 = {
id:newPostKey,
uid: f_uid,
user_name: f_first,
downloadurl:url,
to_uid:targetid,
from_uid: f_uid,
first_number:first_number,
second_number:second_number
};
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + newPostKey).set(chatvar);
firebase.database().ref("photostodelete/" + f_uid + '/' + targetid + '/' + newPostKey).set(photovar1);
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + newPostKey).set(photovar2);
$(".image_"+newPostKey).attr("src", url);
$('.image_'+ newPostKey).removeClass("disabled");
$('.image_'+ newPostKey).css("-webkit-filter","none");
});
});
}
sendNotification(targetid,5);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
//console.log(obj.received);
//console.log(obj.from_uid);
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newpictureNotification(messageq);
});
}
function newpictureNotification(messagenum){
if (!messagenum) {messagenum = 1;}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:'Image ',
timestamp: t_unix,
type:d_type,
param:'image',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates);
}
}
function toTimestamp(year,month,day,hour,minute,second){
var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
return datum.getTime()/1000;
}
var photoarray;
function showPhotos(){
photoarray= [];
myApp.pickerModal(
'<div class="picker-modal photo-picker" style="height:132px;">' +
'<div class="toolbar" style="background-color:#2196f3">' +
'<div class="toolbar-inner">' +
'<div class="left"></div>' +
'<div class="right"><a href="#" class="close-picker" style="color:white;">Close</a></div>' +
'</div>' +
'</div>' +
'<div class="picker-modal-inner" style="background-color:#2196f3">' +
'<div class="content-block" style="margin:0px;padding:0px;">' +
'<div class="swiper-container swiper-photos">'+
'<div class="swiper-wrapper wrapper-photos">'+
' <div class="swiper-slide" style="text-align:center;margin:-5px;height:88px;">'+
'<i class="pe-7s-plus pe-3x" style="color:white;margin-top:10px;"></i>'+
' <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:60px;width:100%;z-index:1;opacity:0;height:88px;margin-top:-44px;" multiple="multiple"> '+
'</div>'+
'</div>'+
'</div>'+
'</div>' +
'</div>' +
'</div>'
);
var photosswiper = myApp.swiper('.swiper-photos', {
slidesPerView:3,
freeMode:true,
preloadImages: false,
// Enable lazy loading
lazyLoading: true,
watchSlidesVisibility:true
//pagination:'.swiper-pagination'
});
firebase.database().ref("photos/" + f_uid).once('value').then(function(snapshot) {
var childcount = 0;
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
//var key = childSnapshot.key;
// childData will be the actual contents of the child
childcount ++;
var childData = childSnapshot.val();
photoarray.push(childSnapshot.val());
$( ".wrapper-photos" ).append('<div onclick="sendphotoExisting(\''+childData.downloadurl+'\',\''+childData.filename+'\')" data-background="'+childData.downloadurl+'" style="border:1px solid black;margin:-5px;height:88px;background-size:cover;background-position:50% 50%;" class="swiper-slide swiper-lazy">'+
' <div class="swiper-lazy-preloader"></div>'+
'</div>');
if (childcount == snapshot.numChildren()){
photosswiper.updateSlidesSize();
photosswiper.slideTo(snapshot.numChildren());
// photosswiper.slideTo(0);
}
});
});
}
function sendphotoExisting(oldurl,filenamez){
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var t_unix = Math.round(+new Date()/1000);
myMessages.addMessage({
// Message text
text: '<img src="'+oldurl+'" onload="scrollBottom();">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first
// Day
// day: !conversationStarted ? 'Today' : false,
// time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false
});
firebase.database().ref("chats/" + first_number+ '/' + second_number).push({
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:'<img src="'+oldurl+'" onload="scrollBottom();">',
seen:'N',
timestamp: t_unix,
type:d_type,
param:'image',
filename:filenamez
});
myApp.closeModal('.photo-picker');
}
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
var xcountdown;
function imagesPopup(go){
if ($('.gallery-popupz').length > 0) {return false;}
var goz;
var popupHTML = '<div class="popup gallery-popupz">'+
'<div class="navbar" style="position:absolute;top:0;background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left"><a href="#" onclick="closeGallery();" class="link icon-only"><i class="pe-7s-angle-left pe-3x" style="margin-left:-10px;color:white;"></i> </a></div>'+
' <div class="center gallerytitle"></div>'+
' <div class="right photo-count"></div>'+
'</div>'+
'</div>'+
'<div class="pages">'+
'<div data-page="gallerypopup" class="page">'+
'<div class="page-content" style="background-color:white;">'+
'<div style="position:absolute;bottom:12px;right:8px;z-index:99999;background-color:white;border-radius:5px;padding:5px;"><div id="photodeletechattime" style="color:black;float:left;"></div></div>'+
'<span style="width:42px; height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;z-index:999999;" class="imagespopuploader preloader"></span> '+
'<div class="swiper-container swiper-gallery" style="height: calc(100% - 44px);margin-top:44px;">'+
' <div class="swiper-wrapper gallery-wrapper">'+
' </div>'+
'</div>'+
'<div class="swiper-pagination-gallery" style="position:absolute;bottom:0;left:0;z-index:999999;width:100%;height:4px;"></div>'+
'</div></div></div>'+
'</div>';
myApp.popup(popupHTML);
var first_number,second_number;
var gallerycount;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var galleryimagecount = 0;
var photodeletetime;
var phototo;
var photofrom;
var photochatid;
var touid;
firebase.database().ref("photochats/" + first_number+ '/' + second_number).once("value")
.then(function(snapshot) {
gallerycount = snapshot.numChildren();
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if (obj.id == go){goz = galleryimagecount;}
var expiryval;
if (obj.photo_expiry == null){expiryval = i;}
else {expiryval = obj.photo_expiry;}
$( ".gallery-wrapper" ).append(' <div class="swiper-slide photochat_'+obj.photo_expiry+'" style="height:100%;">'+
'<div class="swiper-zoom-container">'+
'<img data-src="'+obj.downloadurl+'" class="swiper-lazy" style="width:100%;" onload="$(this).fadeIn(700);hideImagespopuploader();">'+
' <div class="swiper-lazy-preloader"></div></div><input type="hidden" class="photoexpiryhidden_'+galleryimagecount+'" value="'+expiryval +'"><input type="text" class="fromhidden_'+galleryimagecount+'" value="'+obj.from_uid+'"><input type="text" class="tohidden_'+galleryimagecount+'" value="'+obj.user_name+'"><input type="text" class="idhidden_'+galleryimagecount+'" value="'+i+'"><input type="text" class="toidhidden_'+galleryimagecount+'" value="'+obj.to_uid+'"></div>');
galleryimagecount ++;
});
var galleryswiper = myApp.swiper('.swiper-gallery', {
preloadImages: false,
lazyLoadingInPrevNext:true,
// Enable lazy loading
lazyLoading: true,
watchSlidesVisibility:true,
zoom:true,
onInit:function(swiper){var slidenum = swiper.activeIndex + 1;
photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();
phototo = $( ".tohidden_" + swiper.activeIndex).val();
photofrom = $( ".fromhidden_" + swiper.activeIndex).val();
photochatid = $( ".idhidden_" + swiper.activeIndex).val();
touid = $( ".toidhidden_" + swiper.activeIndex).val();
if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';}
else{photodeletecount();}
$( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo);
},
onSlideChangeStart:function(swiper){clearInterval(xcountdown);
var slidenum = galleryswiper.activeIndex + 1;
photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();photodeletecount();
phototo = $( ".tohidden_" + swiper.activeIndex).val();
photofrom = $( ".fromhidden_" + swiper.activeIndex).val();
photochatid = $( ".idhidden_" + swiper.activeIndex).val();
touid = $( ".toidhidden_" + swiper.activeIndex).val();
if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';}
else{photodeletecount();deletePhotochat();}
$( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo);
myApp.sizeNavbars();
},
pagination:'.swiper-pagination-gallery',
paginationType:'progress'
});
galleryswiper.slideTo(goz,0);
myApp.sizeNavbars();
});
function deletePhotochat(){
if (photodeletetime < (new Date().getTime() / 1000)){
$( ".photochat_"+ photodeletetime).remove();
galleryswiper.update();
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + photochatid).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + photochatid).remove();
}
}
function photodeletecount(){
var countDownDate = new Date(photodeletetime * 1000);
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' + hours + "h "
+ minutes + "m " ;
// Update the count down every 1 second
xcountdown = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(xcountdown);
deletePhotochat();
}
else{ document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' +hours + "h "
+ minutes + "m " ;myApp.sizeNavbars();}
}, 60000);
}
}
function hideImagespopuploader(){ $( ".imagespopuploader" ).hide();}
function closeGallery(){
myApp.closeModal('.gallery-popupz');
clearInterval(xcountdown);
}
function updateOnce(){
var uids = ["1381063698874268","1394352877264527","393790024114307","4"];
firebase.database().ref('users/' + f_uid).update({
date_me:uids
});
}
function updatePhotos(){
$( ".pp" ).each(function() {
var classList = $(this).attr("class").split(' ');
var idofphoto = classList[2].replace("photo_", "");
var index1 = f_date_match.indexOf(idofphoto);
var index2 = f_duck_match.indexOf(idofphoto);
var u_date_me = f_date_me.indexOf(idofphoto);
var u_to_date = f_to_date.indexOf(idofphoto);
var u_duck_me = f_duck_me.indexOf(idofphoto);
var u_to_duck = f_to_duck.indexOf(idofphoto);
if (index2 > -1) {
if ($( '.rr').hasClass('r_' + idofphoto)) {
d_type='duck';
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
}
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');
$( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" );
}
else if (index1 > -1) {
if ($( '.rr').hasClass('r_' + idofphoto)) {
d_type='date';
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
}
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');
$( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" );
}
else{$( this ).css( "-webkit-filter","grayscale(80%)" );$( ".distance_" + idofphoto ).css( "background-color","#ccc" );
$( ".iconpos_" + idofphoto ).empty();
$( ".name_" + idofphoto ).css( "-webkit-filter","grayscale(80%)" );
if (u_date_me > -1){
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" );
}
if (u_duck_me > -1) {
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" );
}
if ($( '.rr').hasClass('r_' + idofphoto)) {
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
// alert(u_date_me);
// alert(u_duck_me);
if (u_date_me > -1) {$( ".datebutton" ).addClass( "likesme" );
}
else {$( ".datebutton" ).removeClass( "likesme" );}
if (u_duck_me > -1) {$( ".duckbutton" ).addClass( "likesme" );
}
else {$( ".duckbutton" ).removeClass( "likesme" );}
}
}
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
function singleBrowser(idw,idname,origin){
//firebase.database().ref("users/" + f_uid).off('value', userpref);
//targetid = idw;
targetid = String(idw);
targetname = idname;
var dbuttons;
if (origin){
dbuttons= ' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" onclick="createDate1()" class="button link active" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+
// '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
'<a href="#" onclick="createDuck()" class="button link active" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>';
}
else {
dbuttons=' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" class="button link active photo-browser-close-link" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+
// '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
'<a href="#" onclick="createDuck()" class="button link active photo-browser-close-link" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>';
}
singlePhotoBrowser = myApp.photoBrowser({
zoom: 400,
lazyLoading:true,
lazyLoadingInPrevNext:true,
//exposition:false,
photos: [{
url: 'https://graph.facebook.com/'+targetid+'/picture?type=large',
caption: '...'
}],
toolbarTemplate:'<div class="toolbar tabbar" style="height:100px;">'+
dbuttons+
' <div class="toolbar-inner toolbardecide">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargedateicon +'</a>'+
' <a href="#" class="link orlink">'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;">or</p>'+
' </a>'+
'<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+
'<a href="#" onclick="duckUser();" class="duckbutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargeduckicon +'</a>'+
' </div>'+
'</div>',
onOpen:function(photobrowser){
$( ".chatpop" ).css( "z-index","10000" );},
onClose:function(photobrowser){hideProfile();$( ".chatpop" ).css( "z-index","11500" );
//getPreferences();
},
swipeToClose:false,
// onClick:function(swiper, event){showProfile();},
backLinkText: '',
navbarTemplate: '<div class="navbar photobrowserbar">'+
' <div class="navbar-inner">'+
' <div class="left sliding">'+
' <a href="#" style="margin-left:-10px;" class="matchcolor mainback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
// ' <i class="icon icon-back {{iconsColorClass}}"></i> '+
'<i class="pe-7s-angle-left pe-3x"></i> '+
// '<span class="badge agecat">'+arraynumber+'</span>'+
' </a>'+
' <a href="#" onclick="myApp.closeModal();clearchatHistory();" style="display:none;margin-left:-10px;" class="matchcolor notifback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
' <i class="pe-7s-angle-left pe-3x "></i> '+
// '<span class="badge agecat">'+arraynumber+'</span>'+
' </a>'+
' </div>'+
' <div class="center sliding nametag matchcolor">'+
// ' <span class="photo-browser-current"></span> '+
// ' <span class="photo-browser-of">{{ofText}}</span> '+
// ' <span class="photo-browser-total"></span>'+
' </div>'+
' <div class="right" >' +
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor"></i>'+
' </a>'+
'</div>'+
'</div>'+
'</div> '
});
singlePhotoBrowser.open();
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+'</span>');
var windowwidth = $( ".photo-browser-swiper-container" ).width();
$( ".photo-browser-slide img" ).css( "width", windowwidth + "px" );
$( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".photo-browser-caption" ).css( "margin-top", "-10px" );
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/userdata.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,sexuality:sexuality} )
.done(function( data ) {
var result = JSON.parse(data);
var targetdescription= result[0].description;
//var targetname = result[0].name.substr(0,result[0].name.indexOf(' '));
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
});
}).catch(function(error) {
// Handle error
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) {
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
$( ".loaderlink" ).hide();
$( ".orlink" ).show();
if (snapshot.val() === null) {}
else {
if (first_number == f_uid){
//Dates
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
if (first_number == targetid){
//Date
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
}
});
}
function deletePhotos(){
var unix = Math.round(+new Date()/1000);
firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
if (snapshot.val()){
$.each(objs, function(i, obj) {
$.each(obj, function(i, obk) {
if(obk.photo_expiry){
if (obk.photo_expiry < Number(unix)){
//alert('a photo to delete exists');
firebase.database().ref('/photochats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove();
firebase.database().ref('/chats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove();
var desertRef = storageRef.child(obk.photo_name);
// Delete the file
desertRef.delete().then(function() {
firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove();
}).catch(function(error) {
});
//blocking out
}
}
});
});
}
});
}
function createDuck(idq,nameq,redirect){
keepopen = 1;
d_type = 'duck';
if (idq) {createDate(idq,nameq,redirect)}
else{createDate();}
}
function createDate1(idz,name,redirect){
d_type = 'date';
keepopen = 1;
if (idz) {createDate(idz,name,redirect)}
else{createDate();}
}
function duckClass(place){
if (place ==1) {
if ($( ".button-my" ).hasClass( "active" )){
$('.button-my').removeClass("active");$('.button-your').removeClass("active");
}
else {$('.button-my').addClass("active");$('.button-your').removeClass("active");}
}
if (place ==2) {
if ($( ".button-your" ).hasClass( "active" )){
$('.button-your').removeClass("active");$('.button-my').removeClass("active");
}
else {$('.button-your').addClass("active");$('.button-my').removeClass("active");}
}
}
function matchNotif(){
function newNotificationm(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'New match'}
if (d_type=='date'){smessage = 'New match'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'newmatch',
new_message_count:0,
received:'N',
expire:'',
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
//console.log('delete notification sent');
});
}
sendNotification(targetid,1);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq = 0;
//If existing notifications, get number of unseen messages, delete old notifications
//console.log(snapshot.val());
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newNotificationm(messageq);
});
}
function unmatchNotif(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref('dates/' + f_uid +'/' + targetid).remove();
firebase.database().ref('dates/' + targetid +'/' + f_uid).remove();
firebase.database().ref('notifications/' + f_uid +'/' + targetid).remove();
firebase.database().ref('notifications/' + targetid +'/' + f_uid).remove();
myApp.closePanel();
}
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
function insertAfterNthChild($parent, index, content){
$(content).insertBefore($parent.children().eq(index));
}
//function changeRadius(number){
//$('.radiusbutton').removeClass('active');
//$('#distance_'+ number).addClass('active');
//processUpdate();
//}
function sortBy(number){
var relevanticon;
var relevanttext;
//if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$('.sortbutton').removeClass('active');
$('.sortby_'+ number).addClass('active');
if ($( "#sortrandom" ).hasClass( "active" )){sortby = 'random';}
if ($( "#sortdistance" ).hasClass( "active" )){sortby = 'distance';}
if ($( "#sortactivity" ).hasClass( "active" )){sortby = 'activity';}
firebase.database().ref('users/' + f_uid).update({
sort:sortby
});
}
function addcreateDate(){
$('.left-title').text(f_duck_match_data.length + 'want to date you');
myApp.sizeNavbars();
$('.timeline-upcoming').empty();
for (i = 0; i < f_date_match_data.length; i++) {
$('.timeline-upcoming').append('<div class="timeline-item" onclick="createDate1(\''+f_date_match_data[i].uid+'\',\''+f_date_match_data[i].name+'\');">'+
'<div class="timeline-item-date">'+fdateicon+'</div>'+
'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content">'+
' <div class="timeline-item-inner">'+
' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_date_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="timeline-item-subtitle">'+f_date_match_data[i].name+'</div>'+
'</div>'+
' </div>'+
'</div>');
}
for (i = 0; i < f_duck_match_data.length; i++) {
$('.timeline-upcoming').append('<div class="timeline-item" onclick="createDuck(\''+f_duck_match_data[i].uid+'\',\''+f_duck_match_data[i].name+'\');">'+
'<div class="timeline-item-date">'+fduckicon+'</div>'+
'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content">'+
' <div class="timeline-item-inner">'+
' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_duck_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="timeline-item-subtitle">'+f_duck_match_data[i].name+'</div>'+
'</div>'+
' </div>'+
'</div>');
}
if (f_duck_match_data.length === 0 && f_date_match_data.length ===0){
$('.timeline-upcoming').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;overflow:visible;">No matches yet. <br/><br/>Keep calm and quack on!</div>');
}
}
function unblock(){
myApp.confirm('This will unblock all profiles, making you visible to everyone', 'Are you sure?', function () {
var iblockedfirst = [];
var iblockedsecond = [];
firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) {
if (snapshot.val() != null){
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if((obj.first_number == f_uid)&& (obj.firstnumberblock == 'Y')){iblockedfirst.push(obj.second_number)}
if((obj.second_number == f_uid)&& (obj.secondnumberblock == 'Y')){iblockedsecond.push(obj.first_number)}
});
}
if (iblockedfirst.length){
for (i = 0; i < iblockedfirst.length; i++) {
firebase.database().ref('matches/' + f_uid + '/' + iblockedfirst[i]).update({
//add this user to my list
firstnumberblock:'N',
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:iblockedfirst[i]
});
firebase.database().ref('matches/' + iblockedfirst[i] + '/' + f_uid).update({
//add this user to my list
firstnumberblock:'N',
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:iblockedfirst[i]
});
}
}
if (iblockedsecond.length){
for (i = 0; i < iblockedsecond.length; i++) {
firebase.database().ref('matches/' + f_uid + '/' + iblockedsecond[i]).update({
//add this user to my list
secondnumberblock:'N',
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:iblockedsecond[i]
});
firebase.database().ref('matches/' + iblockedsecond[i] + '/' + f_uid).update({
//add this user to my list
secondnumberblock:'N',
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:iblockedsecond[i]
});
}
}
getWifilocation();
$( ".blockbutton" ).addClass('disabled');
})
});
}
function deleteAccount(){
//users
//photos2delete -> photos in storage
//chats
//matches
myApp.confirm('This will permanently delete your account and remove all your information including photos, chats and profile data', 'Delete Account', function () {
var matchesarray = [];
var firstnumberarray = [];
var secondnumberarray = [];
firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) {
if (snapshot.val() != null){
var objs = snapshot.val();
$.each(objs, function(i, obj) {var uidadd;if(obj.first_number == f_uid){uidadd = obj.second_number;} else{uidadd = obj.first_number} matchesarray.push(uidadd); firstnumberarray.push(obj.first_number);secondnumberarray.push(obj.second_number);});
for (i = 0; i < matchesarray.length; i++) {
var mymatches = firebase.database().ref('matches/' + f_uid + '/' + matchesarray[i]);
mymatches.remove().then(function() {
//console.log("My matches Remove succeeded.")
})
.catch(function(error) {
//console.log("My matches Remove failed: " + error.message)
});
var theirmatches = firebase.database().ref('matches/' + matchesarray[i] + '/' + f_uid);
theirmatches.remove().then(function() {
//console.log("Their matches Remove succeeded.")
})
.catch(function(error) {
//console.log("Their matches Remove failed: " + error.message)
});
var mydates = firebase.database().ref('dates/' + f_uid + '/' + matchesarray[i]);
mydates.remove().then(function() {
//console.log("My dates Remove succeeded.")
})
.catch(function(error) {
//console.log("My dates Remove failed: " + error.message)
});
var theirdates = firebase.database().ref('dates/' + matchesarray[i] + '/' + f_uid);
theirdates.remove().then(function() {
//console.log("Their dates Remove succeeded.")
})
.catch(function(error) {
//console.log("Their dates Remove failed: " + error.message)
});
var theirnotifs = firebase.database().ref('notifications/' + matchesarray[i] + '/' + f_uid);
theirnotifs.remove().then(function() {
//console.log("their notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("their notifs failed: " + error.message)
});
var ourchats = firebase.database().ref('chats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
ourchats.remove().then(function() {
//console.log("Chats Remove succeeded.")
})
.catch(function(error) {
//console.log("Chats Remove failed: " + error.message)
});
var ourphotochats = firebase.database().ref('photochats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
ourphotochats.remove().then(function() {
//console.log("PhotoChats Remove succeeded.")
})
.catch(function(error) {
//console.log("PhotoChats Remove failed: " + error.message)
});
}
}
firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
var objs = snapshot.val();
//console.log(objs);
if (snapshot.val()){
$.each(objs, function(i, obj) {
var targetdeleteid;
if (obj.from_uid == f_uid){targetdeleteid = obj.to_uid} else{targetdeleteid = obj.from_uid;}
var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetdeleteid);
mynotifs.remove().then(function() {
//console.log("my notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("my notifs failed: " + error.message)
});
});
}
firebase.database().ref('users/' + f_uid).set({
auth_id : f_auth_id,
deleted:'Y'
});
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/deleteuser.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
//console.log(data);
firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
var objr = snapshot.val();
if (snapshot.val()){
$.each(objr, function(i, obj) {
$.each(obj, function(i, obk) {
firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove();
var desertRef = storageRef.child(obk.photo_name);
// Delete the file
desertRef.delete().then(function() {
}).catch(function(error) {
//console.log(error);
});
});
});
}
FCMPlugin.unsubscribeFromTopic(f_uid);
cordova.plugins.notification.badge.set(0);
var loginmethod = window.localStorage.getItem("loginmethod");
if (loginmethod == '1'){logoutPlugin();}
else{logoutOpen();}
});
});
}).catch(function(error) {
// Handle error
});
});
});
});
}
function matchNavbar(){
if ($('.infopopup').length > 0) {
$( ".toolbarq" ).show();
$( ".photobrowserbar" ).css("background-color","#2196f3");
$( ".matchcolor" ).addClass('whitetext');
}
else {$( ".toolbarq" ).hide();}
}
function unmatchNavbar(){
if ($('.infopopup').length > 0) {
$( ".toolbarq" ).show();
$( ".photobrowserbar" ).css("background-color","#ccc");
$( ".matchcolor" ).removeClass('whitetext');
$( ".toolbarq" ).css("background-color","transparent");
}
else {$( ".toolbarq" ).hide();}
}
var notifloaded = false;
function establishNotif(){
if(notifcount) {firebase.database().ref('notifications/' + f_uid).off('value', notifcount);}
notifcount = firebase.database().ref('notifications/' +f_uid).on('value', function(snapshot) {
var notificationscount = 0;
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if (obj.to_uid == f_uid) {
if (obj.received =='Y') {
if (notifloaded){ $( ".arrowdivhome_" + obj.from_uid ).empty();$( ".indivnotifcount" ).remove();}
}
if (obj.received =='N') {
var addnumber;
if(obj.param == 'datedeleted' || obj.param =='newmatch'){addnumber = 1;}
else {addnumber = obj.new_message_count}
notificationscount = notificationscount + addnumber;
if (notifloaded){
if (obj.new_message_count > 0){
//alert('Not received, greater than 0 = ' +obj.new_message_count);
$( ".arrowdivhome_" + obj.from_uid ).empty();$( ".arrowdivhome_" + obj.from_uid ).append('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');
$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');
cordova.plugins.notification.badge.set(notificationscount);
}
}
}
}
});
notifloaded = true;
//Update SQL notifcount
if (notificationscount !=0){
if (offsounds == 'Y'){}else{
$('#buzzer')[0].play();
//if ($('.chatpop').length > 0) {}
//else {$('#buzzer')[0].play();}
}
return false;
}
else{}
//$( ".notifspan" ).empty();
//$( ".notifspan" ).append(notificationscount);
}
});
}
function showPloader(){
$( ".ploader" ).css("z-index","9999999");myApp.closeModal();
}
function hidePloader(tabb){
var popupHTML = '<div class="popup prefpop">'+
'<div class="views tabs toolbar-fixed">'+
'<div id="tab1" class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="center" style="color:white;">Terms and Conditions of Use</div>'+
' <div class="right"><a href="#" onclick="showPloader();" style="color:white;">Done</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="home-1" class="page">'+
' <div class="page-content">'+
'<div class="content-block" style="margin-top:0px;">'+
' <div class="content-block-inner terms-inner" >'+
' </div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div id="tab2" class="view tab">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="center" style="color:white;">Privacy Policy</div>'+
' <div class="right close-popup"><a href="#" onclick="showPloader();" class="close-popup" style="color:white;">Done</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="home-2" class="page">'+
' <div class="page-content">'+
'<div class="content-block" style="margin-top:0px;">'+
' <div class="content-block-inner privacy-inner">'+
' </div>'+
'</div>'+
'</div>'+
' </div>'+
'</div>'+
'</div>'+
'<div class="toolbar tabbar" style="padding:0px;background-color:#ccc;">'+
' <div class="toolbar-inner" style="padding:0px;">'+
' <a href="#tab1" onclick="tabOne();" class="tab1 tab-link active"><i class="pe-7s-note2 pe-lg"></i></a>'+
' <a href="#tab2" onclick="tabTwo();" class="tab2 tab-link"><i class="pe-7s-look pe-lg"></i></a>'+
'</div>'+
'</div>'+
'</div>'+
'</div>';
myApp.popup(popupHTML);
$( ".ploader" ).css("z-index","10000");
if (tabb) {
tabTwo();
}
else {tabOne();}
}
function tabOne(){
$( "#tab1" ).addClass('active');
$( "#tab2" ).removeClass('active');
myApp.sizeNavbars();
$( ".tab1" ).addClass('active');
$( ".tab2" ).removeClass('active');
$.get( "http://www.dateorduck.com/terms.html", function( data ) {
$( ".terms-inner" ).html(data);
});
}
function tabTwo(){
$( "#tab1" ).removeClass('active');
$( "#tab2" ).addClass('active');
myApp.sizeNavbars();
$( ".tab1" ).removeClass('active');
$( ".tab2" ).addClass('active');
$.get( "http://www.dateorduck.com/privacy.html", function( data ) {
$( ".privacy-inner" ).html(data);
});
}
//check if on mobile
//}
var pagingalbumurl;
var pagingurl;
var photonumber;
var albumend;
var addedsmallarray;
var addedlargearray;
var addedheight = [];
var addedwidth = [];
function getPhotos(albumid){
$( ".photoloader").show();
$( ".loadmorebuttonphotos").hide();
var retrieveurl;
if (!pagingurl) {photonumber = 0;retrieveurl = 'https://graph.facebook.com/v2.4/'+albumid+'/photos?limit=8&fields=id,source,width,height&access_token=' + f_token}
else {retrieveurl = pagingurl}
$.getJSON(retrieveurl,
function(response) {
$( ".swipebuttondone").addClass("disabled");
$( ".photoloader").hide();
if (response.data.length === 0){$( ".loadmorebuttonphotos").hide();$( "#nophotosfound").show();return false;}
//console.log(response);
pagingurl = response.paging.next;
for (i = 0; i < response.data.length; i++) {
var alreadyselected = addedsmallarray.indexOf(response.data[i].source);
//console.log(response.data[i]);
if (alreadyselected == -1) {
swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+'" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:none;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"><br></div>');
}
else {
swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+' slidee-selected" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:block;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"></div>');
}
photonumber ++;
}
if (response.data.length > 0 && response.data.length < 8) {
$( ".loadmorebuttonphotos").hide();$( "#nomorephotos").show();}
else{$( ".loadmorebuttonphotos").show();}
});
}
function closePhotos(){
$( ".albumblock").show();
$( ".leftalbum").show();
$( ".leftphoto").hide();
$( "#nomorephotos").hide();
$( "#nophotosfound").hide();
$( ".loadmorebuttonphotos").hide();
if (albumend === true){$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();}
else {$( ".loadmorebuttonalbums").show();$( "#nomorealbums").hide();}
swiperPhotos.removeAllSlides();
swiperPhotos.destroy();
photonumber = 0;
pagingurl = false;
}
function closeAlbums(){
myApp.closeModal('.photopopup');
addedsmallarray = [];
addedlargearray = [];
pagingalbumurl = false;
albumend = false;
$( ".swipebuttondone").removeClass("disabled");
}
function photosPopup(){
photosliderupdated = false;
addedsmallarray = f_smallurls;
addedlargearray = f_largeurls;
var popupHTML = '<div class="popup photopopup">'+
'<div class="views tabs toolbar-fixed">'+
'<div class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<i class="pe-7s-angle-left pe-3x leftalbum" onclick="closeAlbums()" style="margin-left:-10px;"></i>'+
'<i class="pe-7s-angle-left pe-3x leftphoto" onclick="closePhotos()" style="display:none;margin-left:-10px;"></i>'+
' </div>'+
' <div class="center photocount">'+
'0 photos selected'+
'</div>'+
' <div class="right"><a href="#" onclick="closeAlbums()" class="noparray" style="color:white;">Done</a><a href="#" class="yesparray" onclick="getPhotoURL()" style="display:none;color:white;">Save</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="photospage" class="page">'+
' <div class="page-content" style="padding-bottom:0px;background-color:white;">'+
'<div class="col-25 photoloader" style="position:absolute;top:50%;left:50%;margin-left:-13.5px;margin-top:-13.5px;">'+
' <span class="preloader"></span>'+
' </div>'+
'<div class="list-block media-list albumblock" style="margin:0px;z-index:999999;"><ul class="albumul" style="z-index:99999999999;"></ul></div>'+
'<div class="swiper-container swiper-photos">'+
' <div class="swiper-wrapper" >'+
'</div>'+
'</div>'+
'<a href="#" class="button loadmorebuttonalbums" onclick="loadAlbums()" style="font-size:17px;border:0;border-radius:0px;background-color:#2196f3;color:white;display:none;margin:10px;">Load more albums</a>'+
'<a href="#" class="button loadmorebuttonphotos" onclick="getPhotos()" style="font-size:17px;border:0;border-radius:0px;background-color:#2196f3;color:white;display:none;margin:10px;">Load more photos</a>'+
'<div id="nomorephotos" style="display:none;width:100%;text-align:center;"><p>No more photos available in this album.</p></div>'+
'<div id="nophotosfound" style="display:none;width:100%;text-align:center;"><p>No photos found in this album.</p></div>'+
'<div id="nomorealbums" style="display:none;width:100%;text-align:center;"><p>No more albums to load.</p></div>'+
'<div><div><div>'+
'<div>'+
'<div>'+
'</div>'
myApp.popup(popupHTML);
if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');}
else {$( ".photocount").text(addedlargearray.length + ' photos selected');}
photoPermissions();
}
function loadAlbums(){
$( ".photoloader").show();
$( ".loadmorebuttonalbums").hide();
var retrievealbumurl;
if (!pagingalbumurl) {retrievealbumurl = 'https://graph.facebook.com/v2.8/'+f_uid+'/albums?limit=20&fields=id,count,name&access_token=' + f_token}
else {retrievealbumurl = pagingalbumurl}
$.getJSON(retrievealbumurl,
function(response) {
if(response.data.length == 0){
myApp.alert('Upload photos to Facebook to make them available to use in this app.', 'No photos are available');myApp.closeModal('.photopopup');return false;
}
pagingalbumurl = response.paging.next;
if (response.data.length > 0){
for (i = 0; i < response.data.length; i++) {
$( ".albumul" ).append(
' <li onclick="getAlbum('+response.data[i].id+')">'+
' <div class="item-content">'+
' <div class="item-media">'+
' <i class="pe-7s-photo-gallery pe-lg"></i>'+
'</div>'+
'<div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">'+response.data[i].name+'</div>'+
' <div class="item-after">'+response.data[i].count+'</div>'+
'</div>'+
'</div>'+
' </div>'+
' </li>'
);
}
}
if (response.data.length < 20) {$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();$( ".photoloader").hide();albumend = true;}
else{$( ".loadmorebuttonalbums").show();}
});
}
function getAlbum(albumid){
$( ".albumblock").hide();
$( ".loadmorebuttonalbums").hide();
$( "#nomorealbums").hide();
$( ".leftalbum").hide();
$( ".leftphoto").show();
swiperPhotos = myApp.swiper('.swiper-photos', {
slidesPerView:2,
slidesPerColumn:1000,
virtualTranslate:true,
slidesPerColumnFill:'row',
spaceBetween: 3,
onClick:function(swiper, event){if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$( ".noparray").hide();
$( ".yesparray").show();
if ($( ".slidee_" + swiper.clickedIndex).hasClass('slidee-selected')){$( ".slidee_" + swiper.clickedIndex).removeClass('slidee-selected');$( ".close_" + swiper.clickedIndex).show();$( ".check_" + swiper.clickedIndex).hide();
var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", "");
var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", "");
var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", "");
var indexdeletedsm = addedsmallarray.indexOf(smallurl);
addedsmallarray.splice(indexdeletedsm, 1);
var indexdeletedsl = addedlargearray.indexOf(smallurl);
addedlargearray.splice(indexdeletedsl, 1);
addedheight.splice(indexdeletedsl, 1);
addedwidth.splice(indexdeletedsl, 1);
//console.log(addedheight);
}
else{$( ".slidee_" + swiper.clickedIndex).addClass('slidee-selected');$( ".close_" + swiper.clickedIndex).hide();$( ".check_" + swiper.clickedIndex).show();
var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", "");
var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", "");
var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", "");
addedsmallarray.push(smallurl);
addedlargearray.push(largeurl);
var widthselected = $( ".width_"+photoselectedid).val();
var heightselected = $( ".height_"+photoselectedid).val();
addedheight.push(heightselected);
addedwidth.push(widthselected);
}
if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');}
else {$( ".photocount").text(addedlargearray.length + ' photos selected');}
}
});
getPhotos(albumid);
swiperPhotos.updateContainerSize();
swiperPhotos.updateSlidesSize();
}
function getPhotoURL(){
photonumber = 0;
pagingurl = false;
pagingalbumurl = false;
albumend = false;
var newsmall = addedsmallarray.toString();
var newlarge = addedlargearray.toString();
var newwidth = addedwidth.toString();
var newheight = addedheight.toString();
firebase.database().ref('users/' + f_uid).update({
image_url:addedlargearray[0],
photoresponse:'Y'
}).then(function() {});
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
$( ".swipebuttondone").removeClass("disabled");
if (addedlargearray.length ===0){if ($( ".reorderbutton" ).hasClass( "disabled" )){}else {$( ".reorderbutton" ).addClass('disabled');}
if ($( ".deleteallbutton" ).hasClass( "disabled" )){}else {$( ".deleteallbutton" ).addClass('disabled');}
}
if (addedlargearray.length > 0){if ($( ".reorderbutton" ).hasClass( "disabled" )){$( ".reorderbutton" ).removeClass('disabled');}
if ($( ".deleteallbutton" ).hasClass( "disabled" )){$( ".deleteallbutton" ).removeClass('disabled');}
}
updatephotoslider();
//swiperPhotos.removeAllSlides();
//swiperPhotos.destroy();
myApp.closeModal('.photopopup');
});
}).catch(function(error) {
// Handle error
});
}
var photosliderupdated;
function updatephotoslider(){
$( ".yesparray").addClass("disabled");
if (photosliderupdated){return false;}
photosliderupdated = true;
myswiperphotos.removeAllSlides();
if (addedlargearray.length > 0){
myswiperphotos.removeAllSlides();
for (i = 0; i < addedlargearray.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+addedlargearray[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()">Remove</div></div>');
}
myswiperphotos.update();
$( ".photosliderinfo" ).addClass('pictures');
if (addedlargearray.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
addedsmallarray = [];
addedlargearray = [];
}
else {
myswiperphotos.removeAllSlides();
f_smallurls = [];
f_largeurls = [];
addedheight = [];
addedwidth = [];
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
}
}
function reorderPhotos(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
var popupHTML = '<div class="popup redorderpopup">'+
'<div class="views tabs toolbar-fixed">'+
'<div class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<i class="pe-7s-angle-left pe-3x leftalbum" style="margin-left:-10px;" onclick="closeReorder()"></i>'+
' </div>'+
' <div class="center">'+
'Order Photos'+
'</div>'+
' <div class="right"><a href="#" onclick="changeOrder()" style="color:white;">Save</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="redorderpage" class="page">'+
' <div class="page-content" style="background-color:white;padding-bottom:0px;">'+
'<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;;padding-top:10px;padding-bottom:10px;">Drag photos to re-order</p>'+
' <div class="list-block media-list" style="width:25%;float:left;margin-top:0px;">'+
' <ul class="numbersul" style="background-color:transparent;">'+
' </ul>'+
'</div>'+
' <div class="list-block sortable" style="width:75%;float:left;margin-top:0px;">'+
' <ul class="sortableul">'+
' </ul>'+
'</div>'+
'<div><div><div>'+
'<div>'+
'<div>'+
'</div>'
myApp.popup(popupHTML);
for (i = 0; i < f_largeurls.length; i++) {
$( ".numbersul" ).append(
'<li style="margin-top:10px;">'+
' <div class="item-content" style="height:80px;">'+
'<div class="item-inner reorderinner">'+
' <div class="item-title badge" style="position:absolute;top:50%;left:50%;margin-top:-10px;margin-left:-20px;">'+i+'</div>'+
'</div>'+
' </div>'+
'</li>'
);
$( ".sortableul" ).append(
' <li style="margin-top:10px;">'+
' <div class="item-content sortdivb" data-width="'+addedwidth[i]+'" data-height="'+addedheight[i]+'" style="background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;height:80px;">'+
' </div>'+
' <div class="sortable-handler" style="width:100%;height:80px;"></div>'+
' </li>'
);
}
myApp.sortableOpen();
}
function closeReorder(){
myApp.closeModal('.redorderpopup');
}
function changeOrder(){
var newurl = [];
var newwidthchange = [];
var newheightchange = [];
$( ".sortdivb" ).each(function() {
var bg = $(this).css("background-image");
var valuewidth = $(this).attr("data-width");
var valueheight = $(this).attr("data-height");
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
newurl.push(bg);
newwidthchange.push(valuewidth);
newheightchange.push(valueheight);
});
myswiperphotos.removeAllSlides();
for (i = 0; i < newurl.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+newurl[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()"><i class="pe-7s-trash pe-lg"></i> Remove</div></div>');
}
myApp.closeModal('.redorderpopup');
myswiperphotos.update();
$( ".photosliderinfo" ).addClass('pictures');
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
var newsmall = newurl.toString();
var newlarge = newurl.toString();
var newwidth = newheightchange.toString();
var newheight = newheightchange.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
});
}).catch(function(error) {
// Handle error
});
f_largeurls = newurl;
firebase.database().ref('users/' + f_uid).update({
image_url:f_largeurls[0],
photoresponse:'Y'
}).then(function() {});
}
function deleteAllPhotos(){
myApp.confirm('Are you sure?', 'Remove all photos', function () {
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
deletedphoto = false;
myswiperphotos.removeAllSlides();
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos.update();
$( ".reorderbutton" ).addClass('disabled');
$( ".deleteallbutton" ).addClass('disabled');
f_largeurls = [];
f_smallurls = [];
var newsmall = "";
var newlarge = "";
var newwidth = "";
var newheight = "";
firebase.database().ref('users/' + f_uid).update({
image_url:f_image,
photoresponse:'Y'
}).then(function() {});
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
//console.log('deleted all');
});
}).catch(function(error) {
// Handle error
});
});
}
var f_smallurls = [];
var f_largeurls = [];
var photosloaded;
function swipePopup(chosen){
$( '.picker-sub' ).hide();
myApp.closeModal('.picker-sub');
photosloaded = false;
var sliderwidth = $( document ).width();
var sliderheight = $( document ).height();
var popupHTML = '<div class="popup prefpop" style="z-index:11000">'+
'<div class="views tabs toolbar-fixed">'+
'<div id="tab99" class="view-99 view tab active">'+
//
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="left" style="color:white;"></div>'+
' <div class="center swipetext" style="color:white;">Availability'+
//'<div style="width:70px;height:70px;border-radius:50%;background-image:url(\''+f_image+'\');background-size:cover;background-position:50% 50%;margin-top:30px;z-index:100;border:5px solid #2196f3"></div>'+
'</div>'+
' <div class="right"><a href="#" onclick="updateUser();" style="color:white;display:none" class="donechange swipebuttondone">Done</a><a href="#" style="color:white;display:none;" class="close-popup doneunchange swipebuttondone">Done</a></div>'+
'</div>'+
'</div>'+
' <div class="pages">'+
' <div data-page="home-3" class="page">'+
'<div class="toolbar tabbar swipetoolbar" style="background-color:#ccc;z-index:9999999999;position:absolute;bottom:0px;">'+
' <div class="toolbar-inner" style="padding:0;">'+
// ' <a href="#" class="button tab-link tab-swipe pan0 active" onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-filter pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan0 " onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan1" onclick="swipePref(1)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan2" onclick="swipePref(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan3" onclick="swipePref(3)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
'</div>'+
'</div>'+
' <div class="page-content" style="height: calc(100% - 44px);background-color:white;">'+
'<div class="swiper-container swiper-prefer" style="padding-top:54px;margin-bottom:-44px;">'+
'<div class="swiper-wrapper">'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-0">'+
'<div class="list-block media-list availblock" style="margin-bottom:0px;margin-top:0px;">'+
' <ul class="availul" style="padding-left:10px;padding-right:10px;padding-bottom:20px;">'+
' </ul>'+
'<div class="list-block-label hiderowpref" style="margin-top:10px;">Make it easier for your matches to organise a time to meet you.</div>'+
'</div> '+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-1">'+
'<div style="background-color:transparent;width:100%;padding-bottom:10px;" class="registerdiv">'+
'<div style="border-radius:50%;width:70px;height:70px;margin:0 auto;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
'</div>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul class="aboutul">'+
'<div class="list-block-label registerdiv" style="margin-top:10px;margin-bottom:10px;">To get started, tell us about you and who you are looking to meet. </div>'+
'<li class="newam" style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label">I am</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="picker-describe">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li class="newme">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label">Preference</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="picker-describe2">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li class="align-top hiderowpref">'+
' <div class="item-content">'+
//'<div class="item-media" style="border-radius:50%;width:70px;height:70px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="item-inner">'+
'<div class="item-title label">About Me</div>'+
' <div class="item-input">'+
' <textarea class="resizable" onkeyup="keyUp()" maxlength="100" id="userdescription" style="width: calc(100% - 40px);min-height:88px;max-height:176px;" placeholder="Hide"></textarea>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'<p id="maxdescription" class="hiderowpref" style="float:right;color:#ccc;font-size:12px;margin-top:-20px;margin-right:5px;margin-bottom:-5px;">0 / 100</p>'+
' <li class="hiderowpref hometownli" style="clear:both;margin-top:0px;">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Hometown</div>'+
' <div class="item-input hometown-input">'+
' <textarea class="resizable" id="homesearch" onclick="newHometown()" onblur="checkHometown()" placeholder="Hide" style="min-height:60px;max-height:132px;"></textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Status</div>'+
' <div class="item-input status-div">'+
' <input type="text" placeholder="Hide" id="status-input" name="name" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Industry</div>'+
' <div class="item-input industry-div">'+
' <input type="text" id="industry-input" name="name" placeholder="Hide" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Zodiac</div>'+
' <div class="item-input zodiac-div">'+
' <input type="text" id="zodiac-input" name="name" placeholder="Hide" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Politics</div>'+
' <div class="item-input politics-div">'+
' <input type="text" id="politics-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Religion</div>'+
' <div class="item-input religion-div">'+
' <input type="text" id="religion-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Ethnicity</div>'+
' <div class="item-input ethnicity-div">'+
' <input type="text" id="ethnicity-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Eye color</div>'+
' <div class="item-input eyes-div">'+
' <input type="text" id="eyes-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Body Type</div>'+
' <div class="item-input body-div">'+
' <input type="text" id="body-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Height</div>'+
' <div class="item-input height-div">'+
' <input type="text" id="height-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Weight</div>'+
' <div class="item-input weight-div">'+
' <input type="text" id="weight-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'</ul>'+
'<div class="list-block-label hiderowpref" style="margin-bottom:0px;">All fields are optional and will be hidden on your profile unless completed.</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-2">'+
'<div class="col-25 photoswiperloader" style="width:57.37px;top:50%;margin-top: -28.7px;top:50%;position: absolute;left: 50%;margin-left: -28.7px;">'+
' <span class="preloader"></span>'+
' </div>'+
'<div class="swiper-container container-photos" style="width:'+sliderwidth+'px;height:250px;">'+
'<div class="swiper-wrapper wrapper-photos">'+
'</div>'+
'<div class="swiper-pagination"></div>'+
'</div>'+
'<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;padding-top:10px;padding-bottom:10px;" class="photosliderinfo"></p>'+
' <div class="buttons-row">'+
'<a href="#" class="button active" onclick="photosPopup();" style="font-size:17px;border:0;border-radius:0px;background-color:#4cd964;margin-left:5px;margin-right:5px;">Edit</a>'+
'<a href="#" class="button reorderbutton active disabled" onclick="reorderPhotos();" style="font-size:17px;border:0;border-radius:0px;margin-right:5px;">Re-order</a>'+
'<a href="#" class="button deleteallbutton active disabled" onclick="deleteAllPhotos();" style="font-size:17px;border:0;border-radius:0px;margin-right:5px;background-color:#ff3b30;color:white">Clear</a>'+
'</div>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul">'+
'<div class="list-block-label hiderowpref" style="margin-bottom:0px;">Photos can be uploaded from your Facebook account.</div>'+
'</ul></div>'+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-3">'+
'<div class="content-block-title" style="margin-top:20px;">Search options</div>'+
// '<p class="buttons-row" style="padding-left:10px;padding-right:10px;">'+
// '<a href="#" id="distance_10" onclick="changeRadius(10)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">10 km</a>'+
// '<a href="#" id="distance_25" onclick="changeRadius(25)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">25 km</a>'+
// '<a href="#" id="distance_50" onclick="changeRadius(50)" class="button button-round radiusbutton active" style="border:0;border-radius:0px;">50 km</a>'+
// '<a href="#" id="distance_100" onclick="changeRadius(100)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">100 km</a>'+
//'</p>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul>'+
'<li style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label" style="width:120px;">Search radius</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="distance-input">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label" style="width:120px;"></div>'+
' <div class="item-input">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>'+
'<div class="content-block-title" style="margin-top:-54px;">Sounds</div>'+
' <div class="list-block media-list">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-inner" style="float:left;">'+
'<div class="item-title label" style="width:calc(100% - 62px);float:left;font-size:17px;font-weight:normal;">Turn off sounds</div>'+
' <div class="item-input" style="width:52px;float:left;">'+
'<label class="label-switch">'+
' <input type="checkbox" id="soundnotif" onchange="processUpdate(); myApp.sizeNavbars();">'+
'<div class="checkbox" ></div>'+
' </label>'+
' </div>'+
' </div>'+
' </div>'+
'</li>'+
'<div class="content-block-title" style="margin-top:20px;">Blocked profiles</div>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title button blockbutton active disabled" onclick="unblock()" style="font-size:17px;border:0;border-radius:0px;">Unblock all </div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'<div class="content-block-title" style="margin-top:20px;">My Account</div>'+
'<li onclick="logout()">'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title active button" style="border:0;border-radius:0px;font-size:17px;">Logout</div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
' <li onclick="deleteAccount()">'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title button" style="font-size:17px;border-color:#ff3b30;background-color:#ff3b30;color:white;border:0;border-radius:0px;">Delete Account</div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'</ul>'+
'</div> '+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
' </div>'+
'</div>'+
'</div>'+
//tabs
'</div>'+
'</div>'+
//tabs
'</div>';
myApp.popup(popupHTML);
if (blocklist){
if (blocklist.length){$( ".blockbutton" ).removeClass('disabled');}
}
if(sexuality){$( ".doneunchange" ).show();$( ".registerdiv" ).hide();$('.hiderowpref').removeClass('hiderowpref');}
if(!sexuality){
$( ".swipetoolbar" ).hide();
}
//if (radiussize) {distancepicker.cols[0].setValue(radiussize);}
distancepicker = myApp.picker({
input: '#distance-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + ($( document ).width()/2) + "px");distancepicker.cols[0].setValue(radiussize);distancepicker.cols[1].setValue(radiusunit);if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onClose:function (p, values, displayValues){radiussize = distancepicker.value[0];
radiusunit = distancepicker.value[1];},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'Search Distance'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100').split(' ')
},
{
textAlign: 'left',
values: ('Kilometres Miles').split(' ')
},
]
});
var industrypicker = myApp.picker({
input: '#industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
var findustrypicker = myApp.picker({
input: '#f-industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (f_industry_u) {findustrypicker.cols[0].setValue(f_industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onChange:function (p, values, displayValues){$( '#f-industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'f_industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
var statuspicker = myApp.picker({
input: '#status-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'status\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated']
}
]
});
var heightpicker = myApp.picker({
input: '#height-input',
onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");},
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
heightpicker.cols[0].setValue(heightset);}},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'height\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')']
},
]
});
var weightpicker = myApp.picker({
input: '#weight-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (weight_u) {
weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}},
onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'weight\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="center">' +
'Weight'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: (function () {
var arr = [];
for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); }
return arr;
})(),
},
]
});
var bodypicker = myApp.picker({
input: '#body-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (body_u) {bodypicker.cols[0].setValue(body_u);}},
onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'body\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant']
}
]
});
var eyespicker = myApp.picker({
input: '#eyes-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}},
onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'eyes\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other']
}
]
});
var ethnicitypicker = myApp.picker({
input: '#ethnicity-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}},
onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'ethnicity\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White']
}
]
});
var politicspicker = myApp.picker({
input: '#politics-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (politics_u) {politicspicker.cols[0].setValue(politics_u);}},
onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'politics\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested']
}
]
});
var zodiacpicker = myApp.picker({
input: '#zodiac-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}},
onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'zodiac\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces']
}
]
});
var religionpicker = myApp.picker({
input: '#religion-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (religion_u) {religionpicker.cols[0].setValue(religion_u);}},
onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'religion\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other']
}
]
});
$( ".slide-pref" ).hide();
mySwiper = myApp.swiper('.swiper-prefer', {
onSlideChangeEnd:function(swiper){$( ".page-content" ).scrollTop( 0 );},
onInit:function(swiper){$( ".swipetoolbar" ).show();$( ".pan" + swiper.activeIndex ).addClass('active');},
onSlideChangeStart:function(swiper){
$( ".page-content" ).scrollTop( 0 );
$( ".tab-swipe").removeClass('active');
$( ".pan" + swiper.activeIndex ).addClass('active');
if (swiper.activeIndex == 0){$( ".swipetext" ).text('Availability');
$( ".slide-pref" ).hide();$( ".pref-0").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 1){$( ".swipetext" ).text('Profile');
$( ".slide-pref" ).hide();$( ".pref-1").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 2){$( ".swipetext" ).text('Photos');getData();
$( ".slide-pref" ).hide();$( ".pref-2").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 3){$( ".swipetext" ).text('Settings');
$( ".slide-pref" ).hide();$( ".pref-3").show();$( ".swipetoolbar" ).show();
}
if (!sexuality){$( '.swipetext' ).text("Welcome, " + f_first);mySwiper.lockSwipes();}
}
});
swipePref(chosen);
setTimeout(function(){ $( ".swipetoolbar" ).show(); }, 3000);
myApp.sizeNavbars();
var dateinfo = [];
var s_namesonly = [];
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var daynumber;
var todayday = weekday[d.getDay()];
//console.log(todayday);
s_namesonly.push(todayday);
var f_available_array;
var s_alldays_values = [];
var s_alldays_names = [];
var tonight = new Date();
tonight.setHours(23,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
daynumber;
daynumber = d.getDate();
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
dateinfo.push(daynumber + dending + ' ' + monthNames[d.getMonth()] + ', ' + d.getFullYear());
s_alldays_values.push(tonight_timestamp);
s_alldays_names.push('Today');
var tomorrow_timestamp = tonight_timestamp + 86400;
var tomorrowdate = new Date(Date.now() + 86400);
var tomorroww = new Date(d.getTime() + 24 * 60 * 60 * 1000);
var tomorrowday = weekday[tomorroww.getDay()];
daynumber = tomorroww.getDate();
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
dateinfo.push(daynumber + dending + ' ' + monthNames[tomorrowdate.getMonth()] + ', ' + tomorrowdate.getFullYear());
//console.log('tomorrow is' + tomorrowday);
s_namesonly.push(tomorrowday);
s_alldays_values.push(tomorrow_timestamp);
s_alldays_names.push('Tomorrow');
for (i = 1; i < 7; i++) {
var newunix = tomorrow_timestamp + (86400 * i);
s_alldays_values.push(newunix);
var dat_number = i + 1;
var datz = new Date(Date.now() + dat_number * 24*60*60*1000);
daynumber = datz.getDate();
var dending;
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
n = weekday[datz.getDay()];
qqq = weekday[datz.getDay() - 1];
//console.log(n);
s_alldays_names.push(n + ' ' + daynumber + dending);
dateinfo.push(daynumber + dending + ' ' + monthNames[datz.getMonth()] + ', ' + datz.getFullYear());
s_namesonly.push(n);
}
s_namesonly.push(n);
//console.log(s_namesonly);
//console.log(s_alldays_values);
for (i = 0; i < s_alldays_names.length; i++) {
if (i==0 | i==2 || i==4 || i==6){
$( ".availul" ).append(
'<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+
'<div class="readd_'+s_alldays_values[i]+'"></div>'+
' <input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">'
);
setPicker();
}
else if (i==1 || i==3 || i==5 || i==7) {
$( ".availul" ).append(
'<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+
'<div class="readd_'+s_alldays_values[i]+'"></div>'+
'<input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">'
);
setPicker();
}
var alreadyavailchosen = 0;
var columnone;
var columntwo;
var idtochange;
for(var k = 0; k < availarray.length; k++) {
if (availarray[k].id == s_alldays_values[i]){
alreadyavailchosen = 1;columntwo = availarray[k].time;columnone = availarray[k].day;
idtochange = s_alldays_values[i];$( '.li_'+ idtochange ).addClass('selecrec');$( "#picker"+ idtochange ).val( columnone + " " + columntwo ); }
else{
alreadyavailchosen = 0;
}
}
function setPicker(){
var myavailpicker = myApp.picker({
input: '#picker' + s_alldays_values[i],
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeAvail(\''+s_alldays_values[i]+'\',\''+s_alldays_names[i]+'\',\''+s_namesonly[i]+'\');">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: (s_namesonly[i] + ',').split(',')
},
{
textAlign: 'left',
values: ('Anytime Morning Midday Afternoon Evening').split(' ')
},
]
});
}
}
if (myphotosarray){
}
else {
}
if (f_description){
$( "#userdescription" ).val(f_description);
var inputlengthd = $( "#userdescription" ).val().length;
$( "#maxdescription" ).text(inputlengthd + ' / 100 ');
}
if (radiussize){
$( ".radiusbutton" ).removeClass( "active" );
$( "#distance_" + radiussize ).addClass( "active" );
}
if (offsounds == 'Y'){$('#soundnotif').prop('checked', true);}
else{$('#soundnotif').prop('checked', false);}
if (f_age) {$( ".savebutton" ).removeClass('disabled');}
if (!sexuality){$( "#distance-input" ).val( '100 Kilometres');}
else {$( "#distance-input" ).val( radiussize + ' ' +radiusunit);
}
if(hometown_u){$( "#homesearch" ).val( hometown_u );}
if(industry_u){$( "#industry-input" ).val( industry_u );}
if(status_u){$( "#status-input" ).val( status_u );}
if(politics_u){$( "#politics-input" ).val( politics_u );}
if(eyes_u){$( "#eyes-input" ).val( eyes_u );}
if(body_u){$( "#body-input" ).val( body_u );}
if(religion_u){$( "#religion-input" ).val( religion_u );}
if(zodiac_u){$( "#zodiac-input" ).val( zodiac_u );}
if(ethnicity_u){$( "#ethnicity-input" ).val( ethnicity_u );}
if(weight_u){$( "#weight-input" ).val( weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)' );}
if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
$( "#height-input" ).val( heightset );
}
if (f_age && f_gender) {$( "#picker-describe" ).val( f_gender + ", " + f_age );}
if (f_interested) {$( "#picker-describe2" ).val( f_interested + ", between " + f_lower + ' - ' + f_upper );}
pickerDescribe = myApp.picker({
input: '#picker-describe',
rotateEffect: true,
onClose:function (p){
$( ".popup-overlay" ).css("z-index","10500");
},
onOpen: function (p){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$('.picker-items-col').eq(0).css('width','50%');
$('.picker-items-col').eq(1).css('width','50%');
// $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");
var gendercol = pickerDescribe.cols[0];
var agecol = pickerDescribe.cols[1];
if (f_age) {agecol.setValue(f_age);}
if (f_gender) {gendercol.setValue(f_gender);}
},
onChange: function (p, value, displayValue){
if (!f_age){
var fpick = pickerDescribe.value;
var spick = pickerDescribe2.value;
if (fpick && spick) {
if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); }
$( ".savebutton" ).removeClass( "disabled" );}
else {$( ".savebutton" ).addClass( "disabled" );}
}
},
formatValue: function (p, values, displayValues) {
return displayValues[0] + ', ' + values[1];
}, toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'I Am'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: ('Male Female').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
]
});
pickerDescribe2 = myApp.picker({
input: '#picker-describe2',
rotateEffect: true,
onClose:function (p){
$( ".popup-overlay" ).css("z-index","10500");
},
onChange: function (p, value, displayValue){
if (!f_age){
var fpick = pickerDescribe.value;
var spick = pickerDescribe2.value;
if (fpick && spick) {
if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); }
$( ".savebutton" ).removeClass( "disabled" );}
else {$( ".savebutton" ).addClass( "disabled" );}
}
},
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }
// $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");
$('.picker-items-col').eq(0).css('width','33%');
$('.picker-items-col').eq(1).css('width','33%');
$('.picker-items-col').eq(2).css('width','33%');
var interestedcol = pickerDescribe2.cols[0];
var lowercol = pickerDescribe2.cols[1];
var uppercol = pickerDescribe2.cols[2];
if (f_interested) {interestedcol.setValue(f_interested);}
if (f_lower) {lowercol.setValue(f_lower);}
if (f_upper) {uppercol.setValue(f_upper);}
},
formatValue: function (p, values, displayValues) {
if (values[1] > values[2]) { return displayValues[0] + ', between ' + values[2] + ' - ' + values[1];}
else { return displayValues[0] + ', between ' + values[1] + ' - ' + values[2];
}
}, toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'Preference'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: ('Men Women').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
]
});
}
function swipePref(index){$( ".swipetoolbar" ).show();$( ".pref-" + index).show();mySwiper.slideTo(index); $( ".swipetoolbar" ).show();
}
function navPicker(){
myApp.pickerModal(
'<div class="picker-modal picker-sub" style="height:88px;">' +
'<div class="toolbar tabbar" style="z-index:9999;background-color:#ccc;">' +
'<div class="toolbar-inner" style="padding:0;">' +
' <a href="#" class="button tab-link tab-swipe home1 " onclick="swipePopup(0);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home2" onclick="swipePopup(1);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home3" onclick="swipePopup(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home4" onclick="swipePopup(3);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
'</div>' +
'</div>' +
'<div class="picker-modal-inner close-picker" style="height:44px;background-color:#2196f3;text-align:center;">' +
'<i class="pe-7s-angle-down pe-2x " style="font-size:34px;margin-top:5px;color:white;"></i>'+
'</div>' +
'</div>'
);
}
function removeProfileSet(pickertype){
$( "#" + pickertype + "-input").remove();
$( "." + pickertype + "-div").append( '<input type="text" id="'+pickertype+'-input" name="name" placeholder="Hide" readonly >' );
if (pickertype=='industry'){
var industrypicker = myApp.picker({
input: '#industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);}
},
onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
}
if (pickertype=='status'){
var statuspicker = myApp.picker({
input: '#status-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);}},
onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'status\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated']
}
]
});
}
if (pickertype=='politics'){
var politicspicker = myApp.picker({
input: '#politics-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (politics_u) {politicspicker.cols[0].setValue(politics_u);}},
onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'politics\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested']
}
]
});
}
if (pickertype=='zodiac'){
var zodiacpicker = myApp.picker({
input: '#zodiac-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}},
onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'zodiac\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces']
}
]
});
}
if (pickertype=='religion'){
var religionpicker = myApp.picker({
input: '#religion-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (religion_u) {religionpicker.cols[0].setValue(religion_u);}},
onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'religion\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other']
}
]
});
}
if (pickertype=='ethnicity'){
var ethnicitypicker = myApp.picker({
input: '#ethnicity-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}},
onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'ethnicity\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White']
}
]
});
}
if (pickertype=='height'){
var heightpicker = myApp.picker({
input: '#height-input',
onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");},
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
heightpicker.cols[0].setValue(heightset);}},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'height\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')']
},
]
});
}
if (pickertype=='weight'){
var weightpicker = myApp.picker({
input: '#weight-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (weight_u) {
weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}},
onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'weight\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="center">' +
'Weight'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: (function () {
var arr = [];
for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); }
return arr;
})(),
},
]
});
}
if (pickertype=='eyes'){var eyespicker = myApp.picker({
input: '#eyes-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}},
onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'eyes\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other']
}
]
});
}
if (pickertype=='body'){
var bodypicker = myApp.picker({
input: '#body-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (body_u) {bodypicker.cols[0].setValue(body_u);}},
onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'body\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant']
}
]
});
}
}
function actionSheet(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
if ($('.chatpop').length === 0 || ($('.chatpop').length === 1 && $('.chatpop').css('z-index') === '10000')){
var disabledattribute;
if (targetreported){disabledattribute=true;}else{disabledattribute=false;}
var buttons = [
{
text: 'View Profile',
bold: true,
onClick: function () {
if ($('.infopopup').length > 0) {
scrolltoTop();
}
else{questions();scrolltoTop();}
}
},
{
text: 'View Profile Photos ('+new_all[myPhotoBrowser.swiper.activeIndex].photocount+')',
bold: true,
onClick: function () {
if ($('.infopopup').length > 0) {
myApp.closeModal() ;backtoProfile();
}
else{}
}
},
{
text: 'View Photo Bombs (0)',
disabled:true,
color: 'green',
onClick: function () {
imagesPopup();
}
},
{
text: 'Block',
onClick: function () {
more();
}
},{
text: 'Report',
disabled:disabledattribute,
onClick: function () {
report();
}
},
{
text: 'Cancel',
color: 'red'
},
];
}
else {
var elementPos = new_all.map(function(x) {return x.id; }).indexOf(targetid);
//var elementPos = new_all.findIndex(x => x.id==targetid);
var disabledattribute;
if (targetreported){disabledattribute=true;}else{disabledattribute=false;}
var buttons = [
{
text: 'View Profile',
bold: true,
onClick: function () {
if($( ".center" ).hasClass( "close-popup" )){
myApp.closeModal('.chatpop');
if ($('.infopopup').length > 0) {
scrolltoTop();
}
else{questions();scrolltoTop();}
}else{viewscroll = true;singleUser(targetid,targetname);}
}
},
{
text: 'View Profile Photos ('+new_all[elementPos].photocount+')',
bold: true,
onClick: function () {
if($( ".center" ).hasClass( "close-popup" )){
myApp.closeModal('.chatpop');
backtoProfile();
}else{viewphotos = true;singleUser(targetid,targetname);}
}
},
{ text: 'View Photo Bombs (0)',
disabled:true,
color: 'green',
onClick: function () {
imagesPopup();
}
},
{
text: 'Block',
onClick: function () {
more();
}
},{
text: 'Report',
disabled:disabledattribute,
onClick: function () {
report();
}
},
{
text: 'Cancel',
color: 'red'
},
];
}
myApp.actions(buttons);
var photobombsheet = firebase.database().ref('photochats/' + first_number + '/'+ second_number);
photobombsheet.once('value', function(snapshot) {
if(snapshot.val()){$(".color-green").removeClass('disabled');
$(".color-green").html('View Photo Bombs ('+snapshot.numChildren()+')');
}
});
}
function triggerCam(){
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
//$('#takePictureField_').trigger('click');
}
|
www/js/app.js
|
var refreshIntervalId;
var desktoparray = ['media/dateicon.png','media/duckicon.png','media/datetongue.png','media/dateorducklogo.png']
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function sendNotification(targetto,param){
firebase.auth().currentUser.getToken().then(function(idToken) {
var titlestring;
var bodystring;
if (param == 1){titlestring = 'New match created';bodystring='With ' + f_first;}
if (param == 2){titlestring = 'New date request received';bodystring='From ' + f_first;}
if (param == 3){titlestring = 'New date confirmed';bodystring='By ' + f_first;}
if (param == 4){titlestring = 'New message received';bodystring='From ' + f_first;}
if (param == 5){titlestring = 'New photo received';bodystring='From ' + f_first;}
if (param == 6){titlestring = 'Date cancelled';bodystring='With ' + f_first;}
var typesend;
if (d_type){typesend = d_type;}
else {typesend = 'date';}
$.post( "http://www.dateorduck.com/sendnotification.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,target:targetto,titlestring:titlestring,bodystring:bodystring,param:param,type:typesend,firstname:f_first,senderid:f_uid} )
.done(function( data ) {
//alert(JSON.stringify(data));
});
});
}
function sharePop(){
facebookConnectPlugin.showDialog({
method: "share",
href: "http://www.dateorduck.com/",
hashtag: "#dateorduck"
//share_feedWeb: true, // iOS only
}, function (response) {}, function (response) {})
}
function appLink(){
facebookConnectPlugin.appInvite(
{
url: "https://fb.me/1554148374659639",
picture: "https://scontent-syd2-1.xx.fbcdn.net/v/t1.0-9/20708231_1724210881205783_3080280387189012101_n.png?oh=105b6d85f2f4bb0e33f3e4909113cdc7&oe=5A3348E7"
},
function(obj){
if(obj) {
if(obj.completionGesture == "cancel") {
// user canceled, bad guy
} else {
// user really invited someone :)
}
} else {
// user just pressed done, bad guy
}
},
function(obj){
// error
// alert(JSON.stringify(obj));
}
);
}
function fcm(){
NativeKeyboard.showMessenger({
onSubmit: function(text) {
//console.log("The user typed: " + text);
}
});
}
var displaySuggestions = function(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
myApp.alert('Could not confirm your hometown.', 'Error');
clearHometown();
} else{
var predictionsarray = [];
$('.hometownprediction').remove();
predictions.forEach(function(prediction) {
predictionsarray.push(prediction.description);
});
}
var hometownpicker = myApp.picker({
input: '#homesearch',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } },
onChange:function (p, values, displayValues){$( '#homesearch' ).addClass("profilevaluechosen");},
onClose:function (p){hometownpicker.destroy();},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'hometown\')">' +
'<a href="#" class="link close-picker" onclick="clearHometown();" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: predictionsarray
}
]
});
hometownpicker.open();
};
function checkHometown(){
var hometownquery = $('#homesearch').val();
if (hometownquery == ''){
return false;}
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({ input: hometownquery,types: ['(cities)'] }, displaySuggestions);
}
function clearHometown(){
$('#homesearch').val('');
}
function newHometown(){
$('#homesearch').remove();
$('.hometown-input').append('<textarea class="resizable" id="homesearch" onclick="newHometown()" onblur="checkHometown()" placeholder="Hide" style="min-height:60px;max-height:132px;"></textarea>');
$('#homesearch').focus();
}
function fQuery(){
$.ajax({
url: "https://graph.facebook.com/v2.4/784956164912201?fields=context.fields(friends_using_app)",
type: "get",
data: { access_token: f_token},
success: function (response, textStatus, jqXHR) {
$.ajax({
url: "https://graph.facebook.com/v2.4/"+response.context.id+"/friends_using_app?summary=1",
type: "get",
data: { access_token: f_token},
success: function (response1, textStatus, jqXHR) {
try {
response1.summary.total_count;
var friendstring;
if (response1.summary.total_count ==0) {friendstring = 'No friends use this app'}
if (response1.summary.total_count ==1) {friendstring = '1 friend uses this app' }
if (response1.summary.total_count >1) {friendstring = response1.summary.total_count + ' friends use this app' }
if (response1.summary.total_count > 9){
nearbyshare = true;
recentshare = true;
$('.nearby-title').html('Nearby First');
$('.recent-title').html('Recently Online');
$('.nearby-helper').hide();
$('.recent-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.recent-wrapper').css("-webkit-filter","none");
firebase.database().ref('users/' + f_uid).update({
recentfriends:'Y'
}).then(function() {});
}
if ((response1.summary.total_count > 4) && (response1.summary.total_count <10)){
if ($('.no-results-div').length > 0) {$('.nearby-helper').hide();
$('.recent-helper').hide();}
else{
nearbyshare = true;
$('.nearby-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.nearby-title').html('Nearby First');
$('.recent-title').html('<i class="pe-7s-lock pe-lg"></i> Recently Online (Locked)');
recentshare = false;
$('.recent-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-helper').show();
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
//$('.recent-helper').html('<p style="margin-top:-10px;padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to <br/>unlock this feature.</p>');
//$('.summary-helper').html('<p style="font-weight:bold;">'+friendstring+'</p><div class="row"><div class="col-50"><a class="button active external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? ">Send SMS</a></div><div class="col-50"><a class="button active external" href="#" onclick="appLink()">Invite Friends</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">We appreciate your help to grow this app!</p>');
}
}
if (response1.summary.total_count < 5){
if ($('.no-results-div').length > 0) {$('.nearby-helper').hide();
$('.recent-helper').hide();}
else{
nearbyshare = false;
recentshare = false;
$('.nearby-helper').show();
$('.recent-helper').show();
$('.nearby-title').html('<i class="pe-7s-lock pe-lg"></i> Nearby First (Locked)');
$('.recent-title').html('<i class="pe-7s-lock pe-lg"></i> Recently Online (Locked)');
$('.nearby-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-wrapper').css("-webkit-filter","blur(10px)");
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
$('.nearby-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">'+friendstring+'</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="appLink()">Invite friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">5</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
//$('.recent-helper').html('<p style="margin-top:-10px;padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to <br/>unlock this feature.</p>');
// $('.nearby-helper').html('<p style=margin-top:-10px;"padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">5</span> or more friends on Facebook to <br/>unlock this feature.</p>');
// $('.summary-helper').html('<p style="font-weight:bold;"></p><div class="row"><div class="col-50"><a class="button active external" href="sms:&body=Check out a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? ">Send SMS</a></div><div class="col-50"><a class="button active external" href="#" onclick="appLink()">Invite Friends</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">We appreciate your help to grow this app!</p>');
}
}
} catch(err) {
$('.nearby-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">Invite friends to use this app</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="getFriends()">Find friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">5</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
$('.recent-helper').html(
'<div class="list-block media-list" style="margin-top:-20px;margin-bottom:5px;"><ul>'+
' <li>'+
' <div class="item-content" style="background-color:#f7f7f8;border-radius:5px;margin-left:20px;margin-right:20px;margin-top:10px;">'+
// ' <div class="item-media">'+
// ' <img src="path/to/img.jpg">'+
// ' </div>'+
'<div class="item-inner">'+
'<div class="item-title-row">'+
' <div class="item-title">Invite friends to use this app</div>'+
// '<div class="item-after"></div>'+
' </div>'+
'<div class="item-subtitle" style="margin-top:5px;margin-bottom:5px;"><a href="#" class="button active" onclick="getFriends()">Find friends</a></div>'+
' <div class="item-text">Sign up <span class="badge" style="background-color:#ff3b30;color:white;">10</span> friends on Facebook to unlock this feature.</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul></div> ');
// $('.recent-helper').html('<p style="padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">10</span> or more friends on Facebook to unlock this feature.</p>');
// $('.nearby-helper').html('<p style="padding:5px;">'+friendstring+'. Invite <span class="badge" style="background-color:#ff3b30;color:white;">5</span> or more friends on Facebook to unlock this feature.</p>');
//$('.summary-helper').html('<p style="font-weight:bold;">Invite friends to unlock features</p><div class="row"><div class="col-100"><a class="button active" href="#" onclick="getFriends">Unlock</a></div></div><p style="color:#666;font-size:12px;margin-top:-10px;">Features are locked based on how many friends you invite to use the app.</p>');
// caught the reference error
// code here will execute **only** if variable was never declared
}
$( ".summary-helper" ).show();
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(errorThrown);
},
complete: function () {
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(errorThrown);
},
complete: function () {
}
});
}
function setWant(val){
$( ".homedate" ).addClass("disabled");
$( ".homeduck" ).addClass("disabled");
if (val == 0){
if ($( ".homedate" ).hasClass( "active" )){$( ".homedate" ).removeClass("active");
if ($( ".homeduck" ).hasClass( "active" )){homewant = 'duck';updateWant();
}else {homewant = 'offline';updateWant();
}
}
else{$( ".homedate" ).addClass("active");
if ($( ".homeduck" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'date';updateWant(); }
}
}
if (val == 1){
if ($( ".homeduck" ).hasClass( "active" )){$( ".homeduck" ).removeClass("active");
if ($( ".homedate" ).hasClass( "active" )){homewant = 'date';updateWant(); }else {homewant = 'offline';updateWant(); }
}
else{$( ".homeduck" ).addClass("active");
if ($( ".homedate" ).hasClass( "active" )){homewant = 'dateduck';updateWant(); }else {homewant = 'duck';updateWant(); }
}
}
}
function updateWant(){
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.update();
nearbyswiper.update();
recentswiper.update();
if (homewant == 'offline'){
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
}
firebase.database().ref('users/' + f_uid).update({
homewant:homewant
}).then(function() {});
//Will update firebase user homewant
//Check if updateuser function is in go daddy file
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatewant.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,want:homewant} )
.done(function( data ) {
//getMatches();
});
}).catch(function(error) {
// Handle error
});
}
function startCamera(){
navigator.camera.getPicture(conSuccess, conFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI,sourceType:Camera.PictureSourceType.PHOTOLIBRARY});
}
function conSuccess(imageURI) {
//var image = document.getElementById('myImage');
//image.src = imageURI;
}
function conFail(message) {
// alert('Failed because: ' + message);
}
function doSomething() {
var i = Math.floor(Math.random() * 4) + 0;
$(".desktopimage").attr("src", desktoparray[i]);
}
var myFunction = function() {
doSomething();
var rand = Math.round(Math.random() * (1000 - 700)) + 700;
refreshIntervalId = setTimeout(myFunction, rand);
}
myFunction();
var mobile = 0;
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {mobile = 1;}
else{
mobile = 0;
$('.login-loader').hide();
$('.dateduckdesktop').append('<div style="clear:both;width:100%;text-align:center;border-top:1px solid #ccc;margin-top:10px;"><p>Meet people nearby for a date or a <strike>fu**</strike> duck.</br></br>Open on your phone.</p></div>');
}
//if (mobile===1){
try {
// try to use localStorage
localStorage.test = 2;
} catch (e) {
// there was an error so...
myApp.alert('You are in Privacy Mode\.<br/>Please deactivate Privacy Mode in your browser', 'Error');
}
function directUser(id,type,firstname){
if ($('.chatpop').length > 0) {myApp.closeModal('.chatpop');}
if (type =='date'){createDate1(id,firstname,0);}
else {createDuck(id,firstname,0);}
}
// Initialize your app
var myApp = new Framework7({dynamicNavbar: true,modalActionsCloseByOutside:true,init: false});
// Export selectors engine
var $$ = Dom7;
var datatap, tapid, taptype, tapname;
var view1, view2, view3, view4;
var updatecontinuously = false;
var initialload = false;
var allowedchange = true;
var view3 = myApp.addView('#view-3');
var view4 = myApp.addView('#view-4');
var myMessages, myMessagebar, f_description,existingchatnotifications, message_history = false, message_historyon, datealertvar = false, datealert = false, latitudep, longitudep, incommondate, incommonduck,f_uid,f_name,f_first,f_gender,f_age,f_email,image_url,f_image,f_token, f_upper, f_lower, f_interested,sexuality;
var f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = [];
var f_auth_id;
var blocklist;
var lastkey,ftokenset = false;
var distancepicker;
var pickerDescribe,pickerDescribe2, pickerCustomToolbar;
var existingmessages;
var additions = 0;
var myPhotoBrowser;
var singlePhotoBrowser;
var calendarInline;
var keepopen;
var userpref;
var loadpref= false;
var loadpref2= false;
var loaded = false;
var myList;
var myphotosarray;
var matcheslistener;
var noresultstimeout;
var timeoutactive = false;
var radiussize = '100';
var radiusunit = 'Kilometres';
var sortby,offsounds;
var industry_u,hometown_u,status_u,politics_u,eyes_u,body_u,religion_u,zodiac_u,ethnicity_u,height_u,weight_u,recentfriends;
var descriptionslist = [];
var nameslist = [];
var fdateicon = '<img src="media/dateicon.png" style="width:28px;margin-right:5px;">';
var fduckicon = '<img src="media/duckicon.png" style="width:28px;margin-right:5px;">';
var notifcount;
var swiperPhotos;
var swiperQuestions;
var myswiperphotos;
var flargedateicon = '<img src="media/dateicon.png" style="width:60px;">';
var flargeduckicon = '<img src="media/duckicon.png" style="width:60px;">';
var mySwiper;
myApp.init();
var f_projectid;
var canloadchat;
var viewphotos = false;
var viewscroll = false;
var homewant;
var singlefxallowed = true;
var photoresponse;
var targetpicture;
/*
* 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.
*/
var firebaseinit;
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
//soNow();
FCMPlugin.onNotification(function(data){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);
cordova.plugins.notification.badge.set(data.ev4);
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
if (latitudep){directUser(data.ev1,data.ev2,data.ev3);}
else{
datatap = true;
tapid = data.ev1;
taptype = data.ev2;
tapname = data.ev3;
}
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
myApp.addNotification({
title: 'Date or Duck',
subtitle:data.aps.alert.title,
message: data.aps.alert.body,
hold:2000,
closeOnClick:true,
onClick:function(){directUser(data.ev1,data.ev2,data.ev3);},
media: '<img width="44" height="44" style="border-radius:100%" src="media/icon-76.png">'
});
// alert( JSON.stringify(data) );
}
});
// Add views
view1 = myApp.addView('#view-1');
view2 = myApp.addView('#view-2', {
// Because we use fixed-through navbar we can enable dynamic navbar
dynamicNavbar: true
});
view3 = myApp.addView('#view-3');
view4 = myApp.addView('#view-4');
//setTimeout(function(){ alert("Hello");
//FCMPlugin.onTokenRefresh(function(token){
// alert( token );
//});
//alert("Hello2");
// }, 10000);
//authstatechanged user only
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var checkbadge = false;
if (f_projectid){checkbadge = false;}
else{checkbadge = true;}
cordova.plugins.notification.badge.get(function (badge) {
if (badge >0){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);}
else {$( ".notifspan" ).hide();}
});
//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
//Keep in mind the function will return null if the token has not been established yet.
f_projectid = firebase.auth().currentUser.toJSON().authDomain.substr(0, firebase.auth().currentUser.toJSON().authDomain.indexOf('.'))
f_uid = user.providerData[0].uid;
f_auth_id = user.uid;
f_name = user.providerData[0].displayName;
f_image = user.providerData[0].photoURL;
f_first = f_name.substr(0,f_name.indexOf(' '));
f_email = user.providerData[0].email;
// if (subscribeset){}
// else{
// FCMPlugin.subscribeToTopic( f_uid, function(msg){
// alert( msg );
//}, function(err){
// alert( err );
//} );
//}
//subscribeset = true;
if (checkbadge){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/setbadge.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data1 ) {
var result1 = JSON.parse(data1);
cordova.plugins.notification.badge.set(result1[0].notificationcount);
if (result1[0].notificationcount >0){
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);}
else {$( ".notifspan" ).hide();}
});
});
}
var originalid = window.localStorage.getItem("originalid");
if (!originalid) {window.localStorage.setItem("originalid", f_uid);}
// $( ".userimagetoolbar" ).css("background-image","url(\'https://graph.facebook.com/"+f_uid+"/picture?type=normal\')");
// $( "#profilepic" ).empty();
// $( "#profilepic" ).append('<div style="float:left;height:70px;width:70px;border-radius:50%;margin:0 auto;background-size:cover;background-position:50% 50%;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');"></div>');
firebase.database().ref('users/' + f_uid).update({
auth_id : f_auth_id
}).then(function() {getPreferences();});
} else {
$( ".ploader" ).show();
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
var originalid = window.localStorage.getItem("originalid");
if (originalid) {$( ".secondlogin" ).show();}
else {$( ".loginbutton" ).show();}
// No user is signed in.
}
});
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
function clearBadge(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/clearnotifications.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
});
});
$( ".notifspan" ).hide();
cordova.plugins.notification.badge.set(0);
}
function startApp(){
firebaseinit = localStorage.getItem('tokenStore');
if (firebaseinit){
var credential = firebase.auth.FacebookAuthProvider.credential(firebaseinit);
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
if (error){
myApp.alert('Error', 'Error message: ' + errorMessage + '(code:' + errorCode + ')');
}
});
}
else {
alert('77');
//alert('no tokenStore');
}
}
//document.addEventListener("screenshot", function() {
// alert("Screenshot");
//}, false);
$$('.panel-right').on('panel:opened', function () {
leftPanel();
});
$$('.panel-right').on('panel:open', function () {
$( ".upgradeli" ).slideDown();
clearBadge();
});
$$('.panel-right').on('panel:closed', function () {
myList.deleteAllItems();
myList.clearCache();
clearBadge();
//firebase.database().ref('notifications/' + f_uid).off('value', notificationlist);
});
function compare(a,b) {
if (a.chat_expire < b.chat_expire)
return -1;
if (a.chat_expire > b.chat_expire)
return 1;
return 0;
}
$$('.panel-left').on('panel:closed', function () {
$(".timeline").empty();
});
$$('.panel-left').on('panel:open', function () {
rightPanel();
});
$$('.panel-right').on('panel:closed', function () {
$( ".upgradeli" ).hide();
});
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content-1');
var geoupdate = Math.round(+new Date()/1000);
var firstupdate = false;
// Add 'refresh' listener on it
ptrContent.on('ptr:refresh', function (e) {
// Emulate 2s loading
//loaded = false;
if ($('.no-results-div').length > 0) {myApp.pullToRefreshDone();return false;}
var timesincelastupdate = Math.round(+new Date()/1000) - geoupdate;
if (firstupdate === false){getPreferences();firstupdate = true;}
else{
if (timesincelastupdate > 10){getPreferences();geoupdate = Math.round(+new Date()/1000);}
else {
random_all = shuffle(random_all);
randomswiper.removeAllSlides();
for (i = 0; i < random_all.length; i++) {
var index1 = f_date_match.indexOf(random_all[i].id);
var index2 = f_duck_match.indexOf(random_all[i].id);
var index3 = f_duck_me.indexOf(random_all[i].id);
var index4 = f_date_me.indexOf(random_all[i].id);
var slidewidth = $( document ).width() / 2.5;
var imagestyle;
imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;';
var randomid = Math.floor(Math.random() * (1000000000 - 0 + 1));
var slidecontent;
if (index1 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:-2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" class="swiper-lazy pp photo_'+random_all[i].id+' photo_'+randomid+'" data-src="'+random_all[i].profilepicstringsmall+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/datefaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index2 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/duckfaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index3 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/duckfaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index4 > -1) {
slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+random_all[i].id+'"><img src="media/datefaceonly.png" style="width:100px;"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else {slidecontent = '<div class="age_'+random_all[i].age+' swiper-slide slide_'+random_all[i].id+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+random_all[i].id+' maindivhome_'+randomid+'"></div><div class="distance_'+random_all[i].id+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;"></div><img crossOrigin="Anonymous" id="photo_'+random_all[i].id+'" onload="mainLoaded(\''+random_all[i].id+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+random_all[i].id+'" data-src="'+random_all[i].profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+random_all[i].id+'"></div><p class="name_'+random_all[i].id+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;"></p></div></div>';
}
randomswiper.appendSlide(slidecontent);
if (i == 0 || i==1 || i==2){
$(".photo_"+random_all[i].id).attr("src", random_all[i].profilepicstringsmall);
}
}
$( ".results-loader" ).show();
$( ".swiper-random" ).hide();
$( ".swiper-nearby" ).hide();
$( ".swiper-recent" ).hide();
$( ".home-title" ).hide();
$( ".nearby-helper" ).hide();
$( ".recent-helper" ).hide();
$( ".summary-helper" ).hide();
setTimeout(function(){
$( ".results-loader" ).hide();
$( ".swiper-random" ).show();
$( ".swiper-nearby" ).show();
$( ".swiper-recent" ).show();
$( ".home-title" ).show();
$( ".nearby-helper" ).show();
$( ".recent-helper" ).show();
$( ".summary-helper" ).show();
}, 2000);
}
}
setTimeout(function () {
// Random image
myApp.pullToRefreshDone();
}, 1000);
});
// Pull to refresh content
var ptrContent = $$('.pull-to-refresh-content-2');
// Add 'refresh' listener on it
ptrContent.on('ptr:refresh', function (e) {
myList.deleteAllItems();
myList.clearCache();
setTimeout(function () {
// Random image
leftPanel();
myApp.pullToRefreshDone();
}, 1000);
});
var onSuccess = function(position) {
latitudep = position.coords.latitude;
longitudep = position.coords.longitude;
//alert(latitudep);
//alert(longitudep);
if (datatap === true){
targetid = tapid;
targetname = tapname;
directUser(tapid,taptype,tapname);
datatap = false; tapid = false; taptype = false; tapname = false;
}
updateGeo();
$( ".age-header" ).remove();
$( ".swiper-container-loaded" ).remove();
};
function onError(error) {
if (error.code == '1'){
myApp.alert('we are using your approximate location, to improve accuracy go to location settings', 'Oops we cannot find you');
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
})
.done(function() {
//alert('done');
})
.fail(function(err) {
myApp.alert('You must share your location on date or duck', 'Oops we cannot find you');
});
}
if ((error.code == '2') || (error.code == '3')){
jQuery.post( "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCAqd15w-_K31IUyLWNlmkHNmZU5YLSg6c", function(success) {
apiGeolocationSuccess({coords: {latitude: success.location.lat, longitude: success.location.lng}});
})
.done(function() {
//alert('done');
})
.fail(function(err) {
myApp.alert('There has been an error.', 'Oops we cannot find you');
});
}
}
function showtext(){
$( ".showtext" ).show();
}
function getWifilocation(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
var apiGeolocationSuccess = function(position) {
latitudep = position.coords.latitude;
longitudep = position.coords.longitude;
//alert(latitudep);
//alert(longitudep);
if (datatap === true){
targetid = tapid;
targetname = tapname;
directUser(tapid,taptype,tapname);
datatap = false; tapid = false; taptype = false; tapname = false;
}
updateGeo();
$( ".age-header" ).remove();
$( ".swiper-container-loaded" ).remove();
};
function mainLoaded(id,pid){
$( ".iconpos_" + id ).show();
$( ".default_" + pid).hide();
$( ".photo_"+ pid ).show();
var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + id);
indivNotif.once('value', function(snapshot) {
if (snapshot.val()){
var obj = snapshot.val();
if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".maindivhome_" + pid).html('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');}
else{$( ".maindivhome_" + pid ).empty();}
}
});
}
var all_matches_photos=[];
var new_all = [];
var main_all = [];
var random_all = [];
var nearby_all = [];
var recent_all = [];
var nearbyshare = false, recentshare = false;
var randomswiper = myApp.swiper('.swiper-random', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = random_all;
photoBrowser(randomswiper.clickedIndex);}
});
var nearbyswiper = myApp.swiper('.swiper-nearby', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = nearby_all;
if (nearbyshare){
photoBrowser(nearbyswiper.clickedIndex);
}
else{}
}
});
var recentswiper = myApp.swiper('.swiper-recent', {
slidesPerView:2.5,
//freeMode:true,
slidesOffsetAfter:12,
preloadImages: false,
lazyLoading: true,
watchSlidesVisibility:true,
watchSlidesProgress: true,
lazyLoadingInPrevNextAmount:5,
lazyLoadingOnTransitionStart:true,
onClick:function(swiper, event) {
new_all = recent_all;
if (recentshare){
photoBrowser(recentswiper.clickedIndex);
}
else{}
}
});
function getMatches(){
$( ".content-here" ).empty();
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.update();
nearbyswiper.update();
recentswiper.update();
$( ".results-loader" ).show();
$( ".home-title" ).hide();
$( ".nearby-helper" ).hide();
$( ".recent-helper" ).hide();
$( ".summary-helper" ).hide();
//alert('getmatch trigger' + homewant);
//can put any ads here
if ((initialload === false) && (availarray.length === 0)){
}
if (!homewant || homewant =='offline'){
$('.content-here').empty();
$( ".statusbar-overlay" ).css("background-color","#ccc");
$( ".buttons-home" ).hide();
$( ".toolbar" ).hide();
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
var swiperheight = $( window ).height() - 378;
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:44px;left:50%;margin-left:-150px;margin-top:54px;">'+
'<div class="topdiv">'+
// '<h3>Get Quacking!</h3>'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:15px;margin-left:0px;">Get Quacking, It\'s Easy</div>'+
'<div class="row" style="padding-top:10px;padding-bottom:10px;">'+
'<div class="col-30" style="padding-top:5px;"><img src="media/datefaceonly.png" style="width:80px;margin:0 auto;"></div>'+
// '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:20px;">date</span> if you want to find something more serious like a relationship.</div>'+
'<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:26px;">date</span> to find love <br/>(or at least try)</div>'+
'</div>'+
'<div class="row" style="padding-top:10px;padding-bottom:10px;margin-bottom:10px;">'+
'<div class="col-30" style="padding-top:5px;"><img src="media/duckfaceonly.png" style="width:80px;margin:0 auto;"></div>'+
// '<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:20px;">duck</span> if you want to get down to...ahem...business (replace the D with another letter). </div>'+
'<div class="col-70" style="padding-top:5px;">Press <span style="font-family: \'Pacifico\', cursive;font-size:26px;">duck</span> to find fun <br/>(replace the D with another letter)</div>'+
'</div>'+
'</div>'+
'<div class="list-block-label" style="color:#666;margin-bottom:10px;">Choose one, or both. Your profile is hidden until you decide.</div>'+
'<div class="swiper-container swiper-helper-info" style="z-index:99999999999999;background-color:#ccc;color:#6d6d72;margin-left:-10px;margin-right:-10px;padding-top:10px;">'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:15px;margin-left:0px;">How this App Works</div>'+
' <div class="swiper-wrapper">'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px;"><i class="twa twa-4x twa-coffee" style="margin-top:5px;"></i><h2>Find your next<br/> coffee date...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-wave" style="margin-top:5px;"></i><h2>Or invite someone over<br/> tonight...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-heart-eyes" style="margin-top:5px;"></i><h2>When you like someone, <br/>they can see...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-calendar" style="margin-top:5px;"></i><h2>Once you both agree on</br> a time to meet...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-clock12" style="margin-top:5px;"></i><h2>Chat is enabled until <br/>midnight of your date...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-bomb" style="margin-top:5px;"></i><h2>You can send photos that delete after 24 hours...</h2></div></div>'+
' <div class="swiper-slide" style="height:'+swiperheight +'px;"><div class="squareheight" style="height:153px;top:50%;margin-top:-85px;position:absolute;width:300px;left:50%;margin-left:-150px"><i class="twa twa-4x twa-watch" style="margin-top:5px;"></i><h2>You can share availability<br/> to easily schedule dates</h2></div></div>'+
' </div>'+
'<div class="swiper-pagination-p" style="margin-top:-20px;margin-bottom:20px;"></div>'+
'</div>'+
' <div class="content-block-title" style="width:100%;text-align:center;margin-top:20px;margin-bottom:10px;margin-left:0px;">Support this app</div>'+
'<a href="#" class="button-big button active" style="margin-bottom:10px;" onclick="appLink()">Invite Friends</a>'+
'<a href="#" class="button-big button" style="margin-bottom:10px;" onclick="sharePop()">Share</a>'+
'<a class="button-big button external" href="sms:&body=Check out this new a new app in the App Store: https://fb.me/1554148374659639. It is called Date or Duck. Thoughts? " style="margin-bottom:10px;">Send SMS</a>'+
'</div>');
$( ".ploader" ).hide();
var homeswiperhelper = myApp.swiper('.swiper-helper-info', {
pagination:'.swiper-pagination-p'
});
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
setTimeout(function(){
$( ".homedate" ).removeClass("disabled");
$( ".homeduck" ).removeClass("disabled");
}, 2000);
return false;
}
$( ".statusbar-overlay" ).css("background-color","#2196f3");
initialload = true;
if (recentfriends){
nearbyshare = true;
recentshare = true;
$('.nearby-title').html('Nearby First');
$('.recent-title').html('Recently Online');
$('.nearby-helper').hide();
$('.recent-helper').hide();
$('.nearby-wrapper').css("-webkit-filter","none");
$('.recent-wrapper').css("-webkit-filter","none");
}
else{
//check permission first
readPermissions();
}
if (updatecontinuously){}
else {setInterval(function(){ justGeo(); }, 599999);updatecontinuously=true;}
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
if (timeoutactive === true) {clearTimeout(noresultstimeout);}
timeoutactive = true;
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/locations.php", { want:homewant,projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,upper:f_upper,lower:f_lower,radius:radiussize,radiusunit:radiusunit,sexuality:sexuality,sortby:'random',latitudep:latitudep,longitudep:longitudep} )
.done(function( data ) {
dbCall('random');
dbCall('distance');
dbCall('activity');
function dbCall(fetch){
var resultall = JSON.parse(data);
var result;
if (fetch == 'random'){result = resultall[2];}
if (fetch == 'distance'){result = resultall[1];}
if (fetch == 'activity'){result = resultall[0];}
var slidewidth = $( document ).width() / 2.5;
var halfwidth = -Math.abs(slidewidth / 2.23);
$( ".swiper-recent" ).css("height",slidewidth + "px");
$( ".swiper-nearby" ).css("height",slidewidth + "px");
$( ".swiper-random" ).css("height",slidewidth + "px");
var slide_number = 0;
descriptionslist = [];
nameslist = [];
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
if (result == 77 ||(result.length ===1 && result[0].uid == f_uid ) ){
$( ".home-title" ).hide();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
else {
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (i = 0; i < result.length; i++) {
var photosstringarray =[];
var photocount;
var photostring;
var blocked = 0;
var subtract = result[i].age;
var laston = result[i].timestamp;
var hometown_d = result[i].hometown;
var industry_d = result[i].industry;
var status_d = result[i].status;
var politics_d = result[i].politics;
var eyes_d = result[i].eyes;
var body_d = result[i].body;
var religion_d = result[i].religion;
var zodiac_d = result[i].zodiac;
var ethnicity_d = result[i].ethnicity;
var height_d = result[i].height;
var weight_d = result[i].weight;
var namescount = result[i].displayname.split(' ').length;
var matchname;
var minphotowidth = $( document ).width();
var imagestyle;
imagestyle='width:100%;max-height:' + slidewidth + 'px;overflow:hidden;';
var availarraystring='';
var availnotexpired = false;
if(result[i].availstring && (result[i].availstring != '[]') && (result[i].uid != f_uid)){
//console.log(result[i].availstring);
var availablearrayindividual = JSON.parse(result[i].availstring);
//console.log(availablearrayindividual);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
}
if (availnotexpired){availarraystring = result[i].availstring;}
}
var profilepicstring;
var photoarrayuserlarge;
var photoarrayusersmall;
if(result[i].largeurl){
var heightarray = result[i].heightslides.split(",");
var widtharray = result[i].widthslides.split(",");
//console.log(heightarray[0]);
//console.log(widtharray[0]);
if (heightarray[0] > widtharray[0]) {imagestyle = 'width:100%;max-height:' + slidewidth + 'px;overflow:hidden;'}
if (widtharray[0] > heightarray[0]) {imagestyle = 'height:100%;max-width:' + slidewidth + 'px;overflow:hidden;'}
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[i].largeurl + '" class="swiper-lazy"></div></div>';
photocount = result[i].largeurl.split(",").length;
photoarrayuserlarge = result[i].largeurl.split(",");
photoarrayusersmall = result[i].smallurl.split(",");
profilepicstringlarge = photoarrayuserlarge[0];
profilepicstringsmall = photoarrayusersmall[0];
photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="')
}
else{
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+result[i].uid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>';
profilepicstringlarge = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=828&height=828';
profilepicstringsmall = 'https://graph.facebook.com/'+result[i].uid+'/picture?width=368&height=368';
photocount = 1;
}
//console.log(photostring);
if(namescount === 1){matchname = result[i].displayname;}
else {matchname = result[i].name.substr(0,result[i].displayname.indexOf(' '));}
var matchdescription = result[i].description;
var swipernumber = subtract - f_lower;
var graphid = result[i].uid;
var distance = parseFloat(result[i].distance).toFixed(1);
var distancerounded = parseFloat(result[i].distance).toFixed(0);
if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'}
if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'}
if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'}
if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'}
if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'}
if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'}
if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'}
if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'}
if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'}
if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'}
if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'}
if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'}
var zz = new Date();
var mmn = zz.getTimezoneOffset();
//console.log(result[i].timestamp);
var timestampyear = result[i].timestamp.substring(0,4);
var timestampmonth = result[i].timestamp.substring(5,7);
var timestampday = result[i].timestamp.substring(8,10);
var timestamphour = result[i].timestamp.substring(11,13);
var timestampminute = result[i].timestamp.substring(14,16);
var timestampsecond = result[i].timestamp.substring(17,20);
var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800;
var d_unix = Math.round(+new Date()/1000);
var diff = (d_unix - timestampunix)/60;
var activecircle='';
//if (diff<11){activecircle = '<span style="position:absolute;left:10px;height:10px;width:10px;border-radius:50%;bottom:10px;background-color:#4cd964"></span>';}
//else{activecircle = '<span style="position:absolute;left:10px;bottom:10px;height:10px;width:10px;border-radius:50%;background-color:transparent;border:1px solid #ccc;"></span>';}
if ($('.slide_' + graphid).length){
}
if (graphid != f_uid){
$('.swiper-' + subtract).show();
$('.header_' + subtract).show();
}
var blockedid = blocklist.indexOf(graphid);
//Do not show the users profile to themselves, and do not show profiles older than 1 month
if ((graphid != f_uid) && (blockedid < 0) && (diff < 43800)){
var index1 = f_date_match.indexOf(graphid);
var index2 = f_duck_match.indexOf(graphid);
var index3 = f_duck_me.indexOf(graphid);
var index4 = f_date_me.indexOf(graphid);
var randomid = Math.floor(Math.random() * (1000000000 - 0 + 1));
var slidecontent;
if (index1 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:-2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" class="swiper-lazy pp photo_'+graphid+' photo_'+randomid+'" data-src="'+profilepicstringsmall+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" style="display:none;'+imagestyle+'-webkit-filter:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index2 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#2196f3;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:none;display:none;overflow:hidden;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index3 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/duckfaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else if (index4 > -1) {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"/><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;-webkit-filter:grayscale(1%);display:none;" class="icondiv iconpos_'+graphid+'"><img src="media/datefaceonly.png" style="width:100px;"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-left:23px;margin-top:-30px;color:white;font-size:15px;text-align:left;"></p></div></div>';
}
else {
slidecontent = '<div class="age_'+subtract+' swiper-slide slide_'+graphid+'" style="text-align:center;padding-top:3px;padding-left:3px;"><span class="preloader default_'+randomid+'"></span><div style="width:'+slidewidth+'px;margin:0 auto;"><div style="position:absolute;right:2px;top:0px;" class="arrowdivhome_'+graphid+' maindivhome_'+randomid+'"></div><div class="distance_'+graphid+'" style="display:none;width:50px;background-color:#ccc;color:white;z-index:999;padding:0.5px;position:absolute;left: 3px;z-index:1000;font-size:12px;">'+distancestring+'</div><img crossOrigin="Anonymous" id="photo_'+graphid+'" onload="mainLoaded(\''+graphid+'\',\''+randomid+'\');" class="photo_'+randomid+' swiper-lazy pp photo_'+graphid+'" data-src="'+profilepicstringsmall+'" style="'+imagestyle+'-webkit-filter:grayscale(80%);overflow:hidden;display:none;margin-top:0px;"><div style="bottom:0px;right:0px;position:absolute;width:50px;overflow-x:hidden;height:50px;overflow-y:hidden;display:none;" class="icondiv iconpos_'+graphid+'"></div>'+activecircle+'<p class="name_'+graphid+'" style="-webkit-filter:grayscale(80%);clear:both;font-weight:bold;margin-top:-30px;color:white;font-size:15px;text-align:left;float:left;margin-left:23px;"></p></div></div>';
}
if (fetch == 'random'){randomswiper.appendSlide(slidecontent);
random_all.push({profilepicstringsmall:profilepicstringsmall,hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (random_all[0].id == graphid || random_all[1].id == graphid || random_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
if (fetch == 'distance'){nearbyswiper.appendSlide(slidecontent);
nearby_all.push({hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (nearby_all[0].id == graphid || nearby_all[1].id == graphid || nearby_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
if (fetch == 'activity'){recentswiper.appendSlide(slidecontent);
recent_all.push({hometown:hometown_d,widthslides:result[i].widthslides,heightslides:result[i].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:subtract,description:matchdescription,id:graphid,url:'https://graph.facebook.com/'+graphid+'/picture?width=828',caption:'...',industry: industry_d, status: status_d, politics:politics_d,eyes:eyes_d,body:body_d,religion:religion_d,zodiac:zodiac_d,ethnicity:ethnicity_d,height:height_d,weight:weight_d});
if (recent_all[0].id == graphid || recent_all[1].id == graphid || recent_all[2].id == graphid){
$(".photo_"+graphid).attr("src", profilepicstringsmall);
}
}
}
}
}
//if (nearbyshare){
//remove blur, unlock swiper
//}
//else{ $( ".nearby-helper" ).show();}
//if (recentshare){
//remove blur, unlock swiper
//}
//else{ $( ".recent-helper" ).show();}
setTimeout(function(){
$( ".homedate" ).removeClass("disabled");
$( ".homeduck" ).removeClass("disabled");
}, 2000);
if (random_all.length === 0){
if ($('.no-results-div').length > 0) {}
else{
$( ".home-title" ).hide();
$( ".results-loader" ).hide();
$( ".summary-helper" ).show();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
}
else {$( ".home-title" ).show(); $('.content-here').empty();}
}
});
//here is the id token call
}).catch(function(error) {
// Handle error
});
$( ".ploader" ).hide();
$( ".toolbar" ).show();
$( ".loginbutton" ).show();
$( ".login-loader" ).hide();
//$('.no-results-div').empty();
clearInterval(refreshIntervalId);
deletePhotos();
}
function justGeo(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} )
.done(function( data ) {
//console.log('updatedtimestamp');
});
}).catch(function(error) {
// Handle error
});
}
function updateGeo(){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatelocation.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,latitude:latitudep,longitude:longitudep} )
.done(function( data ) {
getMatches();
});
}).catch(function(error) {
// alert('error' + error);
});
}
function getPreferences(){
// Test if user exists
if(userpref) {firebase.database().ref('users/' + f_uid).off('value', userpref);}
userpref = firebase.database().ref('users/' + f_uid).on("value",function(snapshot) {
var userexists = snapshot.child('lower').exists(); // true
if (userexists) {
// var matchessetting = firebase.database().ref("users/" + f_uid).on("value",function(snapshot) {
// if (!snapshot.child("to_date").val()) {f_to_date = [];}
// else{f_to_date = snapshot.child("to_date").val();}
// if (!snapshot.child("to_duck").val()) {f_to_duck = [];}
// else{f_to_duck = snapshot.child("to_duck").val();}
// if (!snapshot.child("date_me").val()) {f_date_me = [];}
// else{f_date_me = snapshot.child("date_me").val();}
// if (!snapshot.child("duck_me").val()) {f_duck_me=[];}
// else{f_duck_me = snapshot.child("duck_me").val();}
// incommondate = f_to_date.filter(function(n) {
// return f_date_me.indexOf(n) != -1;
//});
//incommonduck = f_to_duck.filter(function(n) {
// return f_duck_me.indexOf(n) != -1;
//});
// });
hometown_u = snapshot.child("hometown").val();
industry_u = snapshot.child("industry").val();
status_u = snapshot.child("status").val();
politics_u = snapshot.child("politics").val();
eyes_u = snapshot.child("eyes").val();
body_u = snapshot.child("body").val();
religion_u = snapshot.child("religion").val();
zodiac_u = snapshot.child("zodiac").val();
ethnicity_u = snapshot.child("ethnicity").val();
height_u = snapshot.child("height").val();
weight_u = snapshot.child("weight").val();
homewant = snapshot.child("homewant").val();
recentfriends = snapshot.child("recentfriends").val();
//f_image = snapshot.child("image_url").val();
image_url = f_image;
if (snapshot.child("photoresponse").val()){
if (snapshot.child("photoresponse").val() == 'Y'){photoresponse = 'Y';imageurl = snapshot.child("image_url").val();}
}
else{
photoresponse = 'N';
image_url = f_image;
}
sortby = snapshot.child("sort").val();
if (sortby){
if (sortby == 'random'){sortBy(1);}
if (sortby == 'distance'){sortBy(2);}
if (sortby == 'activity'){sortBy(3);}
$( ".sortbutton" ).removeClass( "active" );
$( "#sort" + sortby ).addClass( "active" );
}
if (snapshot.child("offsounds").val()){offsounds = snapshot.child("offsounds").val();}
if (snapshot.child("availstring").val()){ availarray = JSON.parse(snapshot.child("availstring").val());}
f_description = snapshot.child("description").val();
f_lower = snapshot.child("lower").val();
radiussize = snapshot.child("radius").val();
if(snapshot.child("radiusunit").val()){radiusunit = snapshot.child("radiusunit").val();}
else{radiusunit = "Kilometres";}
if (ftokenset){
firebase.database().ref('users/' + f_uid).update({
token: f_token
});
}
else{f_token = snapshot.child("token").val();}
f_upper = snapshot.child("upper").val();
f_interested = snapshot.child("interested").val();
f_gender = snapshot.child("gender").val();
f_age = snapshot.child("age").val();
if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';}
if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';}
if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';}
if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';}
if (loadpref=== false){
if(homewant){
if (homewant == 'offline'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).removeClass('active'); }
if (homewant == 'dateduck'){$( ".homedate" ).addClass('active');$( ".homeduck" ).addClass('active'); }
if (homewant == 'duck'){$( ".homedate" ).removeClass('active');$( ".homeduck" ).addClass('active'); }
if (homewant == 'date'){$( ".homedate" ).addClass('active');$( ".homeduck" ).removeClass('active');}
}
loadpref = true;
establishNotif();
}
matchesListener();
}
else if (!userexists) {
addUser();
if (loadpref=== false){
firebase.database().ref('users/' + f_uid).once("value",function(snapshot) {
f_token = snapshot.child("token").val();
swipePopup(1);
});
//preferencesPopup();
}
loadpref = true;
}
});
}
function matchesListener(){
if (loaded === true){
firebase.database().ref("matches/" + f_uid).off('value', matcheslistener);
}
matcheslistener = firebase.database().ref("matches/" + f_uid).on("value",function(snapshot) {
f_to_date = [],f_to_duck = [],f_date_me = [],f_duck_me = [],f_date_match = [],f_duck_match = [],f_date_match_data = [],f_duck_match_data = [];
blocklist = [];
if (snapshot.val()){
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if ((obj.first_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.second_number);}
if ((obj.second_number == f_uid) && (obj.firstnumberblock == 'Y' || obj.secondnumberblock == 'Y')) {blocklist.push(obj.first_number);}
if(obj.firstnumberdate){
//f_to_date
if ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y')) {f_to_date.push(obj.second_number);}
//f_date_me
if ((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) {f_date_me.push(obj.first_number);}
}
if(obj.firstnumberduck){
//f_duck_me
if ((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) {f_duck_me.push(obj.first_number);}
//f_to_duck
if ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y')) {f_to_duck.push(obj.second_number);}
}
if(obj.secondnumberdate){
//f_to_date
if ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y')) {f_to_date.push(obj.first_number);}
//f_date_me
if ((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) {f_date_me.push(obj.second_number);}
}
if(obj.secondnumberduck){
//f_to_duck
if ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y')) {f_to_duck.push(obj.first_number);}
//f_duck_me
if ((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) {f_duck_me.push(obj.second_number);}
}
if(obj.firstnumberdate && obj.secondnumberdate){
//f_date_match
if(((obj.first_number != f_uid) && (obj.firstnumberdate == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberdate == 'Y'))){f_date_match.push(obj.first_number);f_date_match_data.push({uid:obj.first_number,name:obj.first_name});}
if(((obj.second_number != f_uid) && (obj.secondnumberdate == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberdate == 'Y'))){f_date_match.push(obj.second_number);f_date_match_data.push({uid:obj.second_number,name:obj.second_name});}
}
if(obj.firstnumberduck && obj.secondnumberduck){
//f_duck_match
if(((obj.first_number != f_uid) && (obj.firstnumberduck == 'Y')) && ((obj.second_number == f_uid) && (obj.secondnumberduck == 'Y'))){f_duck_match.push(obj.first_number);f_duck_match_data.push({uid:obj.first_number,name:obj.first_name});}
if(((obj.second_number != f_uid) && (obj.secondnumberduck == 'Y')) && ((obj.first_number == f_uid) && (obj.firstnumberduck == 'Y'))){f_duck_match.push(obj.second_number);f_duck_match_data.push({uid:obj.second_number,name:obj.second_name});}
}
});
updatePhotos();
loaded = true;
}
else{
updatePhotos();
loaded = true;
}
});
getWifilocation();
}
function addUser() {
if (f_token){firebase.database().ref('users/' + f_uid).update({
name: f_name,
email: f_email,
image_url : f_image,
uid:f_uid,
token:f_token,
auth_id : f_auth_id
});}
else{
firebase.database().ref('users/' + f_uid).update({
name: f_name,
email: f_email,
image_url : f_image,
uid:f_uid,
auth_id : f_auth_id
});
}
}
function clickMe() {
pickerDescribe.open();
}
function keyUp(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
var inputlength = $( "#userdescription" ).val().length;
$( "#maxdescription" ).empty();
$( "#maxdescription" ).append(inputlength + " / 100");
}
function updateUser(){
if ((pickerDescribe.initialized === false && !f_age) || (pickerDescribe2.initialized === false && !f_lower)) {
myApp.alert('Please complete more profile information.', 'Missing Information');
return false;}
if (myswiperphotos){
myswiperphotos.destroy();
myswiperphotos = false;
}
var newage,newinterested,newgender;
if (pickerDescribe.initialized === false) {newage = f_age;newgender = f_gender;}
else {newage = pickerDescribe.value[1];newgender = pickerDescribe.value[0];}
if (pickerDescribe2.initialized === false) {newinterested = f_interested;}
else {newinterested = pickerDescribe2.value[0];}
var userzdescription;
if ($( "#userdescription" ).val()) {userzdescription = $( "#userdescription" ).val();}
else {userzdescription = '';}
//Need to delete old reference
if (pickerDescribe.initialized === true) {f_age = pickerDescribe.value[1];f_gender = pickerDescribe.value[0];}
if (pickerDescribe2.initialized === true) {f_interested = pickerDescribe2.value[0];}
if (f_gender == 'Male' && f_interested == 'Men') {sexuality = 'gay';}
if (f_gender == 'Male' && f_interested == 'Women') {sexuality = 'male';}
if (f_gender == 'Female' && f_interested == 'Women') {sexuality = 'lesbian';}
if (f_gender == 'Female' && f_interested == 'Men') {sexuality = 'female';}
var lowerage,upperage;
if (pickerDescribe2.initialized === true) {
if (pickerDescribe2.value[1] > pickerDescribe2.value[2]) {lowerage = pickerDescribe2.value[2];upperage = pickerDescribe2.value[1];}
else {lowerage = pickerDescribe2.value[1];upperage = pickerDescribe2.value[2];}
}
else {lowerage = f_lower;upperage = f_upper;}
//if ($( "#distance_10" ).hasClass( "active" )){radiussize = '10';}
//if ($( "#distance_25" ).hasClass( "active" )){radiussize = '25';}
//if ($( "#distance_50" ).hasClass( "active" )){radiussize = '50';}
//if ($( "#distance_100" ).hasClass( "active" )){radiussize = '100';}
availarray = [];
$( ".availrec" ).each(function() {
if ($( this ).hasClass( "selecrec" )){
var availinputid = $(this).attr('id').replace('aa_', '');
var valueinputted = $( "#picker"+availinputid ).val();
var supdate = $( ".suppdate_"+availinputid ).val();
if (valueinputted == 'Now'){daysaved ='Now';timesaved='';}
else{
valueinputted = valueinputted.split(' ');
var daysaved = valueinputted[0];
var timesaved = valueinputted[1];
}
availarray.push({id:availinputid,day:daysaved,time:timesaved,fulldate:supdate});
}
});
var availstring = JSON.stringify(availarray);
var availstringn = availstring.toString();
if ($('#soundnotif').prop('checked')) {offsounds = 'Y'} else {offsounds = 'N'}
//User Profile details
var hometown_u = $( "#homesearch" ).val();
var industry_u = $( "#industry-input" ).val();
var status_u = $( "#status-input" ).val();
var politics_u = $( "#politics-input" ).val();
var eyes_u = $( "#eyes-input" ).val();
var body_u = $( "#body-input" ).val();
var religion_u = $( "#religion-input" ).val();
var zodiac_u = $( "#zodiac-input" ).val();
var ethnicity_u = $( "#ethnicity-input" ).val();
var height_u = $( "#height-input" ).val().substring(0,3);
var weight_pre = $( "#weight-input" ).val();
var weight_u = weight_pre.substr(0, weight_pre.indexOf(' '));
var uploadurl = '';
photoresponse = 'N';
if (f_largeurls.length > 0){photoresponse = 'Y';uploadurl = f_largeurls[0];}
else{photoresponse='N';uploadurl = '';}
firebase.database().ref('users/' + f_uid).update({
gender: newgender,
industry:industry_u,
hometown:hometown_u,
status:status_u,
politics: politics_u,eyes: eyes_u,body: body_u,religion: religion_u,zodiac: zodiac_u,ethnicity: ethnicity_u,
height: height_u,
weight: weight_u,
age: newage,
interested: newinterested,
lower: lowerage,
upper: upperage,
description:userzdescription,
radius:radiussize,
radiusunit:radiusunit,
availstring:availstring,
offsounds:offsounds,
photoresponse:photoresponse,
uploadurl:uploadurl
});
if (deletedphoto){
var newsmall = f_smallurls.toString();
var newlarge = f_largeurls.toString();
var newwidth = addedwidth.toString();
var newheight = addedheight.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
});
}).catch(function(error) {
// Handle error
});
}
var hometown_u = $( "#homesearch" ).val();
var industry_u = $( "#industry-input" ).val();
var status_u = $( "#status-input" ).val();
var politics_u = $( "#politics-input" ).val();
var eyes_u = $( "#eyes-input" ).val();
var body_u = $( "#body-input" ).val();
var religion_u = $( "#religion-input" ).val();
var zodiac_u = $( "#zodiac-input" ).val();
var ethnicity_u = $( "#ethnicity-input" ).val();
var height_u = $( "#height-input" ).val().substring(0,3);
var weight_pre = $( "#weight-input" ).val();
var weight_u = weight_pre.substr(0, weight_pre.indexOf(' '));
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatedetails.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,sexuality:sexuality,uid:f_uid,name:f_name,description:userzdescription,age:newage,availstring:availstringn,industry:industry_u,hometown:hometown_u,status:status_u,politics:politics_u,eyes:eyes_u,body:body_u,religion:religion_u,zodiac:zodiac_u,ethnicity:ethnicity_u,height:height_u,weight:weight_u} )
.done(function( data ) {
//if (f_gender && (f_gender != newgender)){
//deleteDatabase();
//}
//if (f_interested && (f_interested != newinterested)){
//deleteDatabase();
//}
});
}).catch(function(error) {
// Handle error
});
f_lower = lowerage;
f_upper = upperage;
//if (loadpref2===true){getWifilocation();}
loadpref2 = true;
myApp.closeModal();
$( ".popup-overlay" ).remove();
}
function processUpdate(){
$( '.donechange' ).show();
$( '.doneunchange' ).hide();
}
function processDupdate(){
var unixnow = Math.round(+new Date()/1000);
var middaystamp = new Date();
middaystamp.setHours(12,00,00,000);
var middaystamp_timestamp = Math.round(middaystamp/1000);
var threestamp = new Date();
threestamp.setHours(12,00,00,000);
var threestamp_timestamp = Math.round(threestamp/1000);
var fivestamp = new Date();
fivestamp.setHours(17,00,00,000);
var fivestamp_timestamp = Math.round(fivestamp/1000);
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){myApp.alert('You must choose a time in the future', pickerCustomToolbar.cols[1].displayValue +' has past!');pickerCustomToolbar.cols[1].setValue('');return false;}
if (d_chat_expire){
var datemessageq = $( '#datemessageq' ).val();
var interestnewarray = [];
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestnewarray.push(interestadd);
}
});
var comparedinterest;
var compareninterest;
if (d_interest != null) {
comparedinterest = d_interest.toString();
}
else {comparedinterest = '';}
if (typeof interestnewarray == 'undefined' && interestnewarray.length === 0){compareninterest = '';}else{compareninterest = interestnewarray.toString();}
if ((d_day == pickerCustomToolbar.cols[0].displayValue) && (d_time ==pickerCustomToolbar.cols[1].displayValue) && (datemessageq == '' ) && (compareninterest == comparedinterest))
{
if (d_response=='Y'){noChange();}
else if (d_response=="W"){reverseRequest();dateConfirmationPage();}
}
else{dateRequest();}
}
else {dateRequest();}
}
var mynotifs = [];
function leftPanel(){
canscrollnotif = true;
mynotifs = [];
notifadditions=0;
if(!myList){
myList = myApp.virtualList('.virtual-notifications', {
// Array with plain HTML items
items: [],
height:89,
renderItem: function (index, item) {
var backgroundnotifcolor;
if(item.colordot == ''){backgroundnotifcolor = 'white';}else{backgroundnotifcolor = 'transparent';}
if(item.from_uid == f_uid){
return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' +
'<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+
'</div>' +
'<div class="item-inner" onclick="'+item.func+'('+item.targetid+',\''+item.targetname+'\')" style="margin-left:10px;" >' +
'<div class="item-title-row" >'+
'<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+'</div>'+
'<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+
'</div>'+
'<div class="item-subtitle">'+ item.icon + item.title + ' </div>' +
'<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' +
'</div>' +
'</li>';
}
else{
//onclick="singleBrowser('+item.targetid+')"
return '<li class="item-content" style="height:89px;background-color:'+backgroundnotifcolor+'">' +
'<div class="item-media" onclick="singleUser('+item.targetid+',\''+item.targetname+'\',1)" style="width:50px;height:50px;border-radius:50%;background-image:url('+item.picture+');background-size:cover;background-position:50% 50%;">'+
'</div>' +
'<div class="item-inner" onclick="'+item.func+'(\''+item.targetid+'\',\''+item.targetname+'\')" style="margin-left:10px;" >' +
'<div class="item-title-row" >'+
'<div class="item-title" style="font-size:14px;margin-top:5px;">'+item.targetname+item.colordot+'</div>'+
'<div class="item-after"><img src="media/'+item.type+'faceonly.png" style="width:30px;"></div>'+
'</div>'+
'<div class="item-subtitle" style="color:black;">'+ item.icon + item.title + ' </div>' +
'<div class="item-text" style="height:20.8px">'+ item.timestamptitle + ' </div>' +
'</div>' +
'</li>';
}
}
});
}
var notificationlist = firebase.database().ref('notifications/' + f_uid).once('value', function(snapshot) {
if (snapshot.val() === null){
// $('.title-notify').remove();
// $('.virtual-notifications').append('<div class="content-block-title title-notify" style="margin-top:54px;">No notifications</div>');
$('.nonefound').remove();
$('.virtual-notifications').prepend('<div class="content-block-title nonefound" style="margin: 0 auto;margin-top:10px;text-align:center;">No Matches Yet</div>');
}
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$('.nonefound').remove();
var objs = snapshot.val();
var obg = [];
$.each(objs, function(i, obk) {obg.push (obk)});
//console.log(obg);
function compare(a,b) {
if (a.timestamp > b.timestamp)
return -1;
if (a.timestamp < b.timestamp)
return 1;
return 0;
}
obg.sort(compare);
$.each(obg, function(i, obj) {
var typetype = obj.type.substring(0, 4);
var correctimage;
var correctname;
var iconhtml;
var colordot;
var message_text;
var func;
var picturesrc;
var mediaicon;
var dateseenresponse;
if (typetype == 'date') {mediaicon = fdateicon;}
if (typetype == 'duck') {mediaicon = fduckicon;}
//need to see if a match still and then create function based on tha
var timestamptitle;
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - obj.timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = '1 minute ago';}
else if (tunixminago == 1) {timestamptitle = '1 minute ago';}
else if (tunixminago < 2) {timestamptitle = '1 minute ago';}
else if (tunixminago < 60) {timestamptitle = Math.round(tunixminago)+' minutes ago';}
else if (tunixminago == 60) {timestamptitle = '1 hour ago';}
else if (tunixminago < 120) {timestamptitle = '1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = '1 day ago';}
else if (tunixminago < 2880) {timestamptitle = '1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = Math.round(tunixminago / 1440) +' days ago';}
else if (tunixminago == 10080) {timestamptitle = '1 week ago';}
else if (tunixminago < 20160) {timestamptitle = '1 week ago';}
else if (tunixminago >= 20160) {timestamptitle = Math.round(tunixminago / 10080) +' weeks ago';}
else if (tunixminago == 525600) {timestamptitle = '1 week ago';}
else if (tunixminago < (525600*2)) {timestamptitle = '1 week ago';}
else if (tunixminago >= (525600*2)) {timestamptitle = Math.round(tunixminago / 525600) +' years ago';}
// onclick="singleBrowser('+targetid+')"
if (obj.param=='message'){message_text = obj.message; iconhtml = '<i class="pe-7s-mail pe-lg" style="margin-right:5px;z-index:9999;"></i>'}
if (obj.param=='image'){
if (obj.from_uid == f_uid){message_text = obj.message + 'sent';}
else {message_text = obj.message + 'received';}
iconhtml = '<i class="pe-7s-camera pe-lg" style="margin-right:5px;z-index:9999;"></i>';}
if (obj.param=='daterequest'){
if (obj.from_uid == f_uid){message_text = obj.message + ' sent';}
else {message_text = obj.message + ' received';}
iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='datedeleted'){
if (obj.from_uid == f_uid){message_text = obj.message;}
else {message_text = obj.message;}
iconhtml = '<i class="pe-7s-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='newmatch'){
if (obj.from_uid == f_uid){message_text = obj.message;}
else {message_text = obj.message;}
iconhtml = '<i class="pe-7s-like pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
if (obj.param=='dateconfirmed'){
message_text = obj.message;
iconhtml = '<i class="pe-7f-date pe-lg" style="margin-right:5px;z-index:9999;"></i>';
}
// if(obj.received=='N' && (obj.param=='datedeleted' || obj.param=='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'ssage_count+'</span>';} else{colordot = '';}
// if(obj.received=='N' && (obj.param!='datedeleted' && obj.param!='newmatch')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';} else{colordot = '';}
if(obj.received=='N' && (obj.param=='message' || obj.param=='image')){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;">'+obj.new_message_count+'</span>';}
else if(obj.received=='N'){colordot = '<span class="badge" style="background-color:#2196f3;margin-top:5px;margin-left:5px;width:12px;height:12px;"></span>';}
else{colordot = '';}
if (obj.from_uid == f_uid){correctimage = String(obj.to_uid);correctname = String(obj.to_name);colordot = '';}
else {correctimage = String(obj.from_uid);correctname = String(obj.from_name);image_after = 'received';}
datemeinarray=0;
duckmeinarray=0;
datetoinarray=0;
ducktoinarray=0;
if (obj.from_uid == f_uid){picturesrc = obj.to_picture;}
else{picturesrc = obj.from_picture;}
var datesto = f_to_date.indexOf(correctimage);
if (datesto > -1) {
datetoinarray=1;
}
var datesme = f_date_me.indexOf(correctimage);
if (datesme > -1) {
datemeinarray=1;
}
var duckto = f_to_duck.indexOf(correctimage);
if (duckto > -1) {
ducktoinarray=1;
}
var duckme = f_duck_me.indexOf(correctimage);
if (duckme > -1) {
duckmeinarray=1;
}
if ((datemeinarray==1 && datetoinarray==1) || (duckmeinarray==1 && ducktoinarray==1)) {
if (typetype == 'date') {func = 'createDate1';}
if (typetype == 'duck') {func = 'createDuck';}
}
else{func = 'singleUser'}
mynotifs.push({
title: message_text,
targetid:correctimage,
targetname:correctname,
picture:picturesrc,
from_name: obj.from_name,
to_name: obj.to_name,
from_uid: obj.from_uid,
to_uid: obj.to_uid,
icon:iconhtml,
colordot:colordot,
func:func,
type:typetype,
timestamptitle:timestamptitle
});
});
var notif2load = mynotifs.length;
if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;}
for (i = 0; i < notifletsload; i++) {
myList.appendItem({
title: mynotifs[i].title,
targetid:mynotifs[i].targetid,
targetname:mynotifs[i].targetname,
picture:mynotifs[i].picture,
from_name: mynotifs[i].from_name,
to_name: mynotifs[i].to_name,
from_uid:mynotifs[i].from_uid,
to_uid: mynotifs[i].to_uid,
icon:mynotifs[i].icon,
colordot:mynotifs[i].colordot,
func:mynotifs[i].func,
type:mynotifs[i].type,
timestamptitle:mynotifs[i].timestamptitle
});
}
}
});
}
function rightPanel(){
$('.timeline-upcoming').empty();
myApp.sizeNavbars();
var rightdates = [];
var month = [];
month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";
month[3] = "APR";
month[4] = "MAY";
month[5] = "JUN";
month[6] = "JUL";
month[7] = "AUG";
month[8] = "SEP";
month[9] = "OCT";
month[10] = "NOV";
month[11] = "DEC";
var weekday = [];
weekday[0] = "SUN";
weekday[1] = "MON";
weekday[2] = "TUE";
weekday[3] = "WED";
weekday[4] = "THU";
weekday[5] = "FRI";
weekday[6] = "SAT";
var timelinedates = firebase.database().ref('/dates/' + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
$('.timeline-upcoming').empty();
if (snapshot.val() === null){
$('.timeline').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;">Calendar is empty</div>');
}
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
rightdates.push(obj);
});
rightdates.sort(compare);
for (i = 0; i < rightdates.length; i++) {
var correctname;
var correctid;
var picturesrc;
if (rightdates[i].created_uid == f_uid) {picturesrc = rightdates[i].to_picture;correctname = rightdates[i].received_name;correctid = rightdates[i].received_uid;}
if (rightdates[i].created_uid != f_uid) {picturesrc = rightdates[i].from_picture;correctname = rightdates[i].created_name;correctid = rightdates[i].created_uid;}
var unix = Math.round(+new Date()/1000);
var c = new Date(rightdates[i].chat_expire*1000 - 1);
var cday = weekday[c.getDay()];
if ((rightdates[i].created_uid == f_uid || rightdates[i].received_uid == f_uid) && (rightdates[i].chat_expire > Number(unix)) ){
var d = new Date(rightdates[i].chat_expire*1000 - 3600);
var timehere;
if (rightdates[i].time) {timehere = ', ' + rightdates[i].time;}
else {timehere='';}
var timestamptitle;
var datetype = rightdates[i].type.capitalize();
var datesidetitle;
var dayday = d.getDate();
var monthmonth = month[d.getMonth()];
var subtitletext,confirmtext;
if (rightdates[i].response =='Y') {
if (rightdates[i].type=='date' ){datesidetitle = 'Date';}
if (rightdates[i].type=='duck' ){datesidetitle = 'Duck';}
timestamptitle = datesidetitle + ' Confirmed';
var name_accepted;
if (rightdates[i].received_uid == f_uid) {name_accepted = 'you ';}
else {name_accepted = rightdates[i].received_name;}
subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#4cd964;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-check pe-lg" style="color:white"></i></div>';
confirmtext='Date confirmed by '+name_accepted+' on '+cday;
}
if (rightdates[i].response =='W') {
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - rightdates[i].timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = 'Sent now';}
else if (tunixminago == 1) {timestamptitle = 'Sent 1 min ago';}
else if (tunixminago < 2) {timestamptitle = 'Sent 1 min ago';}
else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' mins ago';}
else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 120) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';}
if (rightdates[i].created_uid == f_uid) {confirmtext = 'Waiting for '+rightdates[i].received_name+' to respond.';}
if (rightdates[i].created_uid != f_uid){confirmtext = rightdates[i].created_name + ' is waiting for your response.';}
if (rightdates[i].type=='date' ){datesidetitle = 'Date Request';}
if (rightdates[i].type=='duck' ){datesidetitle = 'Duck Request';}
subtitletext='<div style="font-family: \'Pacifico\', cursive;font-size:17px;background-color:#ff9500;color:white;width:100%;text-align:center;padding-top:5px;padding-bottom:5px;"><i class="pe-7s-help1 pe-lg" style="color:white"></i></div>';}
if ($(".time_line_" + dayday)[0]){
} else {
$('.timeline').append('<div class="timeline-item" style="margin-bottom">'+
'<div class="timeline-item-date" style="margin-right:10px;">'+cday+'<br/>'+dayday+' <small> '+monthmonth+' </small></div>'+
//'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content time_line_'+dayday+'">'+
'</div>'+
'</div>');
}
$('.time_line_'+dayday).append(
'<a href="#" onclick="createDate(\''+correctid+'\',\''+correctname+'\')">'+
subtitletext+
// '<div class="timeline-item-time" style="padding:2px;margin-top:0px;background-color:white;border-bottom:1px solid #c4c4c4;text-align:center;padding-top:10px;"><i class="pe-7s-clock pe-lg"></i> //'+weekday[d.getDay()]+ timehere+'<div style="clear:both;" id="interestdatediv_'+correctid+'"></div></div>'+
'<div class="timeline-item-inner" style="min-width:136px;padding:7px;border-radius:0;">'+
'<div class="timeline-item-title" style="color:black;margin-top:5px;text-align:center;"><div style="width:50px;height:50px;margin:0 auto;border-radius:50%;background-size:cover;background-position:50% 50%;background-image:url(\''+picturesrc+'\')"></div><span style="clear:both;">'+correctname+'<span> </div>'+
// '<div style="padding:10px;font-size:13px;"><span style="color:#6d6d72;clear:both;padding-top:-5px;">'+confirmtext+'</span></div>'+
'<div style="text-align:center;clear:both;width:100%;color:#8e8e93;">'+timestamptitle+'</div>'+
'</div>'+
'</a>'
);
if(rightdates[i].type=='date'){
//for (k = 0; k < rightdates[i].interest.length; k++) {
// $( "#interestdatediv_" + correctid).append('<a href="#" style="margin-right:5px"><i class="twa twa-'+rightdates[i].interest[k]+'" style="margin-top:5px;margin-right:5px"></i></a>');
// }
}
}
}
}
});
}
function newAm(){
$( ".originalam" ).hide();
$( ".newam" ).show();
pickerDescribe.open();
}
function newMe(){
$( ".originalme" ).hide();
$( ".newme" ).show();
pickerDescribe2.open();
}
var deletedphoto;
function getData(){
deletedphoto = false;
if(photosloaded === false){
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/userdata.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
var result = JSON.parse(data);
//console.log(result);
if (result!='77' && result[0].largeurl){
$( ".reorderbutton" ).removeClass('disabled');
$( ".deleteallbutton" ).removeClass('disabled');
f_smallurls = result[0].smallurl.split(',');
f_largeurls = result[0].largeurl.split(',');
//console.log(result[0].widthslides);
//console.log(result[0].heightslides);
addedwidth = result[0].widthslides.split(',');
addedheight = result[0].heightslides.split(',');
$( ".photosliderinfo" ).addClass('pictures');
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
for (i = 0; i < f_largeurls.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()">Remove</div></div>');
}
myswiperphotos = myApp.swiper('.container-photos', {
pagination:'.swiper-pagination',
paginationType:'progress',
direction:'vertical',
onInit:function(swiper){$( ".photoswiperloader" ).hide();},
onClick:function(swiper, event){
}
});
}
else {
f_smallurls = [];
f_largeurls = [];
addedheight = [];
addedwidth = [];
$( ".wrapper-photos" ).append('<div class="swiper-slide firsthere" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos = myApp.swiper('.container-photos', {
pagination:'.swiper-pagination',
paginationType:'progress',
onInit:function(swiper){$( ".photoswiperloader" ).hide();},
direction:'vertical'
});
}
});
}).catch(function(error) {
// Handle error
});
}
if (photosloaded === true){myswiperphotos.update();}
photosloaded = true;
}
function deleteIndividual(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
if ($( ".photosliderinfo" ).hasClass('pictures')){
myApp.confirm('Are you sure?', 'Delete Photo', function () {
myswiperphotos.removeSlide(myswiperphotos.clickedIndex);
f_largeurls.splice(myswiperphotos.clickedIndex, 1);
f_smallurls.splice(myswiperphotos.clickedIndex, 1);
addedwidth.splice(myswiperphotos.clickedIndex, 1);
addedheight.splice(myswiperphotos.clickedIndex, 1);
//console.log(addedwidth);
//console.log(addedheight);
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
deletedphoto = true;
myswiperphotos.update();
if (myswiperphotos.slides.length > 0){
firebase.database().ref('users/' + f_uid).update({
image_url:f_largeurls[0],
photoresponse:'Y'
}).then(function() {});
}
if (myswiperphotos.slides.length === 0){
firebase.database().ref('users/' + f_uid).update({
image_url:f_image,
photoresponse:'N'
}).then(function() {});
$( ".reorderbutton" ).addClass('disabled');
$( ".deleteallbutton" ).addClass('disabled');
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos.updatePagination();
myswiperphotos.update();
}
});
}
else {
photosPopup();
}
}
function openAvaill(availtime){
if ($( '.li_'+ availtime ).hasClass('selecrec')){$( '.li_'+ availtime ).removeClass('selecrec');$( '.li_'+ availtime ).css('selecrec','');$( '#picker'+ availtime ).val('');}
else{$( '.li_'+ availtime ).addClass('selecrec');$( '#picker'+ availtime ).val('Now');}
}
function openAvail(availtime){
$( '.li_'+ availtime ).addClass('selecrec');
}
function removeAvail(availtime,availname,availnameonly){
$( '.li_'+ availtime ).removeClass('selecrec');
$('#picker'+availtime ).remove();
$('.readd_'+availtime ).append('<input type="text" placeholder="'+availname+'" readonly id="picker'+availtime+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li>');
myApp.picker({
input: '#picker' + availtime,
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeAvail(\''+availtime+'\',\''+availname+'\',\''+availnameonly+'\');">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: (availnameonly + ',').split(',')
},
{
textAlign: 'left',
values: ('Anytime Morning Midday Afternoon Evening').split(' ')
},
]
});
}
var availarray = [];
function report(){
myApp.prompt('What is the problem?', 'Report '+targetname, function (value) {
if (value.length ===0){myApp.alert('You must provide a reason to report ' + targetname, 'What is the problem?');return false;}
targetreported = true;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:value,
response:'N',
timestamp: t_unix,
};
var updates = {};
updates['reports/' + f_uid + '/' + targetid + '/' + newPostKey] = targetData;
if (f_uid == first_number){
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
firstnumberreport:newPostKey,
firstnumberreporttime:t_unix
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
firstnumberreport:newPostKey,
firstnumberreporttime:t_unix
});
}
else{
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
secondnumberreport:newPostKey,
secondnumberreporttime:t_unix
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
secondnumberreport:newPostKey,
secondnumberreporttime:t_unix
});
}
return firebase.database().ref().update(updates).then(function() {
myApp.alert('We will review your report. We encourage you to block offensive users.', 'Report sent');});
});
$(".modal-text-input").prop('maxlength','50');
}
function more(){
var swiperno = 0;
myApp.confirm('Are you sure?', 'Block '+targetname, function () {
var blockindex = myPhotoBrowser.swiper.activeIndex;
targetid = new_all[blockindex].id;
myPhotoBrowser.swiper.removeSlide(blockindex);
myPhotoBrowser.swiper.updateSlidesSize();
swiperQuestions.removeSlide(blockindex);
swiperQuestions.updateSlidesSize();
new_all = new_all.slice(0,blockindex).concat(new_all.slice(blockindex+1));
if (new_all.length>0){
for (var i = 0; i < random_all.length; i++) {
if (random_all[i].id == targetid){
randomswiper.removeSlide(i);
randomswiper.updateSlidesSize();
random_all = random_all.slice(0,i).concat(random_all.slice(i+1));
}
}
for (var i = 0; i < nearby_all.length; i++) {
if (nearby_all[i].id == targetid){
nearbyswiper.removeSlide(i);
nearbyswiper.updateSlidesSize();
nearby_all = nearby_all.slice(0,i).concat(nearby_all.slice(i+1));
}
}
for (var i = 0; i < recent_all.length; i++) {
if (recent_all[i].id == targetid){
recentswiper.removeSlide(i);
recentswiper.updateSlidesSize();
recent_all = recent_all.slice(0,i).concat(recent_all.slice(i+1));
}
}
}
else {
randomswiper.removeAllSlides();
nearbyswiper.removeAllSlides();
recentswiper.removeAllSlides();
randomswiper.destroy();
nearbyswiper.destroy();
recentswiper.destroy();
new_all = [];
random_all = [];
nearby_all = [];
recent_all = [];
}
var firstpos;
var lastpos;
myApp.closeModal('.actions-modal');
allowedchange = false;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var theirnotifs = firebase.database().ref('notifications/' + targetid + '/' + f_uid);
theirnotifs.remove().then(function() {
//console.log("their notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("their notifs failed: " + error.message)
});
var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
mynotifs.remove().then(function() {
//console.log("my notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("my notifs failed: " + error.message)
});
var theirdates = firebase.database().ref('dates/' + targetid + '/' + f_uid);
theirdates.remove().then(function() {
//console.log("their dates Remove succeeded.")
})
.catch(function(error) {
//console.log("their dates failed: " + error.message)
});
var mydates = firebase.database().ref('dates/' + f_uid + '/' + targetid);
mydates.remove().then(function() {
//console.log("my dates Remove succeeded.")
})
.catch(function(error) {
//console.log("my dates failed: " + error.message)
});
var ourchats = firebase.database().ref('chats/' + first_number + '/' + second_number);
ourchats.remove().then(function() {
//console.log("Chats Remove succeeded.")
})
.catch(function(error) {
//console.log("Chats Remove failed: " + error.message)
});
var ourphotochats = firebase.database().ref('photochats/' + first_number + '/' + second_number);
ourphotochats.remove().then(function() {
//console.log("PhotoChats Remove succeeded.")
})
.catch(function(error) {
//console.log("PhotoChats Remove failed: " + error.message)
});
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
secondnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
secondnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
firstnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
second_name:targetname,
second_number:second_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
firstnumberblock:'Y',
created:f_uid,
received:targetid,
first_number:first_number,
second_name:targetname,
second_number:second_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
firstnumberdate:'N',
firstnumberduck:'N'
});
}
if (new_all.length>1){
if (blockindex == (new_all.length-1)){lastpos = 'Y';} else {lastpos ='N';}
if (blockindex == 0){firstpos = 'Y';} else{firstpos ='N';}
if (firstpos == 'Y'){myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();swiperQuestions.slideNext();swiperQuestions.slidePrev(); }
else if (lastpos == 'Y'){myPhotoBrowser.swiper.slidePrev();allowedchange = true;myPhotoBrowser.swiper.slideNext();swiperQuestions.slidePrev();swiperQuestions.slideNext(); }
else {myPhotoBrowser.swiper.slideNext();allowedchange = true;myPhotoBrowser.swiper.slidePrev();swiperQuestions.slideNext();swiperQuestions.slidePrev(); }
}
//myPhotoBrowser.swiper.slideTo(blockindex);
// console.log(all_matches_photos[swipertarget]);
// console.log(new_all);
if (new_all.length === 0){
myPhotoBrowser.close();myApp.closeModal();
$( ".home-title" ).hide();
$( ".results-loader" ).hide();
$('.content-here').append(
'<div class="no-results-div" style="background-color:white;z-index:30000000;text-align:center;margin:0 auto;width:300px;position:absolute;top:50%;left:50%;margin-left:-150px;margin-top:-70px;">'+
'<img src="media/datetongue.png" onload="showtext()" style="width:120px;margin:0 auto;">'+
'<div style="display:none;" class="showtext"><h3>No one found nearby</h3><p style="padding-top:0px;margin-top:-10px;">Try changing your search radius </br> or age range.</p></br></div>'+
'</div>');
}
// myPhotoBrowser.swiper.slideTo(blockindex);
if (new_all.length===1){
$( ".availyo_"+ new_all[0].id ).show();
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var targetdescription= new_all[0].description;
targetname = new_all[0].name;
var targetage = new_all[0].age;
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
}
if (new_all.length>0){
checkMatch(targetid);
}
});
}
var canscrollnotif = true;
function scrollNotifications(){
//console.log($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top);
if ((($( ".virtual-notifications" ).height() + $( ".virtual-notifications" ).offset().top) - 1 < $( document ).height())&& (canscrollnotif)) {
if (notifletsload < 12){$( "#notiflistdiv" ).append('<div class="loadnotifsloader" style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;"><div class="preloader " style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv");
objDiv.scrollTop = objDiv.scrollHeight;
setTimeout(function(){ $( ".loadnotifsloader" ).remove();objDiv.scrollTop = objDiv.scrollHeight-44;}, 2000);
}
else{$( "#notiflistdiv" ).append('<div style="clear:both;width:100%;padding-top:5px;padding-bottom:5px;background-color:#efeff4;clear:both;" class="loadnotifsloader"><div class="preloader" style="width:20px;margin:0 auto;margin-top:5px;margin-left:125px;"></div></div>');canscrollnotif = false;var objDiv = document.getElementById("notiflistdiv");
objDiv.scrollTop = objDiv.scrollHeight;setTimeout(function(){ getmoreNotifs();}, 2000);}
}
}
function scrollMessages(){
if ((($( ".scrolldetect" ).offset().top) == 120) && (canloadchat)) {if (letsload < 20 || existingmessages < 20){$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ $( ".loadmessagesloader" ).hide(); }, 500);}else{$( ".scrolldetect" ).prepend('<div class="preloader loadmessagesloader" style="width:20px;margin:0 auto;margin-top:10px;"></div>');canloadchat = false;setTimeout(function(){ getPrevious(); }, 500);}}
}
function showDecide(){
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
$( ".toolbardecide" ).show();
}
function closeCreate(){
myApp.closeModal('.actions-modal');
myApp.closeModal('.chatpop');
singlefxallowed = true;
}
function createDate(messageid,messagename,redirect){
if (redirect===0) {}
else { if ($('.chatpop').length > 0){return false;}}
var centerdiv;
if (messageid) {targetid = messageid;}
if (messagename) {targetname = messagename;}
singleUser(targetid,targetname,88);
existingchatnotifications = firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.to_uid == f_uid) && (obj.from_uid == targetid) && (obj.received=='N')){
cordova.plugins.notification.badge.get(function (badge) {
var newcount = badge-obj.new_message_count;
if (newcount < 1){
$( ".notifspan" ).hide();
}
else {
$( ".notifspan" ).show();
$( ".notifspan" ).addClass('notifbounce');
setTimeout(function(){ $( ".notifspan" ).removeClass('notifbounce'); }, 5000);
}
});
firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
}
});
}
});
if (messageid) {centerdiv = '<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;"><div class="navbarphoto"></div>'+targetname+'</div>';}
else{centerdiv = '<div class="center center-date close-popup" onclick="clearchatHistory();"><div class="navbarphoto"></div>'+targetname+'</div>';}
var divcentrecontent;
if (redirect === 0){divcentrecontent='<div class="center center-date" onclick="singleUser(\''+targetid+'\',\''+targetname+'\')" style="cursor:pointer;color:white;"><div class="navbarphoto"></div>'+targetname+'</div>';}
else {divcentrecontent='<span id="centerholder" style="color:white;z-index:99999999999999999999999999999999;color:white;"></span>';}
var popupHTML = '<div class="popup chatpop">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<a href="#" class="link icon-only date-back" onclick="closeCreate()" style="margin-left:-10px;color:white;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date-close" onclick="reverseRequest();" style="color:white;font-weight:bold;display:none;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date2-close" onclick="noChange();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'<a href="#" class="link icon-only date1-close" onclick="reverseRequest();dateConfirmationPage();" style="color:white;display:none;font-weight:bold;margin-left:-10px;"> <i class="pe-7s-angle-left pe-3x"></i> </a>'+
'</div>'+
divcentrecontent+
' <div class="right" onclick="actionSheet()" style="font-size:14px;">'+
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor" style="color:white"></i>'+
' </a></div>'+
'</div>'+
'</div>'+
'<div class="pages" style="margin-top:-44px;">'+
'<div data-page="datepopup" class="page">'+
'<div class="toolbar messagebar datetoolbar" style="display:none;background-color:transparent;">'+
' <div class="toolbar-inner yes-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px;display:none;text-align:center;">'+
'<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 33%;"><span style="margin: 0 auto;">Cancel</span></a>'+
'<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width:33%;"><span style="margin: 0 auto;">Change</span></a>'+
'<a href="#" onclick="acceptDate()" class="link" style="height:44px;color:white;background-color:#4cd964;width:33%;"><span style="margin: 0 auto;">Confirm</span></a>'+
'</div>'+
' <div class="toolbar-inner sender-inner" style="background-color:rgba(247, 247, 248,0.9);margin-top:-10px;height:54px;padding-bottom:10px; display:none;text-align:center;">'+
'<a href="#" onclick="cancelDate()" class="link" style="height:44px;color:white;background-color:#ff3b30;width: 50%;"><span style="margin: 0 auto;">Cancel</span></a>'+
'<a href="#" onclick="request()" class="link" style="height:44px;color:white;background-color:#2196f3;width: 50%;"><span style="margin: 0 auto;">Change</span></a>'+
'</div>'+
' <div class="toolbar-inner date-inner" style="padding-left:0px;padding-right:0px;display:none;text-align:center;background-color:white;border-top:1px solid #2196f3;">'+
'<input id="datemessageq" placeholder="Add message..(optional)" style="width: calc(100% - 70px);margin-left:5px;background-color:white;max-height:44px;border-color:transparent;" type="text">'+
'<a href="#" style="z-index:99999999;height:44px;background-color:#2196f3;float:left;line-height:44px;width:70px;" onclick="processDupdate();"><span style="margin: 0 auto;padding-right:10px;padding-left:10px;color:white;">Send</span></a>'+
'</div>'+
' <div class="toolbar-inner message-inner" style="display:none;background-color:white;padding-left:0px;padding-right:0px;border-top:1px solid #2196f3;">'+
'<a href="#" class="link icon-only" style="margin-left:5px;"><i class="pe-7s-camera pe-lg" style="color:#2196f3;font-size:28px;"></i><i class="twa twa-bomb" style="z-index:999;margin-left:-10px;margin-top:-15px;"></i></a> <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:54px;width:50px;z-index:1;opacity:0;margin-top:-12px;margin-left:-50px;"><textarea id="messagebararea messagearea" type="text" placeholder="Type your message.." style="border-color:transparent;"></textarea><a href="#" class="link sendbutton" onclick="sendMessage();" style="margin-right:10px;margin-left:10px;">Send</a>'+
'</div>'+
'</div>'+
'<div class="datedetailsdiv date-button" onclick="noMessages();setDate();dateConfirmationPage(1);" style="display:none;position:absolute;top:44px;text-align:center;height:44px;width:100%;z-index:999999;">'+
'</div>'+
'<div class="page-content messages-content" onscroll="scrollMessages();" id="messagediv" style="background-color:#f7f7f8">'+
'<span class="preloader login-loader messages-loader" style="width:42px;height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;"></span>'+
'<div class="datearea" style="text-align:center;"></div>'+
'<div class="messages scrolldetect" style="margin-top:100px;">'+
'</div></div></div>'+
'</div></div>';
myApp.popup(popupHTML);
var closedvar = $$('.chatpop').on('popup:close', function () {
clearchatHistory();
});
//existingDate();
//setDate();
$( "#centerholder" ).append(centerdiv);
myApp.sizeNavbars();
//$( "#centerholder" ).remove();
if (datealertvar === false) {
datealertvar = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
datealert = firebase.database().ref("dates/" + f_uid +'/' + targetid).on('value', function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists) {
var unix = Math.round(+new Date()/1000);
if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) {
d_type = snapshot.child('type').val();
d_chat_expire = snapshot.child('chat_expire').val();
d_interest = snapshot.child('interest').val();
d_day = snapshot.child('day').val();
d_time = snapshot.child('time').val();
d_response = snapshot.child('response').val();
if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();}
d_created_uid = snapshot.child('created_uid').val();
d_timestamp = snapshot.child('timestamp').val();
d_dateseen = snapshot.child('dateseen').val();
d_dateseentime = snapshot.child('dateseentime').val();
d_message = snapshot.child('message').val();
var newtonight = new Date();
newtonight.setHours(23,59,59,999);
var newtonight_timestamp = Math.round(newtonight/1000);
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var chatdaystring;
var expiredateobject = new Date((d_chat_expire * 1000) - 86400);
var unixleft = d_chat_expire - newtonight_timestamp;
var daysleft = unixleft / 86400;
//console.log('daysleft' + daysleft);
var weekdaynamew = weekday[expiredateobject.getDay()];
if(daysleft <= 0){chatdaystring = 'Today';}
else if(daysleft === 1){chatdaystring = 'Tomorrow';}
else chatdaystring = weekdaynamew;
//console.log(unixleft);
//console.log(daysleft);
var hoursleft = unixleft / 3600;
var salut;
if (daysleft <=0){
salut='tonight';
}
else if (daysleft ==1) {salut = 'in ' + Math.round(daysleft)+' day';}
else{salut = 'in ' + daysleft+' days';}
var aftertag;
$( ".datedetailsdiv" ).empty();
$( ".datedetailsdiv" ).append('<div class="list-block media-list" style="margin-top:0px;border-bottom:1px solid #c4c4c4;">'+
'<ul style="background-color:#4cd964">'+
'<li>'+
' <div class="item-content" style="padding-left:15px;">'+
'<div class="item-media">'+
'<img src="media/'+d_type+'faceonly.png" style="height:36px;">'+
'</div>'+
'<div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title" style="font-size:15px;color:white;">See you <span class="chatdaystringdiv">'+chatdaystring+'</span><span class="chatafternavbar"></span></div>'+
' <div class="item-after" style="margin-top:-10px;margin-right:-15px;color:white;"><i class="pe-7s-angle-right pe-3x"></i></div>'+
' </div>'+
'<div class="item-subtitle" style="font-size:12px;text-align:left;color:white;">Chat will end '+salut+' (at midnight)</div>'+
// '<div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div> ' );
if (d_time){
var lowertime = d_time.toLowerCase()
if (chatdaystring == 'today'){$( ".chatdaystringdiv").empty();$( ".chatafternavbar").append('this ' + lowertime);}
else {
$( ".chatafternavbar").append(' ' + d_time);}
}
//if (d_interest && d_type =='duck'){
// if ((d_interest == 'my') && (d_created_uid == f_uid)){aftertag = 'At '+f_first+'\'s place';}
// if ((d_interest == 'your') && (d_created_uid == f_uid)){aftertag = 'At '+targetname+'\'s place';}
//}
//if (d_interest && d_type =='date'){
//for (i = 0; i < d_interest.length; i++) {
// $( ".chatafternavbar").append('<a href="#" style="margin-left:5px"><i class="twa twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>');
//}
//}
if (d_response == 'Y') {chatShow();}
else {
noMessages();
setDate();
dateConfirmationPage();
}
$( ".messages-loader" ).hide();
}
else{
cancelDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
}
else{
d_interest = false;
d_chat_expire = false;
d_day = false;
d_time = false;
d_response = false;
d_timeaccepted = false;
d_timestamp = false;
d_message = false;
d_dateseen = false;
d_dateseentime = false;
if (keepopen === 0){myApp.closeModal('.chatpop');clearchatHistory();}
noMessages();
setDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
//need to check if still matched
}
//alert('triggered');
// if (snapshot.val().response == 'W') {noMessages();
// setDate();dateConfirmationPage();}
// else {chatShow();}
//dateConfirmationPage();
keepopen = 0;
});
}
else {}
}
function scrollBottom(){
var objDiv = document.getElementById("messagediv");
objDiv.scrollTop = objDiv.scrollHeight;
//$("").animate({ scrollTop: $('#messagediv').prop("scrollHeight")}, 300);
}
function noMessages(){
$( ".messages" ).hide();
$( ".datearea" ).empty();
$( ".datearea" ).append(
'<div class="nomessages" style="margin:0 auto;margin-top:44px;text-align:center;background-color:white;">'+
//'<div class="profileroundpic" style="margin:0 auto;margin-top:5px;height:70px;width:70px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
'<div class="dateheader" style="display:none;background-color:#ccc;padding:11px;text-align:center;font-size:24px;color:white;font-family: \'Pacifico\', cursive;"></div>'+
'<div class="requesticon" style="padding-top:20px;"></div>'+
'<a href="#" onclick="request()" class="button dr requestbutton" style="width:150px;margin: 0 auto;margin-top:10px;font-family: \'Pacifico\', cursive;font-size:20px;"></a>'+
'<div class="dr infop" style="padding:10px;background-color:white;color:#666;"><h3 class="titleconfirm" style="margin-top:10px;display:none;"></h3><p class="infoconfirm">Once you agree on a time to meet you can send instant chat messages to each other.</p></div>'+
'<div class="waitingreply"></div>'+
'<div id="createdatepicker" style="clear:both;border-bottom:1px solid #c4c4c4;margin-top:10px;"></div>'+
'<div class="row date-row" style="display:none;clear:both;margin-top:5px;padding:10px;background-color:#white;">'+
' <div class="col-16.67 coffee_i interestbutton" onclick="interests(\'coffee\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-coffee" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 beers_i interestbutton" onclick="interests(\'beers\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-beers" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 wine-glass_i interestbutton" onclick="interests(\'wine-glass\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-wine-glass" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 movie-camera_i interestbutton" onclick="interests(\'movie-camera\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-movie-camera" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 tada_i interestbutton" onclick="interests(\'tada\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-tada" style="margin-top:5px;"></i></div>'+
' <div class="col-16.67 fork-and-knife_i interestbutton" onclick="interests(\'fork-and-knife\');" style="cursor:pointer;border-radius:5px;"><i class="twa twa-2x twa-fork-and-knife" style="margin-top:5px;"></i></div>'+
'</div> '+
'<div class="row duck-row" style="display:none;clear:both;margin-top:10px;">'+
'<div class="buttons-row" style="width:100%;padding-left:10px;padding-right:10px;">'+
' <a href="#tab1" class="button button-big button-place button-my" onclick="duckClass(1);">My Place</a>'+
'<a href="#tab2" class="button button-big button-place button-your" onclick="duckClass(2);">Your Place</a>'+
'</div>'+
'</div> '+
'<div class="profileyomain profileyo_'+ targetid+'" style="border-top:1px solid #c4c4c4;"></div>'+
'<span class="preloader preloader-white avail-loader" style="margin-top:20px;clear:both;margin-bottom:10px;"></span>'+
'</div>');
if (d_type == 'date') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargedateicon);$( ".requestbutton" ).text('Request Date');$( ".dateheader" ).text('Let\'s Date');}
if (d_type == 'duck') {$( ".requesticon" ).empty();$( ".requesticon" ).append(flargeduckicon);$( ".requestbutton" ).text('Request Duck');$( ".dateheader" ).text('Let\'s Duck');}
}
function setDate(){
var dateset = 'N';
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var n = weekday[d.getDay()];
var alldays_values = [];
var alldays_names = [];
var tonight = new Date();
tonight.setHours(23,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
alldays_values.push(tonight_timestamp - 1);
alldays_values.push(tonight_timestamp);
alldays_names.push('Now');
alldays_names.push('Today');
var tomorrow_timestamp = tonight_timestamp + 86400;
alldays_values.push(tomorrow_timestamp);
alldays_names.push('Tomorrow');
for (i = 1; i < 6; i++) {
var newunix = tomorrow_timestamp + (86400 * i);
alldays_values.push(newunix);
var dat_number = i + 1;
var datz = new Date(Date.now() + dat_number * 24*60*60*1000);
n = weekday[datz.getDay()];
alldays_names.push(n);
}
pickerCustomToolbar = myApp.picker({
container: '#createdatepicker',
rotateEffect: true,
inputReadOnly: true,
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");},
toolbar:false,
onChange:function(p, value, displayValue){
setTimeout(function(){
var unixnow = Math.round(+new Date()/1000);
var middaystamp = new Date();
middaystamp.setHours(12,00,00,000);
var middaystamp_timestamp = Math.round(middaystamp/1000);
var threestamp = new Date();
threestamp.setHours(12,00,00,000);
var threestamp_timestamp = Math.round(threestamp/1000);
var fivestamp = new Date();
fivestamp.setHours(17,00,00,000);
var fivestamp_timestamp = Math.round(fivestamp/1000);
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Morning') && (unixnow>middaystamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Mid-day') && (unixnow>threestamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
if ((pickerCustomToolbar.cols[0].displayValue == 'Today') && (pickerCustomToolbar.cols[1].displayValue == 'Afternoon') && (unixnow>fivestamp_timestamp)){pickerCustomToolbar.cols[1].setValue('');}
}, 1000);
if (p.cols[0].displayValue == 'Now' && (dateset == 'Y')){p.cols[1].setValue('');}
},
cols: [
{
displayValues: alldays_names,
values: alldays_values,
},
{
textAlign: 'left',
values: (' Morning Afternoon Midday Evening').split(' ')
},
]
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid);
ref.once("value")
.then(function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists){
var timecol = pickerCustomToolbar.cols[1];
timecol.setValue(snapshot.child('time').val());
var daycol = pickerCustomToolbar.cols[0];
daycol.setValue(snapshot.child('chat_expire').val());
}
dateset = 'Y';
if (d_interest && d_type =='date') {
for (i = 0; i < d_interest.length; i++) {
$( "." + d_interest[i] +"_i" ).addClass('interestchosen');
}
}
if (d_interest && d_type =='duck') {
if (d_interest == 'my' && d_created_uid == f_uid){ $( ".button-my" ).addClass("active");}
if (d_interest == 'my' && d_created_uid != f_uid){{ $( ".button-your" ).addClass("active");}}
if (d_interest == 'your' && d_created_uid == f_uid){{ $( ".button-your" ).addClass("active");}}
if (d_interest == 'your' && d_created_uid != f_uid){{ $( ".button-my" ).addClass("active");}}
}
});
$( "#createdatepicker" ).hide();
}
function infoPopup(){
var popupHTML = '<div class="popup">'+
'<div class="content-block">'+
'<p>Popup created dynamically.</p>'+
'<p><a href="#" class="close-popup">Close me</a></p>'+
'</div>'+
'</div>';
myApp.popup(popupHTML);
}
function dateUser(){
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
if ($( ".duckbutton" ).hasClass( "active" )&& $( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();}
if (
$( ".datebutton" ).hasClass( "active" )){$( ".datebutton" ).removeClass( "active" );
$( ".notifback" ).show();
$( ".mainback" ).hide();
if ($( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();}
removetoDate();
}
else{
if ($( ".datebutton" ).hasClass( "likesme" )){matchNotif();}
//clicked date
$( ".datebutton" ).addClass( "active" );$( ".duckbutton" ).removeClass( "active" );
addtoDate();
}
}
function addtoDate(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'Y',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'Y',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'Y',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'Y',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
}
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if ($('.photo-browser-slide').length > 1){
var potentialdate = f_date_me.indexOf(targetid);
if (potentialdate == -1) { myPhotoBrowser.swiper.slideNext(true,1000);
if ($('.infopopup').length > 0) {
if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}
}
}
//if button has blue border change the color
}
function removetoDate(){
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
}
function duckUser(){
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
if ($( ".datebutton" ).hasClass( "active" ) && $( ".datebutton" ).hasClass( "likesme" )){unmatchNotif();}
if (
$( ".duckbutton" ).hasClass( "active" )){$( ".duckbutton" ).removeClass( "active" );
if ($( ".duckbutton" ).hasClass( "likesme" )){unmatchNotif();}
$( ".notifback" ).show();
$( ".mainback" ).hide();
removetoDuck();
}
else{
if ($( ".duckbutton" ).hasClass( "likesme" )){matchNotif();}
//clicked duck
$( ".duckbutton" ).addClass( "active" );$( ".datebutton" ).removeClass( "active" );
addtoDuck();
}
}
function removetoDuck(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
}
function markMe(){
var mearray = ["4"];
firebase.database().ref('users/' + f_uid).update({
//add this user to my list
date_me:mearray
});
}
function addtoDuck(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:targetname,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberduck:'Y',
secondnumberdate:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_number:first_number,
second_number:second_number,
second_name:f_name.substr(0,f_name.indexOf(' ')),
secondnumberduck:'Y',
secondnumberdate:'N',
created:f_uid,
received:targetid
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
else {first_number = f_uid;second_number = targetid;
firebase.database().ref('matches/' + f_uid + '/' + targetid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberduck:'Y',
firstnumberdate:'N',
created:f_uid,
received:targetid
});
firebase.database().ref('matches/' + targetid + '/' + f_uid).update({
//add this user to my list
first_number:first_number,
first_name:f_name.substr(0,f_name.indexOf(' ')),
second_number:second_number,
second_name:targetname,
firstnumberduck:'Y',
firstnumberdate:'N',
created:f_uid,
received:targetid
});
}
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if ($('.photo-browser-slide').length > 1){
var potentialduck = f_duck_me.indexOf(targetid);
if (potentialduck == -1) { myPhotoBrowser.swiper.slideNext(true,1000);
if ($('.infopopup').length > 0) {
if(swiperQuestions){comingback = 0; swiperQuestions.slideNext();comingback=1;}}}
}
}
var singleuserarray = [];
function singleUser(idw,idname,origin){
if (singleuserarray[0] != null){
$(".avail-loader").hide();
if (singleuserarray[0].availarraystring !== ''){
$(".availabilitylistblock_"+singleuserarray[0].id).remove();
$(".availtitle").remove();
$( ".profileyo_" + singleuserarray[0].id ).append(
'<div class="content-block-title availtitle" style="padding-top:0px;clear:both;margin-top:15px;">'+targetname+'\'s Availability</div>'+
'<div class="list-block media-list availabilitylistblock_'+singleuserarray[0].id+'" style="z-index:99999999999999;margin-top:0px;clear:both;margin-bottom:-40px;width:100%;">'+
'<ul style="background-color:transparent" style="width:100%;">'+
' </ul></div>');
var availablearrayindividual = JSON.parse(singleuserarray[0].availarraystring);
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){
$( ".availabilitylistblock_"+singleuserarray[0].id ).append(
' <li style="list-style-type:none;width:100%;" onclick="request(\''+availablearrayindividual[k].id+'\',\''+availablearrayindividual[k].time+'\')">'+
'<div class="item-content">'+
'<i class="pe-7s-angle-right pe-3x" style="position:absolute;right:5px;color:#007aff;"></i>'+
'<div class="item-media">'+
'<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+
' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+
' </div>'+
' </div>'+
'</div></li>'
);
}
}
}
if (origin){photoBrowser(0,singleuserarray[0].age,1,1);}
else{photoBrowser(0,singleuserarray[0].age);}
}
else{
if (singlefxallowed === false){return false;}
singlefxallowed = false;
targetid = String(idw);
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/singleuser.php", {projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,latitudep:latitudep,longitudep:longitudep} )
.done(function( data ) {
//console.log(data);
var result = JSON.parse(data);
var availarraystring='';
var availnotexpired = false;
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
if(result[0].availstring && (result[0].availstring != '[]') && (result[0].uid != f_uid)){
var availablearrayindividual = JSON.parse(result[0].availstring);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){availnotexpired = true;}
}
if (availnotexpired){availarraystring = result[0].availstring;}
}
var timestampyear = result[0].timestamp.substring(0,4);
var timestampmonth = result[0].timestamp.substring(5,7);
var timestampday = result[0].timestamp.substring(8,10);
var timestamphour = result[0].timestamp.substring(11,13);
var timestampminute = result[0].timestamp.substring(14,16);
var timestampsecond = result[0].timestamp.substring(17,20);
var timestampunix=(new Date(timestampmonth + '/' + timestampday + '/' + timestampyear + ' ' + timestamphour + ':' + timestampminute + ':' + timestampsecond)).getTime() / 1000 + 64800;
var d_unix = Math.round(+new Date()/1000);
var diff = (d_unix - timestampunix)/60;
var photosstringarray =[];
var photocount;
var photostring;
var profilepicstring;
var photoarrayuserlarge;
var photoarrayusersmall;
if(result[0].largeurl){
var heightarray = result[0].heightslides.split(",");
var widtharray = result[0].widthslides.split(",");
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical" style="height:100%;"><img data-src="' + result[0].largeurl + '" class="swiper-lazy"></div></div>';
photocount = result[0].largeurl.split(",").length;
photoarrayuserlarge = result[0].largeurl.split(",");
photoarrayusersmall = result[0].smallurl.split(",");
profilepicstringlarge = photoarrayuserlarge[0];
profilepicstringsmall = photoarrayusersmall[0];
targetpicture = photoarrayuserlarge[0];
$( ".navbarphoto" ).html(' <div style="width:29px;height:29px;border-radius:50%;background-image:url(\''+profilepicstringlarge+'\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>');
photostring=photostring.replace(/,/g, '" class="swiper-lazy" style="height:100%;"></div></div><div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="')
}
else{
photostring = '<div class="swiper-slide"><div class="swiper-zoom-container zoom-vertical"><img data-src="https://graph.facebook.com/'+targetid+'/picture?width=828" class="swiper-lazy" style="height:100%;"></div></div>';
profilepicstringlarge = 'https://graph.facebook.com/'+targetid+'/picture?width=828&height=828';
profilepicstringsmall = 'https://graph.facebook.com/'+targetid+'/picture?width=368&height=368';
$( ".navbarphoto" ).html(' <div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+targetid+'/picture?width=100&height=100\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>');
targetpicture = 'https://graph.facebook.com/'+targetid+'/picture?width=100&height=100';
photocount = 1;
}
var distance = parseFloat(result[0].distance).toFixed(1);
var distancerounded = parseFloat(result[0].distance).toFixed(0);
if ((distance >= 0) && (distance <0.1)) {distancestring = 'Less than 100 m <span style="font-size:13px;">(328 ft.)</span>'}
if ((distance >= 0.1) && (distance <0.2)) {distancestring = 'Less than 200 m <span style="font-size:13px;">(656 ft.)</span>'}
if ((distance >= 0.2) && (distance <0.3)) {distancestring = 'Less than 300 m <span style="font-size:13px;">(984 ft.)</span>'}
if ((distance >= 0.3) && (distance <0.4)) {distancestring = 'Less than 400 m <span style="font-size:13px;">(1312 ft.)</span>'}
if ((distance >= 0.4) && (distance <0.5)) {distancestring = 'Less than 500 m <span style="font-size:13px;">(1640 ft.)</span>'}
if ((distance >= 0.5) && (distance <0.6)) {distancestring = 'Less than 600 m <span style="font-size:13px;">(1968 ft.)</span>'}
if ((distance >= 0.6) && (distance <0.7)) {distancestring = 'Less than 700 m <span style="font-size:13px;">(2296 ft.)</span>'}
if ((distance >= 0.7) && (distance <0.8)) {distancestring = 'Less than 800 m <span style="font-size:13px;">(2624 ft.)</span>'}
if ((distance >= 0.8) && (distance <0.9)) {distancestring = 'Less than 900 m <span style="font-size:13px;">(2953 ft.)</span>'}
if ((distance >= 0.9) && (distance <1.0)) {distancestring = 'Less than 1 km <span style="font-size:13px;">(3280 ft.)</span>'}
if ((distance >= 1.0) && (distance <1.609344)) {distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 3280.84) + ' ft.)</span>'}
if (distance > 1.609344){distancestring = 'Less than '+distancerounded+ ' km <span style="font-size:13px;">(' + Math.round(distance * 0.621371) + ' mi.)</span>'}
var namescount = result[0].displayname.split(' ').length;
var matchname;
if(namescount === 1){matchname = result[0].displayname;}
else {matchname = result[0].name.substr(0,result[0].displayname.indexOf(' '));}
singleuserarray.push({widthslides:result[0].widthslides,heightslides:result[0].heightslides,availarraystring:availarraystring,minutes:diff,distancenumber:distance,distancestring:distancestring,photocount:photocount,photos:photostring,name:matchname,age:result[0].age,description:result[0].description,id:targetid,url:'https://graph.facebook.com/'+targetid+'/picture?width=828',caption:'...',industry: result[0].industry, status: result[0].status, politics:result[0].politics,eyes:result[0].eyes,body:result[0].body,religion:result[0].religion,zodiac:result[0].zodiac,ethnicity:result[0].ethnicity,height:result[0].height,weight:result[0].weight});
// console.log(singleuserarray);
main_all = new_all;
new_all = singleuserarray;
$(".avail-loader").hide();
if (singleuserarray[0].availarraystring !== ''){
$(".availabilitylistblock_"+singleuserarray[0].id).remove();
$(".availtitle").remove();
$( ".profileyo_" + singleuserarray[0].id ).append(
'<div class="content-block-title availtitle" style="padding-top:0px;clear:both;margin-top:15px;">'+targetname+'\'s Availability</div>'+
'<div class="list-block media-list availabilitylistblock_'+singleuserarray[0].id+'" style="margin-top:0px;clear:both;margin-bottom:-40px;">'+
'<ul style="background-color:transparent">'+
' </ul></div>');
var availablearrayindividual = JSON.parse(singleuserarray[0].availarraystring);
var tonight = new Date();
tonight.setHours(22,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
for (k = 0; k < availablearrayindividual.length; k++) {
if (availablearrayindividual[k].id >= tonight_timestamp){
$( ".availabilitylistblock_"+singleuserarray[0].id ).append(
' <li style="list-style-type:none;" class="item-link item-content" onclick="request(\''+availablearrayindividual[k].id+'\',\''+availablearrayindividual[k].time+'\')">'+
'<div class="item-content">'+
'<i class="pe-7s-angle-right pe-3x" style="position:absolute;right:5px;color:#007aff;"></i>'+
'<div class="item-media">'+
'<span class="badge" style="background-color:#4cd964;">'+availablearrayindividual[k].day.charAt(0)+'</span>'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <input type="text" name="name" style="height:30px;font-size:15px;" value="'+availablearrayindividual[k].day+', '+availablearrayindividual[k].time+'" readonly>'+
' <input type="text" style="float:right;color:#333;text-align:left;height:30px;font-size:15px;" name="name" value="'+availablearrayindividual[k].fulldate+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
}
}
if (origin == 88){
//alert('88');
}
else if (origin == 1){
//alert('99');
photoBrowser(0,singleuserarray[0].age,1,1);
}
else if (!origin){
//alert('100');
photoBrowser(0,singleuserarray[0].age);
}
});
});
}
}
function request(dayw,timeq){
$( ".profileyomain" ).hide();
canloadchat = false;
$( '.picker-items-col-wrapper' ).css("width", "auto");
$( ".requesticon" ).hide();
$( ".dateheader" ).show();
$( ".sender-inner" ).hide();
$( ".yes-inner" ).hide();
conversation_started = false;
if (d_response == 'Y') {
$( ".date-close" ).hide();
$( ".date2-close" ).show();
$( ".date1-close" ).hide();
}
if (d_response == 'W') {
$( ".date-close" ).hide();
$( ".date1-close" ).show();
$( ".date2-close" ).hide();
}
if(!d_response){
$( ".date-close" ).show();
$( ".date2-close" ).hide();
$( ".date1-close" ).hide();
}
$( ".messages" ).hide();
$( ".date-button" ).hide();
$( "#createdatepicker" ).show();
$( ".dr" ).hide();
$( ".date-back" ).hide();
if (d_type == 'date') {$( ".date-row" ).show();$( ".duck-row" ).hide();}
if (d_type == 'duck') {$( ".duck-row" ).show();$( ".date-row" ).hide();}
$( ".waitingreply" ).empty();
$( ".datetoolbar" ).slideDown();
$( ".message-inner" ).hide();
$( ".date-inner" ).show();
if (d_response=='Y'){$( "#datemessageq" ).val('');}
// $( ".center-date" ).empty();
// if (d_type=='date') {$( ".center-date" ).append('Date Details');}
// if (d_type=='duck') {$( ".center-date" ).append('Duck Details');}
myApp.sizeNavbars();
//$( "#createdatepicker" ).focus();
$( ".page-content" ).animate({ scrollTop: 0 }, "fast");
if (dayw){
var daycol = pickerCustomToolbar.cols[0];
daycol.setValue(dayw);
if (timeq != 'Anytime'){
var timecol = pickerCustomToolbar.cols[1];
timecol.setValue(timeq);
}
}
}
function noChange(){
myApp.closeModal('.actions-modal');
canloadchat = true;
$( ".sender-inner" ).hide();
$( ".messages" ).show();
$( ".date-close" ).hide();
$( ".date2-close" ).hide();
$( ".date1-close" ).hide();
$( ".message-inner" ).show();
$( ".date-inner" ).hide();
// $( ".center-date" ).empty();
$( "#createdatepicker" ).hide();
// $( ".center-date" ).append(targetname);
$( ".nomessages" ).hide();
$( ".date-back" ).show();
$( ".date-button" ).show();
scrollBottom();
myApp.sizeNavbars();
}
function reverseRequest(){
if ($('.availtitle').length > 0){$( ".datetoolbar" ).hide();}
myApp.closeModal('.actions-modal');
$( ".profileyomain" ).show();
$( ".dateheader" ).hide();
$( "#createdatepicker" ).hide();
$( ".dr" ).show();
$( ".date-back" ).show();
$( ".date-row" ).hide();
$( ".duck-row" ).hide();
$( ".date-close" ).hide();
$( ".requesticon" ).show();
$( ".date-inner" ).hide();
if (!d_day){
//$( ".center-date" ).empty();
// $( ".center-date" ).append(targetname);
myApp.sizeNavbars();
}
}
var message_count = 0;
var messages_loaded = false;
var conversation_started = false;
var prevdatetitle;
function chatShow(){
//fcm();
prevdatetitle = false;
letsload = 20;
canloadchat = true;
additions = 0;
$( ".yes-inner" ).hide();
$( ".sender-inner" ).hide();
$( ".datedetailsdiv" ).show();
message_count = 1;
image_count = 0;
$( ".messages" ).show();
$( ".datearea" ).empty();
$( ".date-back" ).show();
$( ".date-button" ).show();
$( ".date-close" ).hide();
$( ".date2-close" ).hide();
$( ".datetoolbar" ).show();
$( ".message-inner" ).show();
$( ".date-inner" ).hide();
// $( ".center-date" ).empty();
// $( ".center-date" ).append(targetname);
myApp.sizeNavbars();
myMessagebar = myApp.messagebar('.messagebar', {
maxHeight: 88
});
myMessages = myApp.messages('.messages', {
autoLayout: true,
scrollMessages:true
});
//if (myMessages) {myMessages.clean();}
if (message_history === true){}
if (message_history === false){
message_history = true;
//do the .on call here to keep receiving messages here
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) {
existingmessages = snapshot.numChildren();
// $( ".messages").append( '<a href="#" class="button scrollbutton" onclick="scrollBottom();" style="border:0;margin-top:10px;"><i class="pe-7s-angle-down-circle pe-2x" style="margin-right:5px;"></i> New Messages</a>');
// $( ".messages").append('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>');
// if (snapshot.numChildren() > 10) {$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>');}
}).then(function(result) {
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
message_historyon = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(20).on("child_added", function(snapshot) {
if (message_count ==1) {lastkey = snapshot.getKey();}
message_count ++;
var checkloaded;
if (existingmessages > 19){checkloaded = 20;}
else if (existingmessages < 20){checkloaded = existingmessages;}
if (message_count == checkloaded){messages_loaded = true;}
var obj = snapshot.val();
var datechatstring;
var messagedate = new Date((obj.timestamp * 1000));
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
//console.log('prevdatetitle does not exist');
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
//my messages
var unix = Math.round(+new Date()/1000);
if (obj.from_uid == f_uid) {
if (obj.param == 'dateset'){
$( ".messages" ).append(
'<div class="list-block media-list" style="margin-top:0px;">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-media">'+
' <img src="path/to/img.jpg">'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">Date Details</div>'+
' <div class="item-after">Element label</div>'+
' </div>'+
' <div class="item-subtitle">Subtitle</div>'+
' <div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>');
}
if (obj.param == 'message'){
myMessages.addMessage({
// Message text
text: obj.message,
// Random message type
type: 'sent',
// Avatar and name:
//avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
// Day
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
if (obj.photo_expiry){
if (obj.photo_expiry < Number(unix)){
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
}
else{
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// Avatar and name:
//avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
// Day
});
image_count ++;
}
}
else {
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// ' and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
}
}
if (conversation_started === true) {
$( ".message" ).last().remove();
$( ".message" ).last().addClass("message-last");
$('#buzzer')[0].play();
}
}
//received messages
if (obj.to_uid == f_uid) {
if (messages_loaded === true) {
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
if (snapshot.val()){
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref('notifications/' +f_uid + '/' + targetid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
firebase.database().ref('notifications/' +targetid + '/' + f_uid).update({
received:'Y',
new_message_count:'0',
authcheck:f_uid,
uid_accepted:f_uid
});
}
}
});
}
if (conversation_started === true) {
$('#buzzer')[0].play();
}
if (obj.param == 'dateset'){
$( ".messages" ).append(
'<div class="list-block media-list">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-media">'+
' <img src="path/to/img.jpg">'+
'</div>'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">Element title</div>'+
' <div class="item-after">Element label</div>'+
' </div>'+
' <div class="item-subtitle">Subtitle</div>'+
' <div class="item-text">Additional description text</div>'+
'</div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>');
}
if (obj.param == 'message'){
myMessages.addMessage({
// Message text
text: obj.message,
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: targetname,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
if (!obj.photo_expiry){
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
var seentime = Math.round(+new Date()/1000);
var expirytime = Math.round(+new Date()/1000) + 86400;
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
firebase.database().ref('photostodelete/' + obj.from_uid + '/' +obj.to_uid+ '/' +obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).update({
photo_expiry:expirytime,
seen:'Y',
seentime:seentime
});
}
else {
if (obj.photo_expiry < Number(unix)){
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + obj.id).remove();
}
else{
myMessages.addMessage({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
image_count ++;
}
}
}
}
}, function (errorObject) {
});
});
}
//myMessages.layout();
//myMessages = myApp.messages('.messages', {
// autoLayout: true
//});
//myMessages.scrollMessages();
myApp.initPullToRefresh('.pull-to-refresh-content-9');
}
var notifadditions=0;
var notifletsload = 12;
function getmoreNotifs(){
notifadditions ++;
var notifsloaded = notifadditions * 12;
var notif2load = mynotifs.length - (notifadditions * 12);
if (notif2load > 12) {notifletsload = 12;} else {notifletsload = notif2load;}
var lasttoaddnotif = notifsloaded + notifletsload;
$(".loadnotifsloader").remove();
for (i = notifsloaded; i < lasttoaddnotif; i++) {
myList.appendItem({
title: mynotifs[i].title,
targetid:mynotifs[i].targetid,
targetname:mynotifs[i].targetname,
picture:mynotifs[i].picture,
from_name: mynotifs[i].from_name,
to_name: mynotifs[i].to_name,
from_uid:mynotifs[i].from_uid,
to_uid: mynotifs[i].to_uid,
icon:mynotifs[i].icon,
colordot:mynotifs[i].colordot,
func:mynotifs[i].func,
type:mynotifs[i].type,
timestamptitle:mynotifs[i].timestamptitle
});
}
canscrollnotif = true;
}
var letsload = 20;
function getPrevious(){
if (existingmessages === false){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref("chats/" + first_number+ '/' + second_number).once('value').then(function(snapshot) {
existingmessages = snapshot.numChildren();
previousFunction();
})
}
else{previousFunction();}
function previousFunction(){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var prevarray = [];
message_count = 0;
additions ++;
$(".previouschats").remove();
var left2load = existingmessages - (additions * 20);
if (left2load > 20) {letsload = 20;} else {letsload = left2load;}
//console.log('existingmessages' + existingmessages);
//console.log('letsload' + letsload);
//console.log('additions' + additions);
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var newmessage_history = firebase.database().ref("chats/" + first_number+ '/' + second_number).orderByKey().limitToLast(letsload).endAt(lastkey).on("child_added", function(snapshot) {
message_count ++;
if (message_count ==1) {lastkey = snapshot.getKey();}
var obj = snapshot.val();
var datechatstring;
var messagedate = new Date((obj.timestamp * 1000));
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today'}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){
//console.log($(".message").length);
if ((letsload < 20) && (message_count == 1) ){
if (messagedaytitle == todaystring){datechatstring = 'Today'}
if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
else {datechatstring='';}
}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today'}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday'}
else{datechatstring = messagedaytitle;}
}
}
//my messages
if (obj.from_uid == f_uid) {
if (obj.param == 'message'){
prevarray.push({
// Message text
text: obj.message,
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
prevarray.push({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
}
}
//received messages
if (obj.to_uid == f_uid) {
if (obj.param == 'message'){
prevarray.push({
// Message text
text: obj.message,
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+targetid+'/picture?type=normal',
name: targetname,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
}
if (obj.param == 'image'){
prevarray.push({
// Message text
text: '<img src="'+obj.downloadurl+'" onload="$(this).fadeIn(700);" style="display:none" onclick="imagesPopup(\''+obj.id+'\');">',
// Random message type
type: 'received',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
}
}
if (message_count == letsload) {
$(".loadmessagesloader").remove();
canloadchat = true;
myMessages.addMessages(prevarray.slice(0, -1), 'prepend');
//$(".scrollbutton").remove();
//$(".messages").prepend('<a href="#" class="button scrollbutton" onclick="scrollBottom()" style="display:none;top:103px;position:absolute;right:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-down-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">New messages</div></div></a>');
//if (message_count == 20){$( ".messages").prepend( '<a href="#" class="button previouschats" onclick="getPrevious()" style="top:103px;position:absolute;left:0;float:left;width:50%;border:0;height:auto;"><div style="height:29px;width:130px;margin:0 auto;"><i class="pe-7s-angle-up-circle pe-2x" style="float:left;" ></i> <div style="float:left;margin-left:5px;">Past messages</div></div></a>' );$( ".messages" ).css("margin-top","132px");}
}
}, function (errorObject) {
// console.log("The read failed: " + errorObject.code);
});
}
}
var targetid;
var targetname;
var targetreported;
var targetdatearray,targetduckarray;
var targetdate,targetduck;
var match;
var targetdatelikes, targetducklikes;
var slideheight = $( window ).height();
function getMeta(url){
$("<img/>",{
load : function(){
if (this.height > this.width){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height',$(document).height() + 'px');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
}
},
src : url
});
}
function backtoProfile(){
myApp.closeModal('.infopopup') ;
$( ".toolbarq" ).hide();
//getMeta(new_all[myPhotoBrowser.activeIndex].url);
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
//$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none');
//put original image here
$( ".greytag" ).addClass('bluetext');
//$( ".photo-browser-slide img" ).css("height","100%");
$( ".datebutton" ).addClass('imagelibrary');
$( ".duckbutton" ).addClass('imagelibrary');
//$( ".swiper-container-vertical" ).css("height",slideheight + "px");
//$( ".swiper-container-vertical" ).css("margin-top","0px");
//$( ".swiper-slide-active" ).css("height", "600px");
$( ".toolbarq" ).css("background-color","transparent");
$( ".datefloat" ).hide();
$( ".duckfloat" ).hide();
$( ".vertical-pag" ).show();
//$( ".infopopup" ).css("z-index","-100");
$( ".onlineblock" ).hide();
//$( ".orlink" ).show();
//$( ".uplink" ).hide();
//$( ".nextlink" ).hide();
//$( ".prevlink" ).hide();
$( ".prevphoto" ).show();
$( ".nextphoto" ).show();
$( ".nexts" ).hide();
$( ".prevs" ).hide();
$( ".photo-browser-slide" ).css("opacity","1");
//$( ".datebutton" ).css("height","40px");
//$( ".duckbutton" ).css("height","40px");
//$( ".datebutton img" ).css("height","30px");
//$( ".duckbutton img" ).css("height","30px");
//$( ".datebutton img" ).css("width","auto");
//$( ".duckbutton img" ).css("width","auto");
$( ".photobrowserbar" ).css("background-color","transparent");
}
var comingback;
function scrollQuestions(){
//console.log($( ".wrapper-questions" ).offset().top);
//console.log($( window ).height());
var offsetline = $( window ).height() - 88;
var offsetdiv = $( ".wrapper-questions" ).offset().top;
//if (offsetdiv > offsetline){$( ".photo-browser-slide" ).css("opacity",1);}
var setopacity = (($( ".wrapper-questions" ).offset().top +88) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity);
//if
// if (offsetdiv > offsetline) {$( ".photo-browser-slide" ).css("opacity","1");$( ".adown" ).css("opacity","1");}
//var setopacity = (($( ".wrapper-questions" ).offset().top +10) / $( window ).height());$( ".photo-browser-slide" ).css("opacity",setopacity);$( ".adown" ).css("opacity",setopacity);
}
function delayYo(){
}
function scrolltoTop(){
$( ".swiper-questions" ).animate({ scrollTop: $( window ).height() - 130 });
}
function questions(origin){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
$( ".toolbarq" ).css("background-color","transparent");
$( ".photobrowserbar" ).css("background-color","#ccc");
$( ".greytag" ).removeClass('bluetext');
var targetplugin = new_all[myPhotoBrowser.activeIndex].id;
//may need to readd this
//checkMatch(targetplugin);
comingback = 0;
if (origin){comingback = 1;}
if (swiperQuestions){
swiperQuestions.removeAllSlides();
swiperQuestions.destroy();
}
//alert($('.photo-browser-slide img').css('height'));
if ($('.infopopup').length > 0) {
myApp.alert('Something went wrong. Try restarting the app and please report this to us.', 'Oops');
myApp.closeModal('.infopopup');return false;
}
$( ".vertical-pag" ).hide();
$( ".datefloat" ).show();
$( ".duckfloat" ).show();
$( ".datebutton" ).removeClass('imagelibrary');
$( ".duckbutton" ).removeClass('imagelibrary');
//$( ".swiper-container-vertical.swiper-slide-active img" ).css("height","-webkit-calc(100% - 115px)");
//$( ".swiper-container-vertical" ).css("margin-top","-27px");
//$( ".swiper-slide-active" ).css("height","100%");
//$( ".photo-browser-slide img" ).css("height","calc(100% - 80px)");
//$( ".orlink" ).hide();
//$( ".uplink" ).show();
//$( ".nextlink" ).show();
//$( ".prevlink" ).show();
$( ".onlineblock" ).show();
//$( ".datebutton" ).css("height","70px");
//$( ".duckbutton" ).css("height","70px");
//$( ".datebutton img" ).css("height","60px");
//$( ".duckbutton img" ).css("height","60px");
//$( ".datebutton img" ).css("width","auto");
//$( ".duckbutton img" ).css("width","auto");
//$( ".nametag" ).removeClass('whitetext');
var photobrowserHTML =
'<div class="popup infopopup" style="background-color:transparent;margin-top:44px;height:calc(100% - 127px);padding-bottom:20px;z-index:12000;" >'+
// ' <a href="#tab1" class="prevs button disabled" style="border-radius:5px;position:absolute;left:-37px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99;color:#2196f3;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-left pe-4x" style="margin-left:7px;margin-top:-1px;z-index:-1"></i></a>'+
// ' <a href="#tab3" class="nexts button" style="border-radius:5px;position:absolute;right:-37px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2196f3;border:0;z-index:99;background-color:rgba(247, 247, 247, 0.952941);"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+
'<div class="swiper-container swiper-questions" style="height:100%;overflow-y:scroll;">'+
'<div style="height:100%;width:100%;overflow-x:hidden;" onclick="backtoProfile();">'+
'</div>'+
' <div class="swiper-wrapper wrapper-questions" style="">'+
' </div>'+
'</div>'+
'</div>'
myApp.popup(photobrowserHTML,true,false);
$( ".nexts" ).show();
$( ".prevs" ).show();
$( ".prevphoto" ).hide();
$( ".nextphoto" ).hide();
for (i = 0; i < new_all.length; i++) {
var boxcolor,displayavail,availabilityli,availabletext,iconavaill;
iconavaill='f';boxcolor = 'width:60px;color:#007aff;opacity:1;background-color:transparent';displayavail='none';availabletext='';
$( ".wrapper-questions" ).append('<div class="swiper-slide slideinfo_'+new_all[i].id+'" style="height:100%;">'+
//'<h3 class="availabilitytitle_'+new_all[i].id+'" style="color:white;font-size:16px;padding:5px;float:left;"><i class="pe-7-angle-down pe-3x"></i></h3>'+
'<h3 onclick="scrolltoTop()" class="adown arrowdown_'+new_all[i].id+' availyope availyo_'+ new_all[i].id+'" style="display:none;margin-top:-60px;right:0px;'+boxcolor+';font-size:14px;padding:0px;margin-left:10px;"><i class="pe-7f-angle-down pe-3x" style="float:left;"></i>'+
'</h3>'+
'<div onclick="scrolltoTop()" style="z-index:12000;margin-top:15px;background-color:white;border-radius:20px;border-bottom-right-radius:0px;border-bottom-left-radius:0px;margin-bottom:20px;display:none;" class="prof_'+i+' infoprofile availyo_'+ new_all[i].id+'">'+
'<div class="content-block-title" style="padding-top:0px;clear:both;margin-top:0px;">About '+new_all[i].name+'</div>'+
'<div class="list-block" style="margin-top:0px;clear:both;">'+
'<ul class="profileul_'+new_all[i].id+'" style="background-color:transparent">'+
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Online</div>'+
' <div class="item-input">'+
'<div class="timetag_'+ new_all[i].id+'"></div>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Distance</div>'+
' <div class="item-input">'+
'<div class="distancetag_'+ new_all[i].id+'"></div>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' </ul></div>'+
'</div>'+
'</div>');
//put here
if (new_all[i].description){
$( ".profileul_"+new_all[i].id ).prepend(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-input">'+
' <textarea class="resizable" name="name" style="max-height:200px;font-size:14px;" readonly>'+new_all[i].description+'</textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].hometown){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Hometown</div>'+
' <div class="item-input">'+
'<textarea class="resizable" style="min-height:60px;max-height:132px;" readonly>'+new_all[i].hometown+'</textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].industry){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Industry</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].industry+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].zodiac){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Zodiac</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].zodiac+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].politics){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Politics</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].politics+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].religion){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Religion</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].religion+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].ethnicity){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Ethnicity</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].ethnicity+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].eyes){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Eye Color</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].eyes+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].body){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Body Type</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].body+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].height != 0){
if (new_all[i].height == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (new_all[i].height == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (new_all[i].height == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (new_all[i].height == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (new_all[i].height == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (new_all[i].height == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (new_all[i].height == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (new_all[i].height == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (new_all[i].height == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (new_all[i].height == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (new_all[i].height == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (new_all[i].height == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (new_all[i].height == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (new_all[i].height == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (new_all[i].height == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (new_all[i].height == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (new_all[i].height == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (new_all[i].height == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (new_all[i].height == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (new_all[i].height == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (new_all[i].height == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (new_all[i].height == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (new_all[i].height == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (new_all[i].height == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (new_all[i].height == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (new_all[i].height == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (new_all[i].height == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (new_all[i].height == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (new_all[i].height == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (new_all[i].height == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (new_all[i].height == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (new_all[i].height == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (new_all[i].height == 203) {var heightset = '203 cm (6\' 8\'\')';}
$(".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Height</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+heightset+'" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
if (new_all[i].weight != 0){
$( ".profileul_"+new_all[i].id ).append(
' <li>'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Weight</div>'+
' <div class="item-input">'+
' <input type="text" name="name" value="'+new_all[i].weight+' kg (' + Math.round(new_all[i].weight* 2.20462262) + ' lbs)" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'
);
}
var timestring;
var minutevalue;
if (new_all[i].minutes <= 0){timestring = 'Now';}
if (new_all[i].minutes == 1){timestring = '1 minute ago';}
if ((new_all[i].minutes >= 0) && (new_all[i].minutes <60)){timestring = Math.round(new_all[i].minutes) + ' minutes ago';}
if (new_all[i].minutes == 60){timestring = '1 hour ago';}
if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){
minutevalue = Math.round((new_all[i].minutes / 60));
if (minutevalue == 1) {timestring = '1 hour ago';}
else {timestring = minutevalue + ' hours ago';}
}
if ((new_all[i].minutes >= 60) && (new_all[i].minutes <1440)){timestring = Math.round((new_all[i].minutes / 60)) + ' hours ago';}
if (new_all[i].minutes == 1440){timestring = '1 day ago';}
if ((new_all[i].minutes >= 1440) && (new_all[i].minutes <10080)){
minutevalue = Math.round((new_all[i].minutes / 1440));
if (minutevalue == 1) {timestring = '1 day ago';}
else {timestring = minutevalue + ' days ago';}
}
if (new_all[i].minutes >= 10080){timestring = '1 week';}
if (new_all[i].minutes >= 20160){timestring = '2 weeks';}
if (new_all[i].minutes >= 30240){timestring = '3 weeks';}
$( ".timetag_" + new_all[i].id ).html(timestring);
$( ".distancetag_" + new_all[i].id ).html(new_all[i].distancestring);
}
swiperQuestions = myApp.swiper('.swiper-questions', {
nextButton:'.nexts',
prevButton:'.prevs',
onSetTranslate:function(swiper, translate){myPhotoBrowser.swiper.setWrapperTranslate(translate - (20 * swiper.activeIndex));},
onInit:function(swiper){
myPhotoBrowser.swiper.setWrapperTranslate(0);
$( ".infoprofile").hide();
$( ".adown" ).css( "opacity","1" );
var wrapperheightshould = $(".prof_" + swiper.activeIndex).height();
$( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px");
$( ".availyope").hide();
//$( ".availyo_"+ new_all[0].id ).show();
if (new_all.length === 1){swiper.lockSwipes();myPhotoBrowser.swiper.lockSwipes();}
//checkmatchwashere
//checkMatch(targetid);
},
onSlideChangeStart:function(swiper){
var wrapperheightshould = $(".prof_" + swiper.activeIndex).height();
$( ".wrapper-questions").css("height",(wrapperheightshould - 150)+ "px");
if(comingback === 1){
if (swiper.activeIndex > swiper.previousIndex){myPhotoBrowser.swiper.slideNext();}
if (swiper.activeIndex < swiper.previousIndex){myPhotoBrowser.swiper.slidePrev();}
}
// if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" );
//}
// else{$( ".prevs" ).removeClass( "disabled" );}
// if (swiper.isEnd === true){$( ".nexts" ).addClass( "disabled" );}
// else{$( ".nexts" ).removeClass( "disabled" );}
//if (swiper.isBeginning === true){$( ".prevs" ).addClass( "disabled" );
// $(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show();
// }
//else if (swiper.isEnd === true){$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); }
//else{$(".arrowdown_"+new_all[swiper.activeIndex + 1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex -1].id).hide();
//$(".arrowdown_"+new_all[swiper.activeIndex].id).show(); }
//$( ".adown" ).css( "opacity","1" );
$( ".camerabadge" ).text(new_all[swiper.activeIndex].photocount);
$( ".infoprofile").hide();
$( ".availyope").hide();
//$(".swiper-questions").css("background-image", "url("+new_all[swiper.activeIndex].url+")");
//$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-size", "cover");
//$(".slideinfo_"+new_all[swiper.activeIndex + 1].id).css("background-position", "50% 50%");
//$(".swiper-questions".css("background", "transparent");
$( ".swiper-questions" ).scrollTop( 0 );
if ($('.toolbarq').css('display') == 'block')
{
if (((swiper.activeIndex - swiper.previousIndex) > 1) ||((swiper.activeIndex - swiper.previousIndex) < -1) ){
//alert(swiper.activeIndex - swiper.previousIndex);
//myPhotoBrowser.swiper.slideTo(0);
myPhotoBrowser.swiper.slideTo(swiper.activeIndex);
//swiper.slideTo(myPhotoBrowser.swiper.activeIndex);
}
}
//checkmatchwashere
//checkMatch(targetid);
}
});
//console.log(myPhotoBrowser.swiper.activeIndex);
swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex,0);
$( ".availyo_"+ new_all[swiperQuestions.activeIndex].id ).show();
$( ".toolbarq" ).show();
comingback = 1;
$( ".camerabadge" ).text(new_all[myPhotoBrowser.swiper.activeIndex].photocount);
$( ".distancetag" ).text(new_all[myPhotoBrowser.swiper.activeIndex].distancestring);
//if (myPhotoBrowser.swiper.activeIndex === 0){
//myPhotoBrowser.swiper.slideNext();
//myPhotoBrowser.swiper.slidePrev();
//}
//else {
//}
//swiperQuestions.slideTo(myPhotoBrowser.swiper.activeIndex);
}
function checkMatch(targetid){
var indivNotif = firebase.database().ref('notifications/' + f_uid + '/' + targetid);
indivNotif.once('value', function(snapshot) {
if (snapshot.val()){
var obj = snapshot.val();
if (obj.new_message_count >0 && obj.to_uid == f_uid && obj.received =='N'){$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');}
else{$( ".indivnotifcount" ).remove();}
}
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) {
$( ".availyo_"+ new_all[swiperQuestions.activeIndex].id ).show();
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".loaderlink" ).hide();
$( ".orlink" ).show();
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
if (snapshot.val() === null) {}
else {
if (first_number == f_uid){
if (snapshot.val().firstnumberreport){targetreported = true;}else {targetreported = false;}
//Dates
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
if (first_number == targetid){
if (snapshot.val().secondnumberreport){targetreported = true;}else {targetreported = false;}
//Date
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
}
});
}
function unmatchDate(){
myApp.confirm('Are you sure?', 'Unmatch', function () {
dateUser();
});
}
function unmatchDuck(){
myApp.confirm('Are you sure?', 'Unmatch', function () {
duckUser();
});
}
function photoBrowser(openprofile,arraynumber,mainchange,chatorigin){
allowedchange = true;
photoresize = false;
if ($('.photo-browser').length > 0){return false;}
myApp.closeModal('.picker-sub');
//firebase.database().ref("users/" + f_uid).off('value', userpref);
var photobrowserclass="";
var duckfunction = ""
var datefunction = ""
if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","10000" );photobrowserclass="photo-browser-close-link";}
else{duckfunction = "createDuck()";datefunction = "createDate1()";}
var to_open = 0;
if ($('.chatpop').length > 0 || chatorigin) {}
else {
to_open = openprofile;
}
var hiddendivheight = $( window ).height() - 40;
//alert(JSON.stringify(new_all));
myPhotoBrowser = myApp.photoBrowser({
zoom: false,
expositionHideCaptions:true,
lazyLoading:true,
lazyLoadingInPrevNext:true,
lazyPhotoTemplate:
'<div class="photo-browser-slide photo-browser-slide-lazy swiper-slide" style="background-color:transparent;">'+
'<div class="preloader {{@root.preloaderColorClass}}">{{#if @root.material}}{{@root.materialPreloaderSvg}}{{/if}}</div>'+
'<div class="swiper-container swiper-vertical" style="height:100%;min-width:'+$(document).width()+'px;background-color:transparent;">'+
'<div class="swiper-wrapper vertical-wrapper-swiper">'+
'{{js "this.photos"}}'+
'</div><div class="swiper-pagination vertical-pag" style="top:0;left:0;z-index:999999;"></div></div>'+
'</div>',
exposition:false,
photos: new_all,
captionTemplate:'<div style="width:40px;height:40px;background-color:transparent;margin-top:-80px;margin-left:50px;float:right;display:none;"></div><div class="photo-browser-caption" data-caption-index="{{@index}}">{{caption}}</div>',
toolbarTemplate:'<div class="toolbar tabbar toolbarq" style="height:84px;background-color:transparent;">'+
' <div class="toolbar-inner date-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+
'<a href="#" onclick="unmatchDate();" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;margin-left:15px;">'+
' Unmatch'+
'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" onclick="'+datefunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-right:15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Date <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x" style="margin-left:10px;margin-top:2px;"></i></div></a></div>'+
' <div class="toolbar-inner duck-template" style="display:none;padding:0;background-color:#2196f3;height:74px;border-bottom-right:20px;border-bottom-left:20px;">'+
'<a href="#" onclick="unmatchDuck()" class="button link" style="color:#ccc;font-size:15px;max-width:80px;border:0;margin-left:15px;">'+
' Unmatch'+
'</a>'+
'<a href="#" onclick="'+duckfunction+'" class="button link active lets '+photobrowserclass+'" style="border:1px solid white;margin-left:15px;margin-right:15px;font-family: \'Pacifico\', cursive;font-size:26px;height:40px;">Let\'s Duck <div style="font-family: -apple-system, SF UI Text, Helvetica Neue, Helvetica, Arial, sans-serif;position:absolute;right:0px;top:-8px;" class="arrowdivbrowser"><i class="pe-7s-angle-right pe-2x" style="margin-left:10px;margin-top:2px;"></i></div></a></div>'+
' <div class="toolbar-inner toolbardecide" style="padding-bottom:10px;padding-left:0px;padding-right:0px;">'+
'<a href="#tab3" onclick="dateUser();" class="datebutton disabled button link" style="border:1px solid white;border-right:0;border-radius:20px;border-top-right-radius:0px;border-top-left-radius:0px;border-bottom-right-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+
'<span class="datefloat" style="padding:10px;border-radius:5px;margin-right:20px;">Date</span>'+
' <div style="width:50px;overflow-x:hidden;position:absolute;right:1px;bottom:-8px;"><img src="media/datefaceonly.png" style="width:100px;margin-left:-1px;">'+
'</div>'+
' </a>'+
' <a href="#tab3" onclick="duckUser();" class="duckbutton disabled button link" style="border:1px solid white;border-left:0;border-radius:20px;border-top-left-radius:0px;border-top-right-radius:0px;border-bottom-left-radius:0px;font-family: \'Pacifico\', cursive;font-size:24px;">'+
'<span class="duckfloat" style="padding:10px;border-radius:5px;margin-left:20px;">Duck</span>'+
' <div style="width:54px;overflow-x:hidden;position:absolute;left:-1px;bottom:-8px;"> <img src="media/duckfaceonly.png" style="width:100px;margin-left:-51px;"></div>'+
'</a>'+
'<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+
' </div>'+
'</div>',
onClose:function(photobrowser){myApp.closeModal('.actions-modal');hideProfile();
singlefxallowed = true;
viewphotos = false;
viewscroll = false;
if ($('.chatpop').length > 0) {$( ".chatpop" ).css( "z-index","20000" );if ($('.chatpop').length > 0){myApp.closeModal('.infopopup');}
if (swiperQuestions){
swiperQuestions.removeAllSlides();
swiperQuestions.destroy();swiperQuestions = false;}
}
else{myApp.closeModal(); }
if (mainchange){new_all = main_all;singleuserarray = [];}
//getPreferences();
},
swipeToClose:false,
// onClick:function(swiper, event){showProfile();},
nextButton:'.nextphoto',
prevButton:'.prevphoto',
onSlideChangeStart:function(swiper){
if (allowedchange){
if (photoresize){
if ($('.infopopup').length > 0){}
else{
//getMeta(new_all[swiper.activeIndex].url);
}
}
if (swiper.activeIndex != openprofile){ photoresize = true;}
//var windowheight = $( window ).height();
//$( ".photo-browser-slide img").css( "height", "100% - 144px)" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
myApp.closeModal('.actions-modal');
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".duckbutton" ).hide();
$( ".datebutton" ).hide();
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
targetid = new_all[myPhotoBrowser.activeIndex].id;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var activecircle;
var targetdescription= new_all[myPhotoBrowser.activeIndex].description;
targetname = new_all[myPhotoBrowser.activeIndex].name;
var targetage = new_all[myPhotoBrowser.activeIndex].age;
$( ".agecat" ).text(targetage);
$( ".nametag" ).empty();
$( ".nametag" ).append('<div class="rr r_'+targetid+'">'+targetname+', '+targetage+'</div>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
}
checkMatch(targetid);
},
backLinkText: '',
//expositionHideCaptions:true,
navbarTemplate:
// ' <a href="#tab1" class="prevphoto button disabled" style="border-radius:5px;position:absolute;left:-31px;top:50%;margin-top:-28px;height:56px;width:56px;border:0;z-index:99999;color:#2196f3;background-color:transparent;"><i class="pe-7s-angle-left pe-4x" style="margin-left:5px;margin-top:-1px;"></i></a>'+
// ' <a href="#tab3" class="nextphoto button" style="border-radius:5px;position:absolute;right:-33px;width:56px;top:50%;margin-top:-26px;height:56px;color:#2186f3;border:0;z-index:99999;background-color:transparent"><i class="pe-7s-angle-right pe-4x" style="margin-left:-35px;margin-top:-1px;"></i></a>'+
// '<div style="position:absolute;bottom:80px;right:0px;margin-left:-26px;z-index:9999;color:white;"><i class="pe-7s-info pe-4x" style="margin-top:-10px;"></i></div>'+
'<div class="navbar photobrowserbar" style="background-color:#ccc">'+
' <div class="navbar-inner">'+
' <div class="left sliding">'+
' <a href="#" style="margin-left:-10px;"class="link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
'<i class="pe-7s-angle-left pe-3x matchcolor greytag"></i>'+
'<span class="badge agecat" style="margin-left:-10px;display:none;">'+arraynumber+'</span>'+
' </a>'+
' </div>'+
' <div class="center sliding nametag matchcolor greytag">'+
// ' <span class="photo-browser-current"></span> '+
// ' <span class="photo-browser-of">{{ofText}}</span> '+
// ' <span class="photo-browser-total"></span>'+
' </div>'+
' <div class="right" onclick="actionSheet()">' +
//'<a href="#" class="link"><div class="cameradivnum" style="background-color:transparent;border-radius:50%;opacity:0.9;float:left;z-index:999;"><i class="pe-7s-camera pe-lg matchcolor" style="margin-top:3px;margin-left:-5px;"></i><div class="camerabadge badge" style="position:absolute;right:0px;margin-right:-10px;top:5px;z-index:999;"></div></div></a>'+
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor greytag"></i>'+
' </a>'+
'</div>'+
'</div>'+
'</div> '
});
myPhotoBrowser.open();
targetid = new_all[myPhotoBrowser.activeIndex].id;
var mySwiperVertical = myApp.swiper('.swiper-vertical', {
direction: 'vertical',
zoom:'true',
pagination:'.swiper-pagination',
paginationType:'progress',
onSlideChangeStart:function(swiper){
var verticalheightarray = new_all[myPhotoBrowser.activeIndex].heightslides.split(",");
var verticalwidtharray = new_all[myPhotoBrowser.activeIndex].widthslides.split(",");
var trueh = verticalheightarray[swiper.activeIndex];
var truew = verticalwidtharray[swiper.activeIndex];;
if (trueh > truew){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
}
else if (trueh == trueh){
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','cover');
}
else{
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('height','100%');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('width','auto');
$( ".swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas" ).css('object-fit','none');
}
},
onImagesReady:function(swiper){
},
onInit:function(swiper){
//console.log(new_all[myPhotoBrowser.activeIndex]);
//
if (viewphotos){
setTimeout(function(){ backtoProfile();viewphotos = false; }, 100);
}
if (viewscroll){
setTimeout(function(){ scrolltoTop();viewscroll = false; }, 100);
}
},
onClick:function(swiper, event){
questions();
//if(myPhotoBrowser.exposed === true) {$( ".swiper-container-vertical img " ).css("margin-top","0px");}
//else {$( ".photo-browser-slide img " ).css("height","calc(100% - 120px)");$( ".photo-browser-slide img " ).css("margin-top","-35px");}
}
});
//var windowwidth = $( ".photo-browser-swiper-container" ).width();
$( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".photo-browser-caption" ).css( "margin-top", "-10px" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
myPhotoBrowser.swiper.slideTo(to_open,100);
checkMatch(targetid);
questions();
if (openprofile ===0){
if (myPhotoBrowser.swiper.isBeginning === true){$( ".prevphoto" ).addClass( "disabled" );}
else{$( ".prevphoto" ).removeClass( "disabled" );}
if (myPhotoBrowser.swiper.isEnd === true){$( ".nextphoto" ).addClass( "disabled" );}
else{$( ".nextphoto" ).removeClass( "disabled" );}
//var windowheight = $( window ).height();
//$( ".photo-browser-slide img").css( "height", "100% - 144px)" );
$( ".photo-browser-caption" ).empty();
$( ".nametag" ).empty();
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
var target = new_all[myPhotoBrowser.activeIndex].url;
var pretarget = target.replace("https://graph.facebook.com/", "");
targetid = String(pretarget.replace("/picture?width=828", ""));
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
//$( ".photo-browser-slide.swiper-slide-active img" ).css( "height", "100% - 144px)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
var activecircle;
var targetdescription= new_all[myPhotoBrowser.activeIndex].description;
targetname = new_all[myPhotoBrowser.activeIndex].name;
var targetage = new_all[myPhotoBrowser.activeIndex].age;
$( ".agecat" ).text(targetage);
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+', '+targetage+'</span>');
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
//may need to readd
}
}
function showProfile(){
$( ".profile-info" ).show();
}
function hideProfile(){
$( ".profile-info" ).hide();
}
function dateRequest(){
$( ".dateheader" ).hide();
$( ".date-close" ).hide();
$( ".date-button" ).hide();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var ref = firebase.database().ref();
var datemessageq = $( '#datemessageq' ).val();
var unix = Math.round(+new Date()/1000);
var day = pickerCustomToolbar.cols[0].displayValue;
var time;
if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';}
else if (pickerCustomToolbar.cols[0].displayValue =='Today'){
var daterequestnow = new Date;
var hournow = daterequestnow.getHours();
if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';}
else{time = pickerCustomToolbar.cols[1].value;}
}
else{time = pickerCustomToolbar.cols[1].value;}
var chat_expire = pickerCustomToolbar.cols[0].value;
var interestarray = [];
if (d_type == 'date'){
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestarray.push(interestadd);
}
});
}
if (d_type == 'duck'){
if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'}
if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'}
}
firebase.database().ref("dates/" + f_uid +'/' + targetid).set({
created_uid: f_uid,
created_name: f_first,
received_uid:targetid,
received_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
timestamp:unix,
day:day,
time:time,
chat_expire:chat_expire,
seen:'N',
interest:interestarray,
response:'W',
type:d_type,
message:datemessageq,
authcheck:f_uid
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).set({
created_uid: f_uid,
created_name: f_first,
received_uid:targetid,
received_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
timestamp:unix,
day:day,
time:time,
chat_expire:chat_expire,
seen:'N',
interest:interestarray,
response:'W',
type:d_type,
message:datemessageq,
authcheck:f_uid
});
sendNotification(targetid,2);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'Duck request'}
if (d_type=='date'){smessage = 'Date request'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'daterequest',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
if(d_response=='Y') {chatShow();}
else {reverseRequest();}
});
}
}
var d_interest,d_day,d_chat_expire,d_time,d_response,d_type,d_timestamp,d_dateseen,d_dateseentime,d_timeaccepted;
function existingDate(){
$( ".datearea" ).empty();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
// Test if user exists
var ref = firebase.database().ref("dates/" + f_uid +'/' + targetid);
ref.once("value")
.then(function(snapshot) {
var dateexists = snapshot.child('chat_expire').exists(); // true
if (dateexists) {
var unix = Math.round(+new Date()/1000);
if (Number(snapshot.child('chat_expire').val()) > Number(unix) ) {
d_chat_expire = snapshot.child('chat_expire').val();
d_interest = snapshot.child('interest').val();
d_type = snapshot.child('type').val();
d_day = snapshot.child('day').val();
d_time = snapshot.child('time').val();
d_response = snapshot.child('response').val();
if (snapshot.child('time_accepted').exists()){ d_timeaccepted = snapshot.child('time_accepted').val();}
d_created_uid = snapshot.child('created_uid').val();
d_timestamp = snapshot.child('timestamp').val();
d_dateseen = snapshot.child('dateseen').val();
d_dateseentime = snapshot.child('dateseentime').val();
d_message = snapshot.child('message').val();
if (d_response == 'Y') {chatShow();}
else {
noMessages();
setDate();
dateConfirmationPage();
}
$( ".messages-loader" ).hide();
}
else{
cancelDate();
//$( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
}
else{
d_chat_expire = false;
d_interest = false;
d_day = false;
d_time = false;
d_response = false;
d_message = false;
d_timeaccepted;
d_dateseen = false;
d_dateseentime = false;
d_timestamp = false;
noMessages();
setDate();
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname);
myApp.sizeNavbars();
$( ".messages-loader" ).hide();
}
});
}
function interests(id){
$( "." + id + "_i" ).toggleClass( "interestchosen" );
}
function sendMessage(){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var datechatstring;
var messagedate = new Date();
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
var newmessage = $( "#messagearea" ).val();
if (newmessage === ''){return false;}
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var t_unix = Math.round(+new Date()/1000);
firebase.database().ref("chats/" + first_number+ '/' + second_number).push({
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:newmessage,
seen:'N',
timestamp: t_unix,
type: d_type,
param:'message',
authcheck:f_uid
});
myMessages.addMessage({
// Message text
text: newmessage,
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label: 'Sent ' + messagetimetitle
});
//myMessagebar.clear();
var messageq;
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
//alert('yo3');
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
//alert(obj.param);
// alert(obj.received);
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
// alert('param'+obj.param);
// alert('new_message_count'+obj.new_message_count);
if (obj.param =='message'){
messageq = obj.new_message_count;
messageq ++;}
else{
messageq = 1;
}
}
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
}
});
}
newNotification(messageq);
});
function newNotification(messagenum){
//alert('messagenum'+messagenum);
if (!messagenum) {messagenum = 1;}
//alert(messagenum);
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:newmessage,
timestamp: t_unix,
type:d_type,
param:'message',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates);
}
$( "#messagearea" ).val('');
$( ".sendbutton" ).removeClass('disabled');
sendNotification(targetid,4);
}
function clearchatHistory(){
singlefxallowed = true;
messages_loaded = false;
if (main_all[0] != null){
new_all = main_all;
}
singleuserarray = [];
letsload = 20;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
if (message_history){
//firebase.database().ref("notifications/" + f_uid).off('value', existingchatnotifications);
firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', message_historyon);
if(additions>0){
for (i = 0; i < additions.length; i++) {
firebase.database().ref("chats/" + first_number+ '/' + second_number).off('child_added', newmessage_history);
}
}
message_history = false;
message_count = 0;
additions = 0;
existingmessages = false;
conversation_started = false;
myMessages.clean();
myMessages.destroy();
}
if (datealertvar === true){
firebase.database().ref("dates/" + f_uid +'/' + targetid).off('value', datealert);
}
datealertvar = false;
if ($$('body').hasClass('with-panel-left-reveal')) {
$(".timeline").empty();
rightPanel();
}
if ($$('body').hasClass('with-panel-right-reveal')) {
myList.deleteAllItems();
myList.clearCache();
leftPanel();
}
}
function dateConfirmationPage(details){
$( ".messagebararea" ).css("height","44px");
$( ".messagebar" ).css("height","44px");
$( ".datetoolbar" ).show();
canloadchat = false;
var g = new Date(d_chat_expire*1000 - 3600);
$( ".profileyomain" ).hide();
$( ".avail-loader" ).hide();
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var gday = weekday[g.getDay()];
var proposeddate = g.getDate();
var month = [];
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var messageclass;
if (d_created_uid == f_uid){messageclass="message-sent";messagestyle="";}
else{messageclass = "message-received";messagestyle="margin-left:70px;";}
var proposedmonth = month[g.getMonth()];
var proposedyear = g.getFullYear();
var dending;
if (proposeddate == '1' || proposeddate == '21' || proposeddate == '31'){dending = 'st'}
else if (proposeddate == '2' || proposeddate == '22'){dending = 'nd'}
else if (proposeddate == '3' || proposeddate == '23'){dending = 'rd'}
else {dending = 'th'}
$( ".dateheader" ).hide();
$( ".profileroundpic" ).show();
$( ".date1-close" ).hide();
$( ".date2-close" ).hide();
$( ".message-inner" ).hide();
$( ".date-inner" ).hide();
$( ".date-back" ).show();
var timedisplay;
// $( ".center-date" ).empty();
//$( ".center-date" ).append(targetname.capitalize());
var titleblock;
var namefromdate;
var nametodate;
if (d_created_uid == f_uid){namefromdate = f_first;nametodate = targetname;}
else{nametodate = f_first;namefromdate = targetname;}
var whatrow;
var dateseentitle;
var timestamptitle;
var capitalD;
if (d_type =='duck'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Duck Request</span>';whatrow = 'Duck';capitalD = 'Duck';}
if (d_type =='date'){titleblock = '<span style="font-family: \'Pacifico\', cursive;">Date Request</span>';whatrow = 'Date';capitalD = 'Date';}
var unixnow = Math.round(+new Date()/1000);
var tunixago = unixnow - d_timestamp;
var tunixminago = tunixago / 60;
if (tunixminago < 1) {timestamptitle = 'Sent less than 1 minute ago';}
else if (tunixminago == 1) {timestamptitle = 'Sent 1 minute ago';}
else if (tunixminago < 2) {timestamptitle = 'Sent 1 minute ago';}
else if (tunixminago < 60) {timestamptitle = 'Sent '+Math.round(tunixminago)+' minutes ago';}
else if (tunixminago == 60) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 120) {timestamptitle = 'Sent 1 hour ago';}
else if (tunixminago < 1440) {timestamptitle = 'Sent '+Math.round(tunixminago / 60) +' hours ago';}
else if (tunixminago == 1440) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago < 2880) {timestamptitle = 'Sent 1 day ago';}
else if (tunixminago >= 2880) {timestamptitle = 'Sent '+Math.round(tunixminago / 1440) +' days ago';}
if (d_dateseen){
var unixago = unixnow - d_dateseentime;
var unixminago = unixago / 60;
if (unixminago < 1) {dateseentitle = 'Seen less than 1 minute ago';}
else if (unixminago == 1) {dateseentitle = 'Seen 1 minute ago';}
else if (unixminago < 2) {dateseentitle = 'Seen 1 minute ago';}
else if (unixminago < 60) {dateseentitle = 'Seen '+Math.round(unixminago)+' minutes ago';}
else if (unixminago == 60) {dateseentitle = 'Seen 1 hour ago';}
else if (unixminago < 120) {timestamptitle = 'Seen 1 hour ago';}
else if (unixminago < 1440) {dateseentitle = 'Seen '+Math.round(unixminago / 60) +' hours ago';}
else if (unixminago == 1440) {dateseentitle = 'Seen 1 day ago';}
else if (unixminago < 2880) {dateseentitle = 'Seen 1 day ago';}
else if (unixminago >= 2880) {dateseentitle = 'Seen '+Math.round(unixminago / 1440) +' days ago';}
}
else{dateseentitle = 'Request not seen yet';}
myApp.sizeNavbars();
var messagedateblock;
if (d_message){
messagedateblock='<li><div class="item-content"><div class="item-inner"><div class="messages-content"><div class="messages messages-init" data-auto-layout="true" style="width:100%;clear:both;"> <div class="item-title label" style="width:80px;float:left;margin-top:10px;text-align:left;">Message</div><div class="message '+messageclass+' message-appear-from-top message-last message-with-tail" style="'+messagestyle+'clear:both;text-align:left;"><div class="message-text">'+d_message+'</div></div></div></div></div></div></li><li style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>';
}
else {messagedateblock='';}
if (d_time) {timedisplay = ', ' + d_time}
else {timedisplay='';}
if (details){
var junixago = unixnow - d_timeaccepted;
var junixminago = junixago / 60;
var acceptedtitle;
if (junixminago < 1) {acceptedtitle = 'Confirmed less than 1 minute ago';}
else if (junixminago == 1) {acceptedtitle = 'Confirmed 1 minute ago';}
else if (junixminago < 2) {acceptedtitle = 'Confirmed 1 minute ago';}
else if (junixminago < 60) {acceptedtitle = 'Confirmed '+Math.round(junixminago)+' minutes ago';}
else if (junixminago == 60) {acceptedtitle = 'Confirmed 1 hour ago';}
else if (junixminago < 120) {acceptedtitle = 'Confirmed 1 hour ago';}
else if (junixminago < 1440) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 60) +' hours ago';}
else if (junixminago == 1440) {acceptedtitle = 'Confirmed 1 day ago';}
else if (junixminago < 2880) {acceptedtitle = 'Confirmed 1 day ago';}
else if (junixminago >= 2880) {acceptedtitle = 'Confirmed '+Math.round(junixminago / 1440) +' days ago';}
$( ".date1-close" ).hide();
$( ".date2-close" ).show();
$( ".date-close" ).hide();
$( ".date-back" ).hide();
$( ".datetoolbar" ).show();
$( ".sender-inner" ).show();
$( ".yes-inner" ).hide();
//$( ".datetoolbar" ).css("background-color","#ccc");
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".waitingreply" ).append(
'<div style="background-color:#4cd964;padding:10px;text-align:center;font-size:20px;color:white;"><span style="font-family: \'Pacifico\', cursive;">'+capitalD+' Details</span></div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+acceptedtitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html(capitalD + ' confirmed');
$( ".infoconfirm" ).html('You can continue chatting until midnight of your scheduled '+d_type);
}
else if (d_created_uid == f_uid) {
$( ".datetoolbar" ).show();
$( ".sender-inner" ).show();
$( ".yes-inner" ).hide();
//$( ".datetoolbar" ).css("background-color","#ccc");
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html('Waiting for '+targetname+' to respond');
$( ".waitingreply" ).append(
'<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
}
else{
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var unix = Math.round(+new Date()/1000);
firebase.database().ref("dates/" + f_uid +'/' + targetid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("notifications/" + f_uid +'/' + targetid).update({
dateseen:'Y',
dateseentime:unix
});
firebase.database().ref("notifications/" + targetid +'/' + f_uid).update({
dateseen:'Y',
dateseentime:unix
});
$( ".datetoolbar" ).show();
$( ".sender-inner" ).hide();
$( ".yes-inner" ).show();
$( ".waitingreply" ).empty();
$( ".datedetailsdiv" ).hide();
$( ".requestbutton" ).remove();
$( ".requesticon" ).remove();
$( ".titleconfirm" ).show();
$( ".titleconfirm" ).html(targetname+' is waiting for your response');
$( ".waitingreply" ).append(
'<div style="background-color:#ff9500;padding:10px;text-align:center;font-size:20px;color:white;">'+titleblock+'</div>'+
'<div class="list-block media-list" onclick="request();" style="margin-top:0px;"><ul style="background-color:white;padding-bottom:10px;">'+
'<img src="media/'+d_type+'faceonly.png" style="height:60px;margin-top:15px;">'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">When?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+gday+timedisplay+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+proposeddate + dending + ' '+ proposedmonth + ' ' + proposedyear +'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="interestli" style="display:none;">'+
'<div class="item-content">'+
' <div class="item-inner" style="padding-top:15px;padding-bottom:15px;">'+
' <div class="item-title label" style="float:left;width:70px;text-align:left;">Where?</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<span class="interestdiv" style="float:left;text-align:center;"></span>'+
'</div>'+
'</div>'+
'</div>'+
' </li>'+
'<li class="interestli" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">From</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+namefromdate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+timestamptitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
messagedateblock +
'<li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label" style="width:70px;float:left;text-align:left;">To</div>'+
'<div class="item-input" style="float:left;width:calc(100% - 80px);">'+
'<input type="text" name="name" value="'+nametodate+'" readonly>'+
'<input type="text" name="name" placeholder="Your name" style="color:#666;font-size:15px;clear:both;float:left;margin-top:-20px;" value="'+dateseentitle+'" readonly>'+
'</div>'+
' </div></div>'+
' </li>'+
'<li class="" style="height:0px;overflow:hidden;"><div class="item-content"><div class="item-inner"></div></div></li>'+
'</ul>'+
'</div>'
);
}
if (d_interest && d_type =='duck'){
$( ".interestli").show();
if ((d_interest == 'my') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');}
if ((d_interest == 'my') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');}
if ((d_interest == 'your') && (d_created_uid == f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+targetname+'\'s place </div>');}
if ((d_interest == 'your') && (d_created_uid != f_uid)){$( ".interestdiv").append('<div style="font-size:15px;margin-top:10px;">At '+f_first+'\'s place </div>');}
}
if (d_interest && d_type =='date'){
for (i = 0; i < d_interest.length; i++) {
$( ".interestli").show();
$( ".interestdiv").append('<a href="#" style="margin-right:5px"><i class="twa twa-2x twa-'+d_interest[i]+'" style="margin-top:5px;margin-right:5px"></i></a>');
}
}
}
function acceptDate(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var unix = Math.round(+new Date()/1000);
$( ".sender-inner" ).hide();
$( ".yes-inner" ).hide();
var datemessageq = $( '#datemessageq' ).val();
var unix = Math.round(+new Date()/1000);
var day = pickerCustomToolbar.cols[0].displayValue;
var time;
if (pickerCustomToolbar.cols[0].displayValue =='Now'){time='';}
else if (pickerCustomToolbar.cols[0].displayValue =='Today'){
var daterequestnow = new Date;
var hournow = daterequestnow.getHours();
if((pickerCustomToolbar.cols[0].displayValue =='Morning') && (hournow >= '12')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Mid-day') && (hournow > '14')){time='';}
else if((pickerCustomToolbar.cols[0].displayValue =='Afternoon') && (hournow > '17')){time='';}
else{time = pickerCustomToolbar.cols[1].value;}
}
else{time = pickerCustomToolbar.cols[1].value;}
var chat_expire = pickerCustomToolbar.cols[0].value;
var interestarray = [];
if (d_type == 'date'){
$( ".interestbutton" ).each(function() {
if ($( this ).hasClass( "interestchosen" )) {
var classList = $(this).attr("class").split(' ');
var interestadd = classList[1].split('_')[0];
interestarray.push(interestadd);
}
});
}
if (d_type == 'duck'){
if ($( '.button-my' ).hasClass( "active" )){interestarray = 'my'}
if ($( '.button-your' ).hasClass( "active" )){interestarray = 'your'}
}
firebase.database().ref("dates/" + f_uid +'/' + targetid).update({
response: 'Y',
time_accepted: unix,
uid_accepted: f_uid,
authcheck:f_uid
});
firebase.database().ref("dates/" + targetid +'/' + f_uid).update({
response: 'Y',
time_accepted: unix,
uid_accepted: f_uid,
authcheck:f_uid
});
sendNotification(targetid,3);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
//console.log(snapshot.val());
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
//console.log(messageq);
messageq ++;
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:'Date scheduled',
timestamp: t_unix,
type:d_type,
param:'dateconfirmed',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {chatShow();});
}
}
function cancelDate(){
// Create a reference to the file to delete
$( ".dateheader" ).hide();
$( ".sender-inner" ).hide();
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
// Delete the file
firebase.database().ref("dates/" + f_uid +'/' + targetid).remove().then(function() {
// File deleted successfully
$( ".datearea" ).empty();
d_chat_expire = false;
d_interest = false;
d_day = false;
d_time = false;
d_response = false;
d_timeaccepted = false;
d_created_uid = false;
d_timestamp = false;
d_dateseen = false;
d_dateseentime = false;
d_message = false;
noMessages();
setDate();
//console.log('deleted');
}).catch(function(error) {
// Uh-oh, an error occurred!
});
// Delete the file
firebase.database().ref("dates/" + targetid +'/' + f_uid).remove().then(function() {
// File deleted successfully
//console.log('deleted');
}).catch(function(error) {
// Uh-oh, an error occurred!
});
sendNotification(targetid,6);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
});
}
newNotification();
});
function newNotification(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'Duck cancelled'}
if (d_type=='date'){smessage = 'Date cancelled'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'datedeleted',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
//console.log('delete notification sent');
});
}
}
function getPicture(key){
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = [];
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sep";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
var stringnow = new Date();
var stringyestday = new Date(Date.now() - 86400);
var todaystring = weekday[stringnow.getDay()] + ', ' + month[stringnow.getMonth()] + ' ' + stringnow.getDate();
var yesterdaystring = weekday[stringyestday.getDay()] + ', ' + month[stringyestday.getMonth()] + ' ' + stringyestday.getDate();
var datechatstring;
var messagedate = new Date();
var minstag = ('0'+messagedate.getMinutes()).slice(-2);
messagetimetitle = messagedate.getHours() + ':' + minstag;
var messagedaytitle = weekday[messagedate.getDay()] + ', ' + month[messagedate.getMonth()] + ' ' + messagedate.getDate();
if (!prevdatetitle){prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
else {
if (prevdatetitle == messagedaytitle){datechatstring='';}
else{prevdatetitle = messagedaytitle;
if (messagedaytitle == todaystring){datechatstring = 'Today';}
else if (messagedaytitle == yesterdaystring){datechatstring = 'Yesterday';}
else{datechatstring = messagedaytitle;}
}
}
var t_unix = Math.round(+new Date()/1000);
var returned = 0;
var postkeyarray = [];
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var eventy = document.getElementById('takePictureField_').files[0];
// var number_of_pictures = $(".imageli").length + 1;
if (eventy == 'undefined') {}
if (eventy !== 'undefined') {
for (i = 0; i < document.getElementById('takePictureField_').files.length; i++) {
var photoname = t_unix + i;
var newValue = firebase.database().ref().push().key;
postkeyarray.push(newValue);
myMessages.addMessage({
// Message text
text: '<img class="disabled image_'+newValue+'" src="'+URL.createObjectURL($('#takePictureField_').prop('files')[i])+'" onload="$(this).fadeIn(700);scrollBottom();" onclick="imagesPopup(\''+newValue+'\');" style="display:none;-webkit-filter: blur(50px);">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first,
day:datechatstring,
label:'<i class="twa twa-bomb"></i> Images disappear after 24 hours. Sent ' + messagetimetitle
});
//$("#dealimagediv_"+imagenumber).attr("src",URL.createObjectURL(eventy));
image_count ++;
//$('.image_' + t_unix).onclick = function(){
// openPhoto(url);};
//var randomstring = (Math.random() +1).toString(36).substr(2, 30);
var photochatspath = 'photochats/' + first_number + '/' + second_number + '/'+ photoname;
var photostorage = 'images/' + f_auth_id + '/' + photoname;
var photochatsRef = storageRef.child(photostorage);
photochatsRef.put($('#takePictureField_').prop('files')[i]).then(function(snapshot) {
var photodownloadstorage = 'images/' + f_auth_id + '/' + snapshot.metadata.name;
var photodownloadRef = storageRef.child(photodownloadstorage);
photodownloadRef.getDownloadURL().then(function(url) {
returned ++;
var newPostKey = postkeyarray[(returned-1)];
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var chatvar = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:'<img src="'+url+'" onload="$(this).fadeIn(700);" style="display:none" >',
seen:'N',
timestamp: snapshot.metadata.name,
type:d_type,
param:'image',
downloadurl:url,
first_number:first_number,
second_number:second_number
};
var photovar1 = {
id:newPostKey,
uid: f_uid,
user_name: f_first,
photo_name:photostorage,
downloadurl:url,
to_uid:targetid,
from_uid: f_uid,
first_number:first_number,
second_number:second_number,
folder:f_auth_id
};
var photovar2 = {
id:newPostKey,
uid: f_uid,
user_name: f_first,
downloadurl:url,
to_uid:targetid,
from_uid: f_uid,
first_number:first_number,
second_number:second_number
};
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + newPostKey).set(chatvar);
firebase.database().ref("photostodelete/" + f_uid + '/' + targetid + '/' + newPostKey).set(photovar1);
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + newPostKey).set(photovar2);
$(".image_"+newPostKey).attr("src", url);
$('.image_'+ newPostKey).removeClass("disabled");
$('.image_'+ newPostKey).css("-webkit-filter","none");
});
});
}
sendNotification(targetid,5);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq;
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
//console.log(obj.received);
//console.log(obj.from_uid);
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newpictureNotification(messageq);
});
}
function newpictureNotification(messagenum){
if (!messagenum) {messagenum = 1;}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:'Image ',
timestamp: t_unix,
type:d_type,
param:'image',
new_message_count:messagenum,
received:'N',
expire:d_chat_expire,
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates);
}
}
function toTimestamp(year,month,day,hour,minute,second){
var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
return datum.getTime()/1000;
}
var photoarray;
function showPhotos(){
photoarray= [];
myApp.pickerModal(
'<div class="picker-modal photo-picker" style="height:132px;">' +
'<div class="toolbar" style="background-color:#2196f3">' +
'<div class="toolbar-inner">' +
'<div class="left"></div>' +
'<div class="right"><a href="#" class="close-picker" style="color:white;">Close</a></div>' +
'</div>' +
'</div>' +
'<div class="picker-modal-inner" style="background-color:#2196f3">' +
'<div class="content-block" style="margin:0px;padding:0px;">' +
'<div class="swiper-container swiper-photos">'+
'<div class="swiper-wrapper wrapper-photos">'+
' <div class="swiper-slide" style="text-align:center;margin:-5px;height:88px;">'+
'<i class="pe-7s-plus pe-3x" style="color:white;margin-top:10px;"></i>'+
' <input type="file" size="70" accept="image/*" class="dealPictureField imagenotchosen" id="takePictureField_" onchange="getPicture();" style="background-color:transparent;color:transparent;float:left;cursor: pointer;height:60px;width:100%;z-index:1;opacity:0;height:88px;margin-top:-44px;" multiple="multiple"> '+
'</div>'+
'</div>'+
'</div>'+
'</div>' +
'</div>' +
'</div>'
);
var photosswiper = myApp.swiper('.swiper-photos', {
slidesPerView:3,
freeMode:true,
preloadImages: false,
// Enable lazy loading
lazyLoading: true,
watchSlidesVisibility:true
//pagination:'.swiper-pagination'
});
firebase.database().ref("photos/" + f_uid).once('value').then(function(snapshot) {
var childcount = 0;
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
//var key = childSnapshot.key;
// childData will be the actual contents of the child
childcount ++;
var childData = childSnapshot.val();
photoarray.push(childSnapshot.val());
$( ".wrapper-photos" ).append('<div onclick="sendphotoExisting(\''+childData.downloadurl+'\',\''+childData.filename+'\')" data-background="'+childData.downloadurl+'" style="border:1px solid black;margin:-5px;height:88px;background-size:cover;background-position:50% 50%;" class="swiper-slide swiper-lazy">'+
' <div class="swiper-lazy-preloader"></div>'+
'</div>');
if (childcount == snapshot.numChildren()){
photosswiper.updateSlidesSize();
photosswiper.slideTo(snapshot.numChildren());
// photosswiper.slideTo(0);
}
});
});
}
function sendphotoExisting(oldurl,filenamez){
conversation_started = true;
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var t_unix = Math.round(+new Date()/1000);
myMessages.addMessage({
// Message text
text: '<img src="'+oldurl+'" onload="scrollBottom();">',
// Random message type
type: 'sent',
// Avatar and name:
// avatar: 'https://graph.facebook.com/'+f_uid+'/picture?type=normal',
name: f_first
// Day
// day: !conversationStarted ? 'Today' : false,
// time: !conversationStarted ? (new Date()).getHours() + ':' + (new Date()).getMinutes() : false
});
firebase.database().ref("chats/" + first_number+ '/' + second_number).push({
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
message:'<img src="'+oldurl+'" onload="scrollBottom();">',
seen:'N',
timestamp: t_unix,
type:d_type,
param:'image',
filename:filenamez
});
myApp.closeModal('.photo-picker');
}
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
var xcountdown;
function imagesPopup(go){
if ($('.gallery-popupz').length > 0) {return false;}
var goz;
var popupHTML = '<div class="popup gallery-popupz">'+
'<div class="navbar" style="position:absolute;top:0;background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left"><a href="#" onclick="closeGallery();" class="link icon-only"><i class="pe-7s-angle-left pe-3x" style="margin-left:-10px;color:white;"></i> </a></div>'+
' <div class="center gallerytitle"></div>'+
' <div class="right photo-count"></div>'+
'</div>'+
'</div>'+
'<div class="pages">'+
'<div data-page="gallerypopup" class="page">'+
'<div class="page-content" style="background-color:white;">'+
'<div style="position:absolute;bottom:12px;right:8px;z-index:99999;background-color:white;border-radius:5px;padding:5px;"><div id="photodeletechattime" style="color:black;float:left;"></div></div>'+
'<span style="width:42px; height:42px;position:absolute;top:50%;margin-top:-21px;left:50%;margin-left:-21px;z-index:999999;" class="imagespopuploader preloader"></span> '+
'<div class="swiper-container swiper-gallery" style="height: calc(100% - 44px);margin-top:44px;">'+
' <div class="swiper-wrapper gallery-wrapper">'+
' </div>'+
'</div>'+
'<div class="swiper-pagination-gallery" style="position:absolute;bottom:0;left:0;z-index:999999;width:100%;height:4px;"></div>'+
'</div></div></div>'+
'</div>';
myApp.popup(popupHTML);
var first_number,second_number;
var gallerycount;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
var galleryimagecount = 0;
var photodeletetime;
var phototo;
var photofrom;
var photochatid;
var touid;
firebase.database().ref("photochats/" + first_number+ '/' + second_number).once("value")
.then(function(snapshot) {
gallerycount = snapshot.numChildren();
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if (obj.id == go){goz = galleryimagecount;}
var expiryval;
if (obj.photo_expiry == null){expiryval = i;}
else {expiryval = obj.photo_expiry;}
$( ".gallery-wrapper" ).append(' <div class="swiper-slide photochat_'+obj.photo_expiry+'" style="height:100%;">'+
'<div class="swiper-zoom-container">'+
'<img data-src="'+obj.downloadurl+'" class="swiper-lazy" style="width:100%;" onload="$(this).fadeIn(700);hideImagespopuploader();">'+
' <div class="swiper-lazy-preloader"></div></div><input type="hidden" class="photoexpiryhidden_'+galleryimagecount+'" value="'+expiryval +'"><input type="text" class="fromhidden_'+galleryimagecount+'" value="'+obj.from_uid+'"><input type="text" class="tohidden_'+galleryimagecount+'" value="'+obj.user_name+'"><input type="text" class="idhidden_'+galleryimagecount+'" value="'+i+'"><input type="text" class="toidhidden_'+galleryimagecount+'" value="'+obj.to_uid+'"></div>');
galleryimagecount ++;
});
var galleryswiper = myApp.swiper('.swiper-gallery', {
preloadImages: false,
lazyLoadingInPrevNext:true,
// Enable lazy loading
lazyLoading: true,
watchSlidesVisibility:true,
zoom:true,
onInit:function(swiper){var slidenum = swiper.activeIndex + 1;
photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();
phototo = $( ".tohidden_" + swiper.activeIndex).val();
photofrom = $( ".fromhidden_" + swiper.activeIndex).val();
photochatid = $( ".idhidden_" + swiper.activeIndex).val();
touid = $( ".toidhidden_" + swiper.activeIndex).val();
if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';}
else{photodeletecount();}
$( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo);
},
onSlideChangeStart:function(swiper){clearInterval(xcountdown);
var slidenum = galleryswiper.activeIndex + 1;
photodeletetime = $( ".photoexpiryhidden_" + swiper.activeIndex).val();photodeletecount();
phototo = $( ".tohidden_" + swiper.activeIndex).val();
photofrom = $( ".fromhidden_" + swiper.activeIndex).val();
photochatid = $( ".idhidden_" + swiper.activeIndex).val();
touid = $( ".toidhidden_" + swiper.activeIndex).val();
if (photodeletetime == photochatid){document.getElementById("photodeletechattime").innerHTML = '<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+touid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;float:left;margin-right:5px;"></div> <span style="float:left;margin-top:5px;">Photo unseen</span>';}
else{photodeletecount();deletePhotochat();}
$( ".gallerytitle").html('<div style="width:29px;height:29px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+photofrom+'/picture?type=normal\');background-size:cover;background-position:50% 50%;margin-right:5px;"></div>' + phototo);
myApp.sizeNavbars();
},
pagination:'.swiper-pagination-gallery',
paginationType:'progress'
});
galleryswiper.slideTo(goz,0);
myApp.sizeNavbars();
});
function deletePhotochat(){
if (photodeletetime < (new Date().getTime() / 1000)){
$( ".photochat_"+ photodeletetime).remove();
galleryswiper.update();
firebase.database().ref("photochats/" + first_number+ '/' + second_number + '/' + photochatid).remove();
firebase.database().ref("chats/" + first_number+ '/' + second_number + '/' + photochatid).remove();
}
}
function photodeletecount(){
var countDownDate = new Date(photodeletetime * 1000);
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' + hours + "h "
+ minutes + "m " ;
// Update the count down every 1 second
xcountdown = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(xcountdown);
deletePhotochat();
}
else{ document.getElementById("photodeletechattime").innerHTML = '<i class="twa twa-bomb twa-lg" style="float:left;"></i>' +hours + "h "
+ minutes + "m " ;myApp.sizeNavbars();}
}, 60000);
}
}
function hideImagespopuploader(){ $( ".imagespopuploader" ).hide();}
function closeGallery(){
myApp.closeModal('.gallery-popupz');
clearInterval(xcountdown);
}
function updateOnce(){
var uids = ["1381063698874268","1394352877264527","393790024114307","4"];
firebase.database().ref('users/' + f_uid).update({
date_me:uids
});
}
function updatePhotos(){
$( ".pp" ).each(function() {
var classList = $(this).attr("class").split(' ');
var idofphoto = classList[2].replace("photo_", "");
var index1 = f_date_match.indexOf(idofphoto);
var index2 = f_duck_match.indexOf(idofphoto);
var u_date_me = f_date_me.indexOf(idofphoto);
var u_to_date = f_to_date.indexOf(idofphoto);
var u_duck_me = f_duck_me.indexOf(idofphoto);
var u_to_duck = f_to_duck.indexOf(idofphoto);
if (index2 > -1) {
if ($( '.rr').hasClass('r_' + idofphoto)) {
d_type='duck';
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
}
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');
$( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" );
}
else if (index1 > -1) {
if ($( '.rr').hasClass('r_' + idofphoto)) {
d_type='date';
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
}
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');
$( this ).css( "-webkit-filter","none" ); $( ".distance_" + idofphoto ).css( "background-color","#2196f3" );
}
else{$( this ).css( "-webkit-filter","grayscale(80%)" );$( ".distance_" + idofphoto ).css( "background-color","#ccc" );
$( ".iconpos_" + idofphoto ).empty();
$( ".name_" + idofphoto ).css( "-webkit-filter","grayscale(80%)" );
if (u_date_me > -1){
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/datefaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" );
}
if (u_duck_me > -1) {
$( ".iconpos_" + idofphoto ).empty();
$( ".iconpos_" + idofphoto ).append('<img src="media/duckfaceonly.png" style="width:100px;">');$( ".iconpos_" + idofphoto ).css( "-webkit-filter","grayscale(1%)" );
}
if ($( '.rr').hasClass('r_' + idofphoto)) {
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
// alert(u_date_me);
// alert(u_duck_me);
if (u_date_me > -1) {$( ".datebutton" ).addClass( "likesme" );
}
else {$( ".datebutton" ).removeClass( "likesme" );}
if (u_duck_me > -1) {$( ".duckbutton" ).addClass( "likesme" );
}
else {$( ".duckbutton" ).removeClass( "likesme" );}
}
}
});
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
}
function singleBrowser(idw,idname,origin){
//firebase.database().ref("users/" + f_uid).off('value', userpref);
//targetid = idw;
targetid = String(idw);
targetname = idname;
var dbuttons;
if (origin){
dbuttons= ' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" onclick="createDate1()" class="button link active" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+
// '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
'<a href="#" onclick="createDuck()" class="button link active" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>';
}
else {
dbuttons=' <div class="toolbar-inner date-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;max-width:106.47px;">'+flargedateicon +'</a>'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;visibility:hidden;">or</p>'+
'<a href="#" class="button link active photo-browser-close-link" style="width: calc(100% - 70px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Date</a></div>'+
// '<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
' <div class="toolbar-inner duck-template" style="display:none;background-color:#2196f3;">'+
'<a href="#" class="link button" onclick="showDecide()" style="width:55px;font-family: \'Pacifico\', cursive;font-size:20px;height:40px;border:0;color:#007aff;><i class="pe-7s-close pe-2x"></i></a>'+
'<a href="#" onclick="createDuck()" class="button link active photo-browser-close-link" style="width: calc(100% - 65px);font-family: \'Pacifico\', cursive;font-size:20px;height:40px;">Let\'s Duck</a></div>';
}
singlePhotoBrowser = myApp.photoBrowser({
zoom: 400,
lazyLoading:true,
lazyLoadingInPrevNext:true,
//exposition:false,
photos: [{
url: 'https://graph.facebook.com/'+targetid+'/picture?type=large',
caption: '...'
}],
toolbarTemplate:'<div class="toolbar tabbar" style="height:100px;">'+
dbuttons+
' <div class="toolbar-inner toolbardecide">'+
'<a href="#" onclick="dateUser();" class="datebutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargedateicon +'</a>'+
' <a href="#" class="link orlink">'+
'<p style="font-family: \'Pacifico\', cursive;font-size:20px;">or</p>'+
' </a>'+
'<a href="#" class="link loaderlink"><span class="preloader preloader-white login-loader"></span></a>'+
'<a href="#" onclick="duckUser();" class="duckbutton button link disabled" style="font-family: \'Pacifico\', cursive;font-size:20px;height:80px;">'+flargeduckicon +'</a>'+
' </div>'+
'</div>',
onOpen:function(photobrowser){
$( ".chatpop" ).css( "z-index","10000" );},
onClose:function(photobrowser){hideProfile();$( ".chatpop" ).css( "z-index","11500" );
//getPreferences();
},
swipeToClose:false,
// onClick:function(swiper, event){showProfile();},
backLinkText: '',
navbarTemplate: '<div class="navbar photobrowserbar">'+
' <div class="navbar-inner">'+
' <div class="left sliding">'+
' <a href="#" style="margin-left:-10px;" class="matchcolor mainback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
// ' <i class="icon icon-back {{iconsColorClass}}"></i> '+
'<i class="pe-7s-angle-left pe-3x"></i> '+
// '<span class="badge agecat">'+arraynumber+'</span>'+
' </a>'+
' <a href="#" onclick="myApp.closeModal();clearchatHistory();" style="display:none;margin-left:-10px;" class="matchcolor notifback link photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'+
' <i class="pe-7s-angle-left pe-3x "></i> '+
// '<span class="badge agecat">'+arraynumber+'</span>'+
' </a>'+
' </div>'+
' <div class="center sliding nametag matchcolor">'+
// ' <span class="photo-browser-current"></span> '+
// ' <span class="photo-browser-of">{{ofText}}</span> '+
// ' <span class="photo-browser-total"></span>'+
' </div>'+
' <div class="right" >' +
'<a href="#" class="link">'+
' <i class="pe-7s-more pe-lg matchcolor"></i>'+
' </a>'+
'</div>'+
'</div>'+
'</div> '
});
singlePhotoBrowser.open();
$( ".nametag" ).empty();
$( ".nametag" ).append('<span class="rr r_'+targetid+'">'+targetname+'</span>');
var windowwidth = $( ".photo-browser-swiper-container" ).width();
$( ".photo-browser-slide img" ).css( "width", windowwidth + "px" );
$( ".photo-browser-slide img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".photo-browser-caption" ).css( "margin-top", "-10px" );
$( ".datebutton" ).removeClass( "active" );
$( ".duckbutton" ).removeClass( "active" );
$( ".duckbutton" ).addClass( "disabled" );
$( ".datebutton" ).addClass( "disabled" );
$( ".loaderlink" ).show();
$( ".orlink" ).hide();
match = 0;
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","grayscale(80%)" );
$( ".duck-template" ).hide();
$( ".date-template" ).hide();
unmatchNavbar();
$( ".toolbardecide" ).show();
$( ".datebutton" ).removeClass( "likesme" );
$( ".duckbutton" ).removeClass( "likesme" );
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/userdata.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:targetid,sexuality:sexuality} )
.done(function( data ) {
var result = JSON.parse(data);
var targetdescription= result[0].description;
//var targetname = result[0].name.substr(0,result[0].name.indexOf(' '));
$( ".photo-browser-caption" ).empty();
$( ".photo-browser-caption" ).append(targetdescription);
myApp.sizeNavbars();
});
}).catch(function(error) {
// Handle error
});
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
return firebase.database().ref('matches/' + f_uid + '/' + targetid).once('value').then(function(snapshot) {
$( ".duckbutton" ).removeClass( "disabled" );
$( ".datebutton" ).removeClass( "disabled" );
$( ".duckbutton" ).show();
$( ".datebutton" ).show();
$( ".loaderlink" ).hide();
$( ".orlink" ).show();
if (snapshot.val() === null) {}
else {
if (first_number == f_uid){
//Dates
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberduck == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
if (first_number == targetid){
//Date
if (snapshot.val().firstnumberdate == 'Y'){$( ".datebutton" ).addClass( "likesme" );}else {$( ".datebutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberdate == 'Y'){$( ".datebutton" ).addClass( "active" );}else {$( ".datebutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberdate == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).hide();
$( ".date-template" ).show();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='date';
}
else {}
//Duck
if (snapshot.val().firstnumberduck == 'Y'){$( ".duckbutton" ).addClass( "likesme" );}else {$( ".duckbutton" ).removeClass( "likesme" );}
if (snapshot.val().secondnumberduck == 'Y'){$( ".duckbutton" ).addClass( "active" );}else {$( ".duckbutton" ).removeClass( "active" );}
if (snapshot.val().secondnumberduck == 'Y' && snapshot.val().firstnumberdate == 'Y'){
$( ".photo-browser-slide.swiper-slide-active img" ).css( "-webkit-filter","none" );
$( ".duck-template" ).show();
$( ".date-template" ).hide();
$( ".toolbardecide" ).hide();
matchNavbar();
d_type='duck';
}
else {}
}
}
});
}
function deletePhotos(){
var unix = Math.round(+new Date()/1000);
firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
if (snapshot.val()){
$.each(objs, function(i, obj) {
$.each(obj, function(i, obk) {
if(obk.photo_expiry){
if (obk.photo_expiry < Number(unix)){
//alert('a photo to delete exists');
firebase.database().ref('/photochats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove();
firebase.database().ref('/chats/' + obk.first_number + '/' + obk.second_number+'/'+ obk.id).remove();
var desertRef = storageRef.child(obk.photo_name);
// Delete the file
desertRef.delete().then(function() {
firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove();
}).catch(function(error) {
});
//blocking out
}
}
});
});
}
});
}
function createDuck(idq,nameq,redirect){
keepopen = 1;
d_type = 'duck';
if (idq) {createDate(idq,nameq,redirect)}
else{createDate();}
}
function createDate1(idz,name,redirect){
d_type = 'date';
keepopen = 1;
if (idz) {createDate(idz,name,redirect)}
else{createDate();}
}
function duckClass(place){
if (place ==1) {
if ($( ".button-my" ).hasClass( "active" )){
$('.button-my').removeClass("active");$('.button-your').removeClass("active");
}
else {$('.button-my').addClass("active");$('.button-your').removeClass("active");}
}
if (place ==2) {
if ($( ".button-your" ).hasClass( "active" )){
$('.button-your').removeClass("active");$('.button-my').removeClass("active");
}
else {$('.button-your').addClass("active");$('.button-my').removeClass("active");}
}
}
function matchNotif(){
function newNotificationm(messagenum){
if (!messagenum) {messagenum = 1;}
var smessage;
if (d_type=='duck'){smessage = 'New match'}
if (d_type=='date'){smessage = 'New match'}
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push().key;
var t_unix = Math.round(+new Date()/1000);
var targetData = {
id:newPostKey,
from_uid: f_uid,
from_name: f_first,
to_uid:targetid,
to_name:targetname,
to_picture:targetpicture,
from_picture:image_url,
message:smessage,
timestamp: t_unix,
type:d_type,
param:'newmatch',
new_message_count:0,
received:'N',
expire:'',
authcheck:f_uid
};
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['notifications/' + f_uid + '/' + targetid] = targetData;
updates['notifications/' + targetid + '/' + f_uid] = targetData;
return firebase.database().ref().update(updates).then(function() {
//console.log('delete notification sent');
});
}
sendNotification(targetid,1);
var existingnotifications = firebase.database().ref("notifications/" + f_uid).once('value').then(function(snapshot) {
var objs = snapshot.val();
var messageq = 0;
//If existing notifications, get number of unseen messages, delete old notifications
//console.log(snapshot.val());
if (snapshot.val()){
$.each(objs, function(i, obj) {
if ((obj.from_uid == targetid)||(obj.to_uid == targetid) ){
firebase.database().ref("notifications/" + f_uid + '/' + targetid).remove();
firebase.database().ref("notifications/" + targetid + '/' + f_uid).remove();
if ((obj.from_uid == f_uid)&&(obj.received == 'N') ){
messageq = obj.new_message_count;
messageq ++;
}
}
});
}
newNotificationm(messageq);
});
}
function unmatchNotif(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
firebase.database().ref('dates/' + f_uid +'/' + targetid).remove();
firebase.database().ref('dates/' + targetid +'/' + f_uid).remove();
firebase.database().ref('notifications/' + f_uid +'/' + targetid).remove();
firebase.database().ref('notifications/' + targetid +'/' + f_uid).remove();
myApp.closePanel();
}
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
function insertAfterNthChild($parent, index, content){
$(content).insertBefore($parent.children().eq(index));
}
//function changeRadius(number){
//$('.radiusbutton').removeClass('active');
//$('#distance_'+ number).addClass('active');
//processUpdate();
//}
function sortBy(number){
var relevanticon;
var relevanttext;
//if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$('.sortbutton').removeClass('active');
$('.sortby_'+ number).addClass('active');
if ($( "#sortrandom" ).hasClass( "active" )){sortby = 'random';}
if ($( "#sortdistance" ).hasClass( "active" )){sortby = 'distance';}
if ($( "#sortactivity" ).hasClass( "active" )){sortby = 'activity';}
firebase.database().ref('users/' + f_uid).update({
sort:sortby
});
}
function addcreateDate(){
$('.left-title').text(f_duck_match_data.length + 'want to date you');
myApp.sizeNavbars();
$('.timeline-upcoming').empty();
for (i = 0; i < f_date_match_data.length; i++) {
$('.timeline-upcoming').append('<div class="timeline-item" onclick="createDate1(\''+f_date_match_data[i].uid+'\',\''+f_date_match_data[i].name+'\');">'+
'<div class="timeline-item-date">'+fdateicon+'</div>'+
'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content">'+
' <div class="timeline-item-inner">'+
' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_date_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="timeline-item-subtitle">'+f_date_match_data[i].name+'</div>'+
'</div>'+
' </div>'+
'</div>');
}
for (i = 0; i < f_duck_match_data.length; i++) {
$('.timeline-upcoming').append('<div class="timeline-item" onclick="createDuck(\''+f_duck_match_data[i].uid+'\',\''+f_duck_match_data[i].name+'\');">'+
'<div class="timeline-item-date">'+fduckicon+'</div>'+
'<div class="timeline-item-divider"></div>'+
'<div class="timeline-item-content">'+
' <div class="timeline-item-inner">'+
' <div class="timeline-item-title" style="width:100px;height:100px;border-radius:50%;background-image:url(\'https://graph.facebook.com/'+f_duck_match_data[i].uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="timeline-item-subtitle">'+f_duck_match_data[i].name+'</div>'+
'</div>'+
' </div>'+
'</div>');
}
if (f_duck_match_data.length === 0 && f_date_match_data.length ===0){
$('.timeline-upcoming').append('<div class="content-block-title" style="margin: 0 auto;text-align:center;overflow:visible;">No matches yet. <br/><br/>Keep calm and quack on!</div>');
}
}
function unblock(){
myApp.confirm('This will unblock all profiles, making you visible to everyone', 'Are you sure?', function () {
var iblockedfirst = [];
var iblockedsecond = [];
firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) {
if (snapshot.val() != null){
var objs = snapshot.val();
$.each(objs, function(i, obj) {
if((obj.first_number == f_uid)&& (obj.firstnumberblock == 'Y')){iblockedfirst.push(obj.second_number)}
if((obj.second_number == f_uid)&& (obj.secondnumberblock == 'Y')){iblockedsecond.push(obj.first_number)}
});
}
if (iblockedfirst.length){
for (i = 0; i < iblockedfirst.length; i++) {
firebase.database().ref('matches/' + f_uid + '/' + iblockedfirst[i]).update({
//add this user to my list
firstnumberblock:'N',
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:iblockedfirst[i]
});
firebase.database().ref('matches/' + iblockedfirst[i] + '/' + f_uid).update({
//add this user to my list
firstnumberblock:'N',
firstnumberdate:'N',
firstnumberduck:'N',
created:f_uid,
received:iblockedfirst[i]
});
}
}
if (iblockedsecond.length){
for (i = 0; i < iblockedsecond.length; i++) {
firebase.database().ref('matches/' + f_uid + '/' + iblockedsecond[i]).update({
//add this user to my list
secondnumberblock:'N',
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:iblockedsecond[i]
});
firebase.database().ref('matches/' + iblockedsecond[i] + '/' + f_uid).update({
//add this user to my list
secondnumberblock:'N',
secondnumberdate:'N',
secondnumberduck:'N',
created:f_uid,
received:iblockedsecond[i]
});
}
}
getWifilocation();
$( ".blockbutton" ).addClass('disabled');
})
});
}
function deleteAccount(){
//users
//photos2delete -> photos in storage
//chats
//matches
myApp.confirm('This will permanently delete your account and remove all your information including photos, chats and profile data', 'Delete Account', function () {
var matchesarray = [];
var firstnumberarray = [];
var secondnumberarray = [];
firebase.database().ref("matches/" + f_uid).once("value",function(snapshot) {
if (snapshot.val() != null){
var objs = snapshot.val();
$.each(objs, function(i, obj) {var uidadd;if(obj.first_number == f_uid){uidadd = obj.second_number;} else{uidadd = obj.first_number} matchesarray.push(uidadd); firstnumberarray.push(obj.first_number);secondnumberarray.push(obj.second_number);});
for (i = 0; i < matchesarray.length; i++) {
var mymatches = firebase.database().ref('matches/' + f_uid + '/' + matchesarray[i]);
mymatches.remove().then(function() {
//console.log("My matches Remove succeeded.")
})
.catch(function(error) {
//console.log("My matches Remove failed: " + error.message)
});
var theirmatches = firebase.database().ref('matches/' + matchesarray[i] + '/' + f_uid);
theirmatches.remove().then(function() {
//console.log("Their matches Remove succeeded.")
})
.catch(function(error) {
//console.log("Their matches Remove failed: " + error.message)
});
var mydates = firebase.database().ref('dates/' + f_uid + '/' + matchesarray[i]);
mydates.remove().then(function() {
//console.log("My dates Remove succeeded.")
})
.catch(function(error) {
//console.log("My dates Remove failed: " + error.message)
});
var theirdates = firebase.database().ref('dates/' + matchesarray[i] + '/' + f_uid);
theirdates.remove().then(function() {
//console.log("Their dates Remove succeeded.")
})
.catch(function(error) {
//console.log("Their dates Remove failed: " + error.message)
});
var theirnotifs = firebase.database().ref('notifications/' + matchesarray[i] + '/' + f_uid);
theirnotifs.remove().then(function() {
//console.log("their notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("their notifs failed: " + error.message)
});
var ourchats = firebase.database().ref('chats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
ourchats.remove().then(function() {
//console.log("Chats Remove succeeded.")
})
.catch(function(error) {
//console.log("Chats Remove failed: " + error.message)
});
var ourphotochats = firebase.database().ref('photochats/' + firstnumberarray[i] + '/' + secondnumberarray[i]);
ourphotochats.remove().then(function() {
//console.log("PhotoChats Remove succeeded.")
})
.catch(function(error) {
//console.log("PhotoChats Remove failed: " + error.message)
});
}
}
firebase.database().ref("notifications/" + f_uid).once("value", function(snapshot) {
var objs = snapshot.val();
//console.log(objs);
if (snapshot.val()){
$.each(objs, function(i, obj) {
var targetdeleteid;
if (obj.from_uid == f_uid){targetdeleteid = obj.to_uid} else{targetdeleteid = obj.from_uid;}
var mynotifs = firebase.database().ref('notifications/' + f_uid + '/' + targetdeleteid);
mynotifs.remove().then(function() {
//console.log("my notifs Remove succeeded.")
})
.catch(function(error) {
//console.log("my notifs failed: " + error.message)
});
});
}
firebase.database().ref('users/' + f_uid).set({
auth_id : f_auth_id,
deleted:'Y'
});
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/deleteuser.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid} )
.done(function( data ) {
//console.log(data);
firebase.database().ref('/photostodelete/' + f_uid).once('value').then(function(snapshot) {
var objr = snapshot.val();
if (snapshot.val()){
$.each(objr, function(i, obj) {
$.each(obj, function(i, obk) {
firebase.database().ref('/photostodelete/' + obk.from_uid + '/' + obk.to_uid+'/'+ obk.id).remove();
var desertRef = storageRef.child(obk.photo_name);
// Delete the file
desertRef.delete().then(function() {
}).catch(function(error) {
//console.log(error);
});
});
});
}
FCMPlugin.unsubscribeFromTopic(f_uid);
cordova.plugins.notification.badge.set(0);
var loginmethod = window.localStorage.getItem("loginmethod");
if (loginmethod == '1'){logoutPlugin();}
else{logoutOpen();}
});
});
}).catch(function(error) {
// Handle error
});
});
});
});
}
function matchNavbar(){
if ($('.infopopup').length > 0) {
$( ".toolbarq" ).show();
$( ".photobrowserbar" ).css("background-color","#2196f3");
$( ".matchcolor" ).addClass('whitetext');
}
else {$( ".toolbarq" ).hide();}
}
function unmatchNavbar(){
if ($('.infopopup').length > 0) {
$( ".toolbarq" ).show();
$( ".photobrowserbar" ).css("background-color","#ccc");
$( ".matchcolor" ).removeClass('whitetext');
$( ".toolbarq" ).css("background-color","transparent");
}
else {$( ".toolbarq" ).hide();}
}
var notifloaded = false;
function establishNotif(){
if(notifcount) {firebase.database().ref('notifications/' + f_uid).off('value', notifcount);}
notifcount = firebase.database().ref('notifications/' +f_uid).on('value', function(snapshot) {
var notificationscount = 0;
var objs = snapshot.val();
//If existing notifications, get number of unseen messages, delete old notifications
if (snapshot.val()){
$.each(objs, function(i, obj) {
if (obj.to_uid == f_uid) {
if (obj.received =='Y') {
if (notifloaded){ $( ".arrowdivhome_" + obj.from_uid ).empty();$( ".indivnotifcount" ).remove();}
}
if (obj.received =='N') {
var addnumber;
if(obj.param == 'datedeleted' || obj.param =='newmatch'){addnumber = 1;}
else {addnumber = obj.new_message_count}
notificationscount = notificationscount + addnumber;
if (notifloaded){
if (obj.new_message_count > 0){
//alert('Not received, greater than 0 = ' +obj.new_message_count);
$( ".arrowdivhome_" + obj.from_uid ).empty();$( ".arrowdivhome_" + obj.from_uid ).append('<span class="badge" style="background-color:rgb(255, 208, 0);color:black;margin-top:5px;margin-left:-5px;">'+obj.new_message_count+'</span>');
$( ".indivnotifcount" ).remove();$( ".arrowdivbrowser" ).append('<span class="badge indivnotifcount" style="position:absolute;right:0px;background-color:rgb(255, 208, 0);color:black;">'+obj.new_message_count+'</span>');
cordova.plugins.notification.badge.set(notificationscount);
}
}
}
}
});
notifloaded = true;
//Update SQL notifcount
if (notificationscount !=0){
if (offsounds == 'Y'){}else{
$('#buzzer')[0].play();
//if ($('.chatpop').length > 0) {}
//else {$('#buzzer')[0].play();}
}
return false;
}
else{}
//$( ".notifspan" ).empty();
//$( ".notifspan" ).append(notificationscount);
}
});
}
function showPloader(){
$( ".ploader" ).css("z-index","9999999");myApp.closeModal();
}
function hidePloader(tabb){
var popupHTML = '<div class="popup prefpop">'+
'<div class="views tabs toolbar-fixed">'+
'<div id="tab1" class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="center" style="color:white;">Terms and Conditions of Use</div>'+
' <div class="right"><a href="#" onclick="showPloader();" style="color:white;">Done</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="home-1" class="page">'+
' <div class="page-content">'+
'<div class="content-block" style="margin-top:0px;">'+
' <div class="content-block-inner terms-inner" >'+
' </div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div id="tab2" class="view tab">'+
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="center" style="color:white;">Privacy Policy</div>'+
' <div class="right close-popup"><a href="#" onclick="showPloader();" class="close-popup" style="color:white;">Done</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="home-2" class="page">'+
' <div class="page-content">'+
'<div class="content-block" style="margin-top:0px;">'+
' <div class="content-block-inner privacy-inner">'+
' </div>'+
'</div>'+
'</div>'+
' </div>'+
'</div>'+
'</div>'+
'<div class="toolbar tabbar" style="padding:0px;background-color:#ccc;">'+
' <div class="toolbar-inner" style="padding:0px;">'+
' <a href="#tab1" onclick="tabOne();" class="tab1 tab-link active"><i class="pe-7s-note2 pe-lg"></i></a>'+
' <a href="#tab2" onclick="tabTwo();" class="tab2 tab-link"><i class="pe-7s-look pe-lg"></i></a>'+
'</div>'+
'</div>'+
'</div>'+
'</div>';
myApp.popup(popupHTML);
$( ".ploader" ).css("z-index","10000");
if (tabb) {
tabTwo();
}
else {tabOne();}
}
function tabOne(){
$( "#tab1" ).addClass('active');
$( "#tab2" ).removeClass('active');
myApp.sizeNavbars();
$( ".tab1" ).addClass('active');
$( ".tab2" ).removeClass('active');
$.get( "http://www.dateorduck.com/terms.html", function( data ) {
$( ".terms-inner" ).html(data);
});
}
function tabTwo(){
$( "#tab1" ).removeClass('active');
$( "#tab2" ).addClass('active');
myApp.sizeNavbars();
$( ".tab1" ).removeClass('active');
$( ".tab2" ).addClass('active');
$.get( "http://www.dateorduck.com/privacy.html", function( data ) {
$( ".privacy-inner" ).html(data);
});
}
//check if on mobile
//}
var pagingalbumurl;
var pagingurl;
var photonumber;
var albumend;
var addedsmallarray;
var addedlargearray;
var addedheight = [];
var addedwidth = [];
function getPhotos(albumid){
$( ".photoloader").show();
$( ".loadmorebuttonphotos").hide();
var retrieveurl;
if (!pagingurl) {photonumber = 0;retrieveurl = 'https://graph.facebook.com/v2.4/'+albumid+'/photos?limit=8&fields=id,source,width,height&access_token=' + f_token}
else {retrieveurl = pagingurl}
$.getJSON(retrieveurl,
function(response) {
$( ".swipebuttondone").addClass("disabled");
$( ".photoloader").hide();
if (response.data.length === 0){$( ".loadmorebuttonphotos").hide();$( "#nophotosfound").show();return false;}
//console.log(response);
pagingurl = response.paging.next;
for (i = 0; i < response.data.length; i++) {
var alreadyselected = addedsmallarray.indexOf(response.data[i].source);
//console.log(response.data[i]);
if (alreadyselected == -1) {
swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+'" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:none;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"><br></div>');
}
else {
swiperPhotos.appendSlide('<div class="swiper-slide slidee slidee_'+photonumber+' largeurl_'+response.data[i].source+' smallurl_'+response.data[i].source+' id_'+response.data[i].id+' slidee-selected" style="background-image:url(\''+response.data[i].source+'\');height:180px;width:180px;background-size:cover;background-position:50% 50%;"><div style="width:40px;height:40px;border-radius:50%;position:absolute;top:50%;left:50%;margin-left:-28px;margin-top:-28px;"><i class="pe-7s-check check_'+photonumber+' pe-4x" style="display:block;color:#4cd964;"></i></div><input type="hidden" class="width_'+response.data[i].id+'" value="'+response.data[i].width+'"><input type="hidden" class="height_'+response.data[i].id+'" value="'+response.data[i].height+'"></div>');
}
photonumber ++;
}
if (response.data.length > 0 && response.data.length < 8) {
$( ".loadmorebuttonphotos").hide();$( "#nomorephotos").show();}
else{$( ".loadmorebuttonphotos").show();}
});
}
function closePhotos(){
$( ".albumblock").show();
$( ".leftalbum").show();
$( ".leftphoto").hide();
$( "#nomorephotos").hide();
$( "#nophotosfound").hide();
$( ".loadmorebuttonphotos").hide();
if (albumend === true){$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();}
else {$( ".loadmorebuttonalbums").show();$( "#nomorealbums").hide();}
swiperPhotos.removeAllSlides();
swiperPhotos.destroy();
photonumber = 0;
pagingurl = false;
}
function closeAlbums(){
myApp.closeModal('.photopopup');
addedsmallarray = [];
addedlargearray = [];
pagingalbumurl = false;
albumend = false;
$( ".swipebuttondone").removeClass("disabled");
}
function photosPopup(){
photosliderupdated = false;
addedsmallarray = f_smallurls;
addedlargearray = f_largeurls;
var popupHTML = '<div class="popup photopopup">'+
'<div class="views tabs toolbar-fixed">'+
'<div class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<i class="pe-7s-angle-left pe-3x leftalbum" onclick="closeAlbums()" style="margin-left:-10px;"></i>'+
'<i class="pe-7s-angle-left pe-3x leftphoto" onclick="closePhotos()" style="display:none;margin-left:-10px;"></i>'+
' </div>'+
' <div class="center photocount">'+
'0 photos selected'+
'</div>'+
' <div class="right"><a href="#" onclick="closeAlbums()" class="noparray" style="color:white;">Done</a><a href="#" class="yesparray" onclick="getPhotoURL()" style="display:none;color:white;">Save</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="photospage" class="page">'+
' <div class="page-content" style="padding-bottom:0px;background-color:white;">'+
'<div class="col-25 photoloader" style="position:absolute;top:50%;left:50%;margin-left:-13.5px;margin-top:-13.5px;">'+
' <span class="preloader"></span>'+
' </div>'+
'<div class="list-block media-list albumblock" style="margin:0px;z-index:999999;"><ul class="albumul" style="z-index:99999999999;"></ul></div>'+
'<div class="swiper-container swiper-photos">'+
' <div class="swiper-wrapper" >'+
'</div>'+
'</div>'+
'<a href="#" class="button loadmorebuttonalbums" onclick="loadAlbums()" style="font-size:17px;border:0;border-radius:0px;background-color:#2196f3;color:white;display:none;margin:10px;">Load more albums</a>'+
'<a href="#" class="button loadmorebuttonphotos" onclick="getPhotos()" style="font-size:17px;border:0;border-radius:0px;background-color:#2196f3;color:white;display:none;margin:10px;">Load more photos</a>'+
'<div id="nomorephotos" style="display:none;width:100%;text-align:center;"><p>No more photos available in this album.</p></div>'+
'<div id="nophotosfound" style="display:none;width:100%;text-align:center;"><p>No photos found in this album.</p></div>'+
'<div id="nomorealbums" style="display:none;width:100%;text-align:center;"><p>No more albums to load.</p></div>'+
'<div><div><div>'+
'<div>'+
'<div>'+
'</div>'
myApp.popup(popupHTML);
if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');}
else {$( ".photocount").text(addedlargearray.length + ' photos selected');}
photoPermissions();
}
function loadAlbums(){
$( ".photoloader").show();
$( ".loadmorebuttonalbums").hide();
var retrievealbumurl;
if (!pagingalbumurl) {retrievealbumurl = 'https://graph.facebook.com/v2.8/'+f_uid+'/albums?limit=20&fields=id,count,name&access_token=' + f_token}
else {retrievealbumurl = pagingalbumurl}
$.getJSON(retrievealbumurl,
function(response) {
if(response.data.length == 0){
myApp.alert('Upload photos to Facebook to make them available to use in this app.', 'No photos are available');myApp.closeModal('.photopopup');return false;
}
pagingalbumurl = response.paging.next;
if (response.data.length > 0){
for (i = 0; i < response.data.length; i++) {
$( ".albumul" ).append(
' <li onclick="getAlbum('+response.data[i].id+')">'+
' <div class="item-content">'+
' <div class="item-media">'+
' <i class="pe-7s-photo-gallery pe-lg"></i>'+
'</div>'+
'<div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title">'+response.data[i].name+'</div>'+
' <div class="item-after">'+response.data[i].count+'</div>'+
'</div>'+
'</div>'+
' </div>'+
' </li>'
);
}
}
if (response.data.length < 20) {$( ".loadmorebuttonalbums").hide();$( "#nomorealbums").show();$( ".photoloader").hide();albumend = true;}
else{$( ".loadmorebuttonalbums").show();}
});
}
function getAlbum(albumid){
$( ".albumblock").hide();
$( ".loadmorebuttonalbums").hide();
$( "#nomorealbums").hide();
$( ".leftalbum").hide();
$( ".leftphoto").show();
swiperPhotos = myApp.swiper('.swiper-photos', {
slidesPerView:2,
slidesPerColumn:1000,
virtualTranslate:true,
slidesPerColumnFill:'row',
spaceBetween: 3,
onClick:function(swiper, event){if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$( ".noparray").hide();
$( ".yesparray").show();
if ($( ".slidee_" + swiper.clickedIndex).hasClass('slidee-selected')){$( ".slidee_" + swiper.clickedIndex).removeClass('slidee-selected');$( ".close_" + swiper.clickedIndex).show();$( ".check_" + swiper.clickedIndex).hide();
var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", "");
var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", "");
var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", "");
var indexdeletedsm = addedsmallarray.indexOf(smallurl);
addedsmallarray.splice(indexdeletedsm, 1);
var indexdeletedsl = addedlargearray.indexOf(smallurl);
addedlargearray.splice(indexdeletedsl, 1);
addedheight.splice(indexdeletedsl, 1);
addedwidth.splice(indexdeletedsl, 1);
//console.log(addedheight);
}
else{$( ".slidee_" + swiper.clickedIndex).addClass('slidee-selected');$( ".close_" + swiper.clickedIndex).hide();$( ".check_" + swiper.clickedIndex).show();
var largeurl = swiper.clickedSlide.classList[3].replace("largeurl_", "");
var smallurl = swiper.clickedSlide.classList[4].replace("smallurl_", "");
var photoselectedid = swiper.clickedSlide.classList[5].replace("id_", "");
addedsmallarray.push(smallurl);
addedlargearray.push(largeurl);
var widthselected = $( ".width_"+photoselectedid).val();
var heightselected = $( ".height_"+photoselectedid).val();
addedheight.push(heightselected);
addedwidth.push(widthselected);
}
if (addedlargearray.length === 1){$( ".photocount").text(addedlargearray.length + ' photo selected');}
else {$( ".photocount").text(addedlargearray.length + ' photos selected');}
}
});
getPhotos(albumid);
swiperPhotos.updateContainerSize();
swiperPhotos.updateSlidesSize();
}
function getPhotoURL(){
photonumber = 0;
pagingurl = false;
pagingalbumurl = false;
albumend = false;
var newsmall = addedsmallarray.toString();
var newlarge = addedlargearray.toString();
var newwidth = addedwidth.toString();
var newheight = addedheight.toString();
firebase.database().ref('users/' + f_uid).update({
image_url:addedlargearray[0],
photoresponse:'Y'
}).then(function() {});
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
$( ".swipebuttondone").removeClass("disabled");
if (addedlargearray.length ===0){if ($( ".reorderbutton" ).hasClass( "disabled" )){}else {$( ".reorderbutton" ).addClass('disabled');}
if ($( ".deleteallbutton" ).hasClass( "disabled" )){}else {$( ".deleteallbutton" ).addClass('disabled');}
}
if (addedlargearray.length > 0){if ($( ".reorderbutton" ).hasClass( "disabled" )){$( ".reorderbutton" ).removeClass('disabled');}
if ($( ".deleteallbutton" ).hasClass( "disabled" )){$( ".deleteallbutton" ).removeClass('disabled');}
}
updatephotoslider();
//swiperPhotos.removeAllSlides();
//swiperPhotos.destroy();
myApp.closeModal('.photopopup');
});
}).catch(function(error) {
// Handle error
});
}
var photosliderupdated;
function updatephotoslider(){
$( ".yesparray").addClass("disabled");
if (photosliderupdated){return false;}
photosliderupdated = true;
myswiperphotos.removeAllSlides();
if (addedlargearray.length > 0){
myswiperphotos.removeAllSlides();
for (i = 0; i < addedlargearray.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+addedlargearray[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()">Remove</div></div>');
}
myswiperphotos.update();
$( ".photosliderinfo" ).addClass('pictures');
if (addedlargearray.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
addedsmallarray = [];
addedlargearray = [];
}
else {
myswiperphotos.removeAllSlides();
f_smallurls = [];
f_largeurls = [];
addedheight = [];
addedwidth = [];
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add photos to your profile below');
}
}
function reorderPhotos(){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
var popupHTML = '<div class="popup redorderpopup">'+
'<div class="views tabs toolbar-fixed">'+
'<div class="view tab active">'+
'<div class="navbar" style="background-color:#2196f3;color:white;">'+
' <div class="navbar-inner">'+
' <div class="left">'+
'<i class="pe-7s-angle-left pe-3x leftalbum" style="margin-left:-10px;" onclick="closeReorder()"></i>'+
' </div>'+
' <div class="center">'+
'Order Photos'+
'</div>'+
' <div class="right"><a href="#" onclick="changeOrder()" style="color:white;">Save</a></div>'+
'</div>'+
'</div>'+
'<div class="pages navbar-fixed">'+
' <div data-page="redorderpage" class="page">'+
' <div class="page-content" style="background-color:white;padding-bottom:0px;">'+
'<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;;padding-top:10px;padding-bottom:10px;">Drag photos to re-order</p>'+
' <div class="list-block media-list" style="width:25%;float:left;margin-top:0px;">'+
' <ul class="numbersul" style="background-color:transparent;">'+
' </ul>'+
'</div>'+
' <div class="list-block sortable" style="width:75%;float:left;margin-top:0px;">'+
' <ul class="sortableul">'+
' </ul>'+
'</div>'+
'<div><div><div>'+
'<div>'+
'<div>'+
'</div>'
myApp.popup(popupHTML);
for (i = 0; i < f_largeurls.length; i++) {
$( ".numbersul" ).append(
'<li style="margin-top:10px;">'+
' <div class="item-content" style="height:80px;">'+
'<div class="item-inner reorderinner">'+
' <div class="item-title badge" style="position:absolute;top:50%;left:50%;margin-top:-10px;margin-left:-20px;">'+i+'</div>'+
'</div>'+
' </div>'+
'</li>'
);
$( ".sortableul" ).append(
' <li style="margin-top:10px;">'+
' <div class="item-content sortdivb" data-width="'+addedwidth[i]+'" data-height="'+addedheight[i]+'" style="background-image:url(\''+f_largeurls[i]+'\');background-size:cover;background-position:50% 50%;height:80px;">'+
' </div>'+
' <div class="sortable-handler" style="width:100%;height:80px;"></div>'+
' </li>'
);
}
myApp.sortableOpen();
}
function closeReorder(){
myApp.closeModal('.redorderpopup');
}
function changeOrder(){
var newurl = [];
var newwidthchange = [];
var newheightchange = [];
$( ".sortdivb" ).each(function() {
var bg = $(this).css("background-image");
var valuewidth = $(this).attr("data-width");
var valueheight = $(this).attr("data-height");
bg = bg.replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
newurl.push(bg);
newwidthchange.push(valuewidth);
newheightchange.push(valueheight);
});
myswiperphotos.removeAllSlides();
for (i = 0; i < newurl.length; i++) {
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\''+newurl[i]+'\');background-size:cover;background-position:50% 50%;"><div class="button" style="border:0;border-radius:0px;background-color:#ff3b30;color:white;position:absolute;bottom:10px;right:5px;" onclick="deleteIndividual()"><i class="pe-7s-trash pe-lg"></i> Remove</div></div>');
}
myApp.closeModal('.redorderpopup');
myswiperphotos.update();
$( ".photosliderinfo" ).addClass('pictures');
if (f_largeurls.length === 1){ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photo to your profile');
}
else{ $( ".photosliderinfo" ).html('You have added '+f_largeurls.length+' photos to your profile');
}
var newsmall = newurl.toString();
var newlarge = newurl.toString();
var newwidth = newheightchange.toString();
var newheight = newheightchange.toString();
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
});
}).catch(function(error) {
// Handle error
});
f_largeurls = newurl;
firebase.database().ref('users/' + f_uid).update({
image_url:f_largeurls[0],
photoresponse:'Y'
}).then(function() {});
}
function deleteAllPhotos(){
myApp.confirm('Are you sure?', 'Remove all photos', function () {
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
deletedphoto = false;
myswiperphotos.removeAllSlides();
$( ".wrapper-photos" ).append('<div class="swiper-slide" style="height:250px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?width=828\');background-size:cover;background-position:50% 50%;\');"></div>');
$( ".photosliderinfo" ).removeClass('pictures');
$( ".photosliderinfo" ).html('Add');
$( ".photosliderinfo" ).html('Add photos to your profile below');
myswiperphotos.update();
$( ".reorderbutton" ).addClass('disabled');
$( ".deleteallbutton" ).addClass('disabled');
f_largeurls = [];
f_smallurls = [];
var newsmall = "";
var newlarge = "";
var newwidth = "";
var newheight = "";
firebase.database().ref('users/' + f_uid).update({
image_url:f_image,
photoresponse:'Y'
}).then(function() {});
firebase.auth().currentUser.getToken().then(function(idToken) {
$.post( "http://www.dateorduck.com/updatephotos.php", { projectid:f_projectid,token:idToken,currentid:firebase.auth().currentUser.uid,uid:f_uid,largeurls:newlarge,smallurls:newsmall,height:newheight,width:newwidth} )
.done(function( data ) {
//console.log('deleted all');
});
}).catch(function(error) {
// Handle error
});
});
}
var f_smallurls = [];
var f_largeurls = [];
var photosloaded;
function swipePopup(chosen){
$( '.picker-sub' ).hide();
myApp.closeModal('.picker-sub');
photosloaded = false;
var sliderwidth = $( document ).width();
var sliderheight = $( document ).height();
var popupHTML = '<div class="popup prefpop" style="z-index:11000">'+
'<div class="views tabs toolbar-fixed">'+
'<div id="tab99" class="view-99 view tab active">'+
//
'<div class="navbar" style="background-color:#2196f3;">'+
' <div class="navbar-inner">'+
' <div class="left" style="color:white;"></div>'+
' <div class="center swipetext" style="color:white;">Availability'+
//'<div style="width:70px;height:70px;border-radius:50%;background-image:url(\''+f_image+'\');background-size:cover;background-position:50% 50%;margin-top:30px;z-index:100;border:5px solid #2196f3"></div>'+
'</div>'+
' <div class="right"><a href="#" onclick="updateUser();" style="color:white;display:none" class="donechange swipebuttondone">Done</a><a href="#" style="color:white;display:none;" class="close-popup doneunchange swipebuttondone">Done</a></div>'+
'</div>'+
'</div>'+
' <div class="pages">'+
' <div data-page="home-3" class="page">'+
'<div class="toolbar tabbar swipetoolbar" style="background-color:#ccc;z-index:9999999999;position:absolute;bottom:0px;">'+
' <div class="toolbar-inner" style="padding:0;">'+
// ' <a href="#" class="button tab-link tab-swipe pan0 active" onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-filter pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan0 " onclick="swipePref(0)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan1" onclick="swipePref(1)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan2" onclick="swipePref(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe pan3" onclick="swipePref(3)" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
'</div>'+
'</div>'+
' <div class="page-content" style="height: calc(100% - 44px);background-color:white;">'+
'<div class="swiper-container swiper-prefer" style="padding-top:54px;margin-bottom:-44px;">'+
'<div class="swiper-wrapper">'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-0">'+
'<div class="list-block media-list availblock" style="margin-bottom:0px;margin-top:0px;">'+
' <ul class="availul" style="padding-left:10px;padding-right:10px;padding-bottom:20px;">'+
' </ul>'+
'<div class="list-block-label hiderowpref" style="margin-top:10px;">Make it easier for your matches to organise a time to meet you.</div>'+
'</div> '+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-1">'+
'<div style="background-color:transparent;width:100%;padding-bottom:10px;" class="registerdiv">'+
'<div style="border-radius:50%;width:70px;height:70px;margin:0 auto;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
'</div>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul class="aboutul">'+
'<div class="list-block-label registerdiv" style="margin-top:10px;margin-bottom:10px;">To get started, tell us about you and who you are looking to meet. </div>'+
'<li class="newam" style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label">I am</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="picker-describe">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li class="newme">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label">Preference</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="picker-describe2">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li class="align-top hiderowpref">'+
' <div class="item-content">'+
//'<div class="item-media" style="border-radius:50%;width:70px;height:70px;background-image:url(\'https://graph.facebook.com/'+f_uid+'/picture?type=normal\');background-size:cover;background-position:50% 50%;"></div>'+
' <div class="item-inner">'+
'<div class="item-title label">About Me</div>'+
' <div class="item-input">'+
' <textarea class="resizable" onkeyup="keyUp()" maxlength="100" id="userdescription" style="width: calc(100% - 40px);min-height:88px;max-height:176px;" placeholder="Hide"></textarea>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'<p id="maxdescription" class="hiderowpref" style="float:right;color:#ccc;font-size:12px;margin-top:-20px;margin-right:5px;margin-bottom:-5px;">0 / 100</p>'+
' <li class="hiderowpref hometownli" style="clear:both;margin-top:0px;">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Hometown</div>'+
' <div class="item-input hometown-input">'+
' <textarea class="resizable" id="homesearch" onclick="newHometown()" onblur="checkHometown()" placeholder="Hide" style="min-height:60px;max-height:132px;"></textarea>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Status</div>'+
' <div class="item-input status-div">'+
' <input type="text" placeholder="Hide" id="status-input" name="name" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Industry</div>'+
' <div class="item-input industry-div">'+
' <input type="text" id="industry-input" name="name" placeholder="Hide" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Zodiac</div>'+
' <div class="item-input zodiac-div">'+
' <input type="text" id="zodiac-input" name="name" placeholder="Hide" readonly >'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Politics</div>'+
' <div class="item-input politics-div">'+
' <input type="text" id="politics-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Religion</div>'+
' <div class="item-input religion-div">'+
' <input type="text" id="religion-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Ethnicity</div>'+
' <div class="item-input ethnicity-div">'+
' <input type="text" id="ethnicity-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Eye color</div>'+
' <div class="item-input eyes-div">'+
' <input type="text" id="eyes-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Body Type</div>'+
' <div class="item-input body-div">'+
' <input type="text" id="body-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Height</div>'+
' <div class="item-input height-div">'+
' <input type="text" id="height-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
' <li class="hiderowpref">'+
'<div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title label">Weight</div>'+
' <div class="item-input weight-div">'+
' <input type="text" id="weight-input" name="name" placeholder="Hide" readonly>'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'</ul>'+
'<div class="list-block-label hiderowpref" style="margin-bottom:0px;">All fields are optional and will be hidden on your profile unless completed.</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-2">'+
'<div class="col-25 photoswiperloader" style="width:57.37px;top:50%;margin-top: -28.7px;top:50%;position: absolute;left: 50%;margin-left: -28.7px;">'+
' <span class="preloader"></span>'+
' </div>'+
'<div class="swiper-container container-photos" style="width:'+sliderwidth+'px;height:250px;">'+
'<div class="swiper-wrapper wrapper-photos">'+
'</div>'+
'<div class="swiper-pagination"></div>'+
'</div>'+
'<p style="width:100%;text-align:center;background-color:#ccc;color:#6d6d72;padding-top:10px;padding-bottom:10px;" class="photosliderinfo"></p>'+
' <div class="buttons-row">'+
'<a href="#" class="button active" onclick="photosPopup();" style="font-size:17px;border:0;border-radius:0px;background-color:#4cd964;margin-left:5px;margin-right:5px;">Edit</a>'+
'<a href="#" class="button reorderbutton active disabled" onclick="reorderPhotos();" style="font-size:17px;border:0;border-radius:0px;margin-right:5px;">Re-order</a>'+
'<a href="#" class="button deleteallbutton active disabled" onclick="deleteAllPhotos();" style="font-size:17px;border:0;border-radius:0px;margin-right:5px;background-color:#ff3b30;color:white">Clear</a>'+
'</div>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul">'+
'<div class="list-block-label hiderowpref" style="margin-bottom:0px;">Photos can be uploaded from your Facebook account.</div>'+
'</ul></div>'+
'</div>'+
'</div>'+
'<div class="swiper-slide">'+
'<div class="slide-pref pref-3">'+
'<div class="content-block-title" style="margin-top:20px;">Search options</div>'+
// '<p class="buttons-row" style="padding-left:10px;padding-right:10px;">'+
// '<a href="#" id="distance_10" onclick="changeRadius(10)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">10 km</a>'+
// '<a href="#" id="distance_25" onclick="changeRadius(25)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">25 km</a>'+
// '<a href="#" id="distance_50" onclick="changeRadius(50)" class="button button-round radiusbutton active" style="border:0;border-radius:0px;">50 km</a>'+
// '<a href="#" id="distance_100" onclick="changeRadius(100)" class="button button-round radiusbutton" style="border:0;border-radius:0px;">100 km</a>'+
//'</p>'+
'<div class="list-block" style="margin-top:0px;">'+
' <ul>'+
'<li style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label" style="width:120px;">Search radius</div>'+
' <div class="item-input">'+
' <input type="text" placeholder="..." readonly id="distance-input">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'<li style="clear:both;">'+
' <div class="item-content">'+
' <div class="item-inner">'+
'<div class="item-title label" style="width:120px;"></div>'+
' <div class="item-input">'+
' </div>'+
' </div>'+
'</div>'+
'</li>'+
'</ul>'+
'</div>'+
'<div class="content-block-title" style="margin-top:-54px;">Sounds</div>'+
' <div class="list-block media-list">'+
'<ul>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-inner" style="float:left;">'+
'<div class="item-title label" style="width:calc(100% - 62px);float:left;font-size:17px;font-weight:normal;">Turn off sounds</div>'+
' <div class="item-input" style="width:52px;float:left;">'+
'<label class="label-switch">'+
' <input type="checkbox" id="soundnotif" onchange="processUpdate(); myApp.sizeNavbars();">'+
'<div class="checkbox" ></div>'+
' </label>'+
' </div>'+
' </div>'+
' </div>'+
'</li>'+
'<div class="content-block-title" style="margin-top:20px;">Blocked profiles</div>'+
' <li>'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title button blockbutton active disabled" onclick="unblock()" style="font-size:17px;border:0;border-radius:0px;">Unblock all </div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'<div class="content-block-title" style="margin-top:20px;">My Account</div>'+
'<li onclick="logout()">'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title active button" style="border:0;border-radius:0px;font-size:17px;">Logout</div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
' <li onclick="deleteAccount()">'+
' <div class="item-content">'+
' <div class="item-inner">'+
' <div class="item-title-row">'+
' <div class="item-title button" style="font-size:17px;border-color:#ff3b30;background-color:#ff3b30;color:white;border:0;border-radius:0px;">Delete Account</div>'+
'</div>'+
' </div>'+
' </div>'+
'</li>'+
'</ul>'+
'</div> '+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
' </div>'+
'</div>'+
'</div>'+
//tabs
'</div>'+
'</div>'+
//tabs
'</div>';
myApp.popup(popupHTML);
if (blocklist){
if (blocklist.length){$( ".blockbutton" ).removeClass('disabled');}
}
if(sexuality){$( ".doneunchange" ).show();$( ".registerdiv" ).hide();$('.hiderowpref').removeClass('hiderowpref');}
if(!sexuality){
$( ".swipetoolbar" ).hide();
}
//if (radiussize) {distancepicker.cols[0].setValue(radiussize);}
distancepicker = myApp.picker({
input: '#distance-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + ($( document ).width()/2) + "px");distancepicker.cols[0].setValue(radiussize);distancepicker.cols[1].setValue(radiusunit);if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onClose:function (p, values, displayValues){radiussize = distancepicker.value[0];
radiusunit = distancepicker.value[1];},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'Search Distance'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ('1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100').split(' ')
},
{
textAlign: 'left',
values: ('Kilometres Miles').split(' ')
},
]
});
var industrypicker = myApp.picker({
input: '#industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
var findustrypicker = myApp.picker({
input: '#f-industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (f_industry_u) {findustrypicker.cols[0].setValue(f_industry_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }
},
onChange:function (p, values, displayValues){$( '#f-industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'f_industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
var statuspicker = myApp.picker({
input: '#status-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);} if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'status\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated']
}
]
});
var heightpicker = myApp.picker({
input: '#height-input',
onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");},
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
heightpicker.cols[0].setValue(heightset);}},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'height\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')']
},
]
});
var weightpicker = myApp.picker({
input: '#weight-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (weight_u) {
weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}},
onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'weight\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="center">' +
'Weight'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: (function () {
var arr = [];
for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); }
return arr;
})(),
},
]
});
var bodypicker = myApp.picker({
input: '#body-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (body_u) {bodypicker.cols[0].setValue(body_u);}},
onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'body\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant']
}
]
});
var eyespicker = myApp.picker({
input: '#eyes-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}},
onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'eyes\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other']
}
]
});
var ethnicitypicker = myApp.picker({
input: '#ethnicity-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}},
onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'ethnicity\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White']
}
]
});
var politicspicker = myApp.picker({
input: '#politics-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (politics_u) {politicspicker.cols[0].setValue(politics_u);}},
onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'politics\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested']
}
]
});
var zodiacpicker = myApp.picker({
input: '#zodiac-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}},
onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'zodiac\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces']
}
]
});
var religionpicker = myApp.picker({
input: '#religion-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (sexuality){processUpdate(); myApp.sizeNavbars(); } if (religion_u) {religionpicker.cols[0].setValue(religion_u);}},
onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'religion\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other']
}
]
});
$( ".slide-pref" ).hide();
mySwiper = myApp.swiper('.swiper-prefer', {
onSlideChangeEnd:function(swiper){$( ".page-content" ).scrollTop( 0 );},
onInit:function(swiper){$( ".swipetoolbar" ).show();$( ".pan" + swiper.activeIndex ).addClass('active');},
onSlideChangeStart:function(swiper){
$( ".page-content" ).scrollTop( 0 );
$( ".tab-swipe").removeClass('active');
$( ".pan" + swiper.activeIndex ).addClass('active');
if (swiper.activeIndex == 0){$( ".swipetext" ).text('Availability');
$( ".slide-pref" ).hide();$( ".pref-0").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 1){$( ".swipetext" ).text('Profile');
$( ".slide-pref" ).hide();$( ".pref-1").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 2){$( ".swipetext" ).text('Photos');getData();
$( ".slide-pref" ).hide();$( ".pref-2").show();$( ".swipetoolbar" ).show();
}
if (swiper.activeIndex == 3){$( ".swipetext" ).text('Settings');
$( ".slide-pref" ).hide();$( ".pref-3").show();$( ".swipetoolbar" ).show();
}
if (!sexuality){$( '.swipetext' ).text("Welcome, " + f_first);mySwiper.lockSwipes();}
}
});
swipePref(chosen);
setTimeout(function(){ $( ".swipetoolbar" ).show(); }, 3000);
myApp.sizeNavbars();
var dateinfo = [];
var s_namesonly = [];
var d = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var daynumber;
var todayday = weekday[d.getDay()];
//console.log(todayday);
s_namesonly.push(todayday);
var f_available_array;
var s_alldays_values = [];
var s_alldays_names = [];
var tonight = new Date();
tonight.setHours(23,59,59,999);
var tonight_timestamp = Math.round(tonight/1000);
daynumber;
daynumber = d.getDate();
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
dateinfo.push(daynumber + dending + ' ' + monthNames[d.getMonth()] + ', ' + d.getFullYear());
s_alldays_values.push(tonight_timestamp);
s_alldays_names.push('Today');
var tomorrow_timestamp = tonight_timestamp + 86400;
var tomorrowdate = new Date(Date.now() + 86400);
var tomorroww = new Date(d.getTime() + 24 * 60 * 60 * 1000);
var tomorrowday = weekday[tomorroww.getDay()];
daynumber = tomorroww.getDate();
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
dateinfo.push(daynumber + dending + ' ' + monthNames[tomorrowdate.getMonth()] + ', ' + tomorrowdate.getFullYear());
//console.log('tomorrow is' + tomorrowday);
s_namesonly.push(tomorrowday);
s_alldays_values.push(tomorrow_timestamp);
s_alldays_names.push('Tomorrow');
for (i = 1; i < 7; i++) {
var newunix = tomorrow_timestamp + (86400 * i);
s_alldays_values.push(newunix);
var dat_number = i + 1;
var datz = new Date(Date.now() + dat_number * 24*60*60*1000);
daynumber = datz.getDate();
var dending;
if (daynumber == '1' || daynumber == '21' || daynumber == '31'){dending = 'st'}
else if (daynumber == '2' || daynumber == '22'){dending = 'nd'}
else if (daynumber == '3' || daynumber == '23'){dending = 'rd'}
else {dending = 'th'}
n = weekday[datz.getDay()];
qqq = weekday[datz.getDay() - 1];
//console.log(n);
s_alldays_names.push(n + ' ' + daynumber + dending);
dateinfo.push(daynumber + dending + ' ' + monthNames[datz.getMonth()] + ', ' + datz.getFullYear());
s_namesonly.push(n);
}
s_namesonly.push(n);
//console.log(s_namesonly);
//console.log(s_alldays_values);
for (i = 0; i < s_alldays_names.length; i++) {
if (i==0 | i==2 || i==4 || i==6){
$( ".availul" ).append(
'<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+
'<div class="readd_'+s_alldays_values[i]+'"></div>'+
' <input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">'
);
setPicker();
}
else if (i==1 || i==3 || i==5 || i==7) {
$( ".availul" ).append(
'<li class="li_'+s_alldays_values[i]+' availrec" id="aa_'+s_alldays_values[i]+'" style="height:44px;float:left;width:100%;text-align:center;margin-bottom:10px;padding-top:10px;color:white;" onclick="openAvail('+s_alldays_values[i]+')">'+
'<div class="readd_'+s_alldays_values[i]+'"></div>'+
'<input type="text" placeholder="'+s_alldays_names[i]+'" readonly id="picker'+s_alldays_values[i]+'" style="height:44px;text-align:center;margin-top:-10px;font-size:17px;color:white;"></li><input type="hidden" class="suppdate_'+s_alldays_values[i]+'" value="'+dateinfo[i]+'">'
);
setPicker();
}
var alreadyavailchosen = 0;
var columnone;
var columntwo;
var idtochange;
for(var k = 0; k < availarray.length; k++) {
if (availarray[k].id == s_alldays_values[i]){
alreadyavailchosen = 1;columntwo = availarray[k].time;columnone = availarray[k].day;
idtochange = s_alldays_values[i];$( '.li_'+ idtochange ).addClass('selecrec');$( "#picker"+ idtochange ).val( columnone + " " + columntwo ); }
else{
alreadyavailchosen = 0;
}
}
function setPicker(){
var myavailpicker = myApp.picker({
input: '#picker' + s_alldays_values[i],
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeAvail(\''+s_alldays_values[i]+'\',\''+s_alldays_names[i]+'\',\''+s_namesonly[i]+'\');">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: (s_namesonly[i] + ',').split(',')
},
{
textAlign: 'left',
values: ('Anytime Morning Midday Afternoon Evening').split(' ')
},
]
});
}
}
if (myphotosarray){
}
else {
}
if (f_description){
$( "#userdescription" ).val(f_description);
var inputlengthd = $( "#userdescription" ).val().length;
$( "#maxdescription" ).text(inputlengthd + ' / 100 ');
}
if (radiussize){
$( ".radiusbutton" ).removeClass( "active" );
$( "#distance_" + radiussize ).addClass( "active" );
}
if (offsounds == 'Y'){$('#soundnotif').prop('checked', true);}
else{$('#soundnotif').prop('checked', false);}
if (f_age) {$( ".savebutton" ).removeClass('disabled');}
if (!sexuality){$( "#distance-input" ).val( '100 Kilometres');}
else {$( "#distance-input" ).val( radiussize + ' ' +radiusunit);
}
if(hometown_u){$( "#homesearch" ).val( hometown_u );}
if(industry_u){$( "#industry-input" ).val( industry_u );}
if(status_u){$( "#status-input" ).val( status_u );}
if(politics_u){$( "#politics-input" ).val( politics_u );}
if(eyes_u){$( "#eyes-input" ).val( eyes_u );}
if(body_u){$( "#body-input" ).val( body_u );}
if(religion_u){$( "#religion-input" ).val( religion_u );}
if(zodiac_u){$( "#zodiac-input" ).val( zodiac_u );}
if(ethnicity_u){$( "#ethnicity-input" ).val( ethnicity_u );}
if(weight_u){$( "#weight-input" ).val( weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)' );}
if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
$( "#height-input" ).val( heightset );
}
if (f_age && f_gender) {$( "#picker-describe" ).val( f_gender + ", " + f_age );}
if (f_interested) {$( "#picker-describe2" ).val( f_interested + ", between " + f_lower + ' - ' + f_upper );}
pickerDescribe = myApp.picker({
input: '#picker-describe',
rotateEffect: true,
onClose:function (p){
$( ".popup-overlay" ).css("z-index","10500");
},
onOpen: function (p){
if (sexuality){processUpdate(); myApp.sizeNavbars(); }
$('.picker-items-col').eq(0).css('width','50%');
$('.picker-items-col').eq(1).css('width','50%');
// $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");
var gendercol = pickerDescribe.cols[0];
var agecol = pickerDescribe.cols[1];
if (f_age) {agecol.setValue(f_age);}
if (f_gender) {gendercol.setValue(f_gender);}
},
onChange: function (p, value, displayValue){
if (!f_age){
var fpick = pickerDescribe.value;
var spick = pickerDescribe2.value;
if (fpick && spick) {
if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); }
$( ".savebutton" ).removeClass( "disabled" );}
else {$( ".savebutton" ).addClass( "disabled" );}
}
},
formatValue: function (p, values, displayValues) {
return displayValues[0] + ', ' + values[1];
}, toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'I Am'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: ('Male Female').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
]
});
pickerDescribe2 = myApp.picker({
input: '#picker-describe2',
rotateEffect: true,
onClose:function (p){
$( ".popup-overlay" ).css("z-index","10500");
},
onChange: function (p, value, displayValue){
if (!f_age){
var fpick = pickerDescribe.value;
var spick = pickerDescribe2.value;
if (fpick && spick) {
if(!sexuality){sexuality=true;$( ".registerdiv" ).slideUp();$('.hiderowpref').removeClass('hiderowpref');$( ".swipetoolbar" ).show();$( '.swipetext' ).text("Profile");mySwiper.unlockSwipes();$( ".donechange" ).show();$( ".doneunchange" ).hide();myApp.sizeNavbars(); }
$( ".savebutton" ).removeClass( "disabled" );}
else {$( ".savebutton" ).addClass( "disabled" );}
}
},
onOpen: function (p){if (sexuality){processUpdate(); myApp.sizeNavbars(); }
// $( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");
$('.picker-items-col').eq(0).css('width','33%');
$('.picker-items-col').eq(1).css('width','33%');
$('.picker-items-col').eq(2).css('width','33%');
var interestedcol = pickerDescribe2.cols[0];
var lowercol = pickerDescribe2.cols[1];
var uppercol = pickerDescribe2.cols[2];
if (f_interested) {interestedcol.setValue(f_interested);}
if (f_lower) {lowercol.setValue(f_lower);}
if (f_upper) {uppercol.setValue(f_upper);}
},
formatValue: function (p, values, displayValues) {
if (values[1] > values[2]) { return displayValues[0] + ', between ' + values[2] + ' - ' + values[1];}
else { return displayValues[0] + ', between ' + values[1] + ' - ' + values[2];
}
}, toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left">' +
'Preference'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
textAlign: 'left',
values: ('Men Women').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
{
values: ('18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99').split(' ')
},
]
});
}
function swipePref(index){$( ".swipetoolbar" ).show();$( ".pref-" + index).show();mySwiper.slideTo(index); $( ".swipetoolbar" ).show();
}
function navPicker(){
myApp.pickerModal(
'<div class="picker-modal picker-sub" style="height:88px;">' +
'<div class="toolbar tabbar" style="z-index:9999;background-color:#ccc;">' +
'<div class="toolbar-inner" style="padding:0;">' +
' <a href="#" class="button tab-link tab-swipe home1 " onclick="swipePopup(0);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-clock pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home2" onclick="swipePopup(1);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-info pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home3" onclick="swipePopup(2);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-camera pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
' <a href="#" class="button tab-link tab-swipe home4" onclick="swipePopup(3);" style="border-radius:0;font-size:17px;border:0;text-align:center;"><i class="pe-7s-config pe-lg" style="width:22px;margin:0 auto;"></i></a>'+
'</div>' +
'</div>' +
'<div class="picker-modal-inner close-picker" style="height:44px;background-color:#2196f3;text-align:center;">' +
'<i class="pe-7s-angle-down pe-2x " style="font-size:34px;margin-top:5px;color:white;"></i>'+
'</div>' +
'</div>'
);
}
function removeProfileSet(pickertype){
$( "#" + pickertype + "-input").remove();
$( "." + pickertype + "-div").append( '<input type="text" id="'+pickertype+'-input" name="name" placeholder="Hide" readonly >' );
if (pickertype=='industry'){
var industrypicker = myApp.picker({
input: '#industry-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (industry_u) {industrypicker.cols[0].setValue(industry_u);}
},
onChange:function (p, values, displayValues){$( '#industry-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'industry\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Accounting', 'Administration','Advertising','Agriculture','Banking and finance', 'Business', 'Charity', 'Creative arts','Construction','Consulting', 'Design', 'Education','Energy','Events', 'Engineering','Environment','Healthcare','Hospitality','HR and Recruitment', 'IT','Law','Law Enforcement','Leisure','Management','Manufacturing', 'Marketing','Media','Other','Pharmaceuticals','PR','Property','Public Services','Retail','Sales','Science','Security','Social Care','Small business','Sport','Tourism','Transport','Utilities','Voluntary work']
}
]
});
}
if (pickertype=='status'){
var statuspicker = myApp.picker({
input: '#status-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (status_u) {statuspicker.cols[0].setValue(status_u);}},
onChange:function (p, values, displayValues){$( '#status-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'status\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Single', 'Married', 'Engaged','Open relationship', 'Committed relationship','It\'s Complicated']
}
]
});
}
if (pickertype=='politics'){
var politicspicker = myApp.picker({
input: '#politics-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (politics_u) {politicspicker.cols[0].setValue(politics_u);}},
onChange:function (p, values, displayValues){$( '#politics-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'politics\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Left / Liberal', 'Centre','Right / Conservative','Not interested']
}
]
});
}
if (pickertype=='zodiac'){
var zodiacpicker = myApp.picker({
input: '#zodiac-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (zodiac_u) {zodiacpicker.cols[0].setValue(zodiac_u);}},
onChange:function (p, values, displayValues){$( '#zodiac-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'zodiac\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn','Aquarius','Pisces']
}
]
});
}
if (pickertype=='religion'){
var religionpicker = myApp.picker({
input: '#religion-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (religion_u) {religionpicker.cols[0].setValue(religion_u);}},
onChange:function (p, values, displayValues){$( '#religion-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'religion\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Atheist','Agnostic','Christianity','Islam','Buddhism','Hindusim','Sikhism','Judaism','Other']
}
]
});
}
if (pickertype=='ethnicity'){
var ethnicitypicker = myApp.picker({
input: '#ethnicity-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (ethnicity_u) {ethnicitypicker.cols[0].setValue(ethnicity_u);}},
onChange:function (p, values, displayValues){$( '#ethnicity-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'ethnicity\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Asian', 'Black', 'Latin / Hispanic','Mixed','Middle Eastern','Native American','Other','Pacific Islander','White']
}
]
});
}
if (pickertype=='height'){
var heightpicker = myApp.picker({
input: '#height-input',
onChange:function (p, values, displayValues){$( '#height-input' ).addClass("profilevaluechosen");},
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (height_u) {
if (height_u == 122) {var heightset = '122 cm (4\' 0\'\')';}
if (height_u == 124) {var heightset = '124 cm (4\' 1\'\')';}
if (height_u == 127) {var heightset = '127 cm (4\' 2\'\')';}
if (height_u == 130) {var heightset = '130 cm (4\' 3\'\')';}
if (height_u == 132) {var heightset = '132 cm (4\' 4\'\')';}
if (height_u == 135) {var heightset = '135 cm (4\' 5\'\')';}
if (height_u == 137) {var heightset = '137 cm (4\' 6\'\')';}
if (height_u == 140) {var heightset = '140 cm (4\' 7\'\')';}
if (height_u == 142) {var heightset = '142 cm (4\' 8\'\')';}
if (height_u == 145) {var heightset = '145 cm (4\' 9\'\')';}
if (height_u == 147) {var heightset = '147 cm (4\' 10\'\')';}
if (height_u == 150) {var heightset = '150 cm (4\' 11\'\')';}
if (height_u == 152) {var heightset = '152 cm (5\' 0\'\')';}
if (height_u == 155) {var heightset = '155 cm (5\' 1\'\')';}
if (height_u == 157) {var heightset = '157 cm (5\' 2\'\')';}
if (height_u == 160) {var heightset = '160 cm (5\' 3\'\')';}
if (height_u == 163) {var heightset = '163 cm (5\' 4\'\')';}
if (height_u == 165) {var heightset = '165 cm (5\' 5\'\')';}
if (height_u == 168) {var heightset = '168 cm (5\' 6\'\')';}
if (height_u == 170) {var heightset = '170 cm (5\' 7\'\')';}
if (height_u == 173) {var heightset = '173 cm (5\' 8\'\')';}
if (height_u == 175) {var heightset = '175 cm (5\' 9\'\')';}
if (height_u == 178) {var heightset = '178 cm (5\' 10\'\')';}
if (height_u == 180) {var heightset = '180 cm (5\' 11\'\')';}
if (height_u == 183) {var heightset = '183 cm (6\' 0\'\')';}
if (height_u == 185) {var heightset = '185 cm (6\' 1\'\')';}
if (height_u == 188) {var heightset = '185 cm (6\' 2\'\')';}
if (height_u == 191) {var heightset = '191 cm (6\' 3\'\')';}
if (height_u == 193) {var heightset = '193 cm (6\' 4\'\')';}
if (height_u == 195) {var heightset = '195 cm (6\' 5\'\')';}
if (height_u == 198) {var heightset = '198 cm (6\' 6\'\')';}
if (height_u == 201) {var heightset = '201 cm (6\' 7\'\')';}
if (height_u == 203) {var heightset = '203 cm (6\' 8\'\')';}
heightpicker.cols[0].setValue(heightset);}},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'height\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['122 cm (4\' 0\'\')','124 cm (4\' 1\'\')','127 cm (4\' 2\'\')','130 cm (4\' 3\'\')','132 cm (4\' 4\'\')','135 cm (4\' 5\'\')','137 cm (4\' 6\'\')','140 cm (4\' 7\'\')','142 cm (4\' 8\'\')','145 cm (4\' 9\'\')','147 cm (4\' 10\'\')','150 cm (4\' 11\'\')','152 cm (5\' 0\'\')','155 cm (5\' 1\'\')','157 cm (5\' 2\'\')','160 cm (5\' 3\'\')','163 cm (5\' 4\'\')','165 cm (5\' 5\'\')','168 cm (5\' 6\'\')','170 cm (5\' 7\'\')','173 cm (5\' 8\'\')','175 cm (5\' 9\'\')','178 cm (5\' 10\'\')','180 cm (5\' 11\'\')','183 cm (6\' 0\'\')','185 cm (6\' 1\'\')','188 cm (6\' 2\'\')','191 cm (6\' 3\'\')','193 cm (6\' 3\'\')','195 cm (6\' 4\'\')','198 cm (6\' 5\'\')','201 cm (6\' 6\'\')','203 cm (6\' 8\'\')']
},
]
});
}
if (pickertype=='weight'){
var weightpicker = myApp.picker({
input: '#weight-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (weight_u) {
weightpicker.cols[0].setValue(weight_u + ' kg (' + Math.round(weight_u* 2.20462262) + ' lbs)');}},
onChange:function (p, values, displayValues){$( '#weight-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'weight\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="center">' +
'Weight'+
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: (function () {
var arr = [];
for (var i = 45; i <= 150; i++) { arr.push(i + ' kg (' + Math.round(i* 2.20462262) + ' lbs)'); }
return arr;
})(),
},
]
});
}
if (pickertype=='eyes'){var eyespicker = myApp.picker({
input: '#eyes-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (eyes_u) {eyespicker.cols[0].setValue(eyes_u);}},
onChange:function (p, values, displayValues){$( '#eyes-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'eyes\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Amber', 'Blue', 'Brown','Grey','Green','Hazel','Other']
}
]
});
}
if (pickertype=='body'){
var bodypicker = myApp.picker({
input: '#body-input',
onOpen: function (p){$( '.picker-items-col-wrapper' ).css("width", + $( document ).width() + "px");if (body_u) {bodypicker.cols[0].setValue(body_u);}},
onChange:function (p, values, displayValues){$( '#body-input' ).addClass("profilevaluechosen");},
toolbarTemplate:
'<div class="toolbar">' +
'<div class="toolbar-inner">' +
'<div class="left" onclick="removeProfileSet(\'body\')">' +
'<a href="#" class="link close-picker" style="color:#ff3b30">Cancel</a>' +
'</div>' +
'<div class="right">' +
'<a href="#" class="link close-picker">Done</a>' +
'</div>' +
'</div>' +
'</div>',
cols: [
{
values: ['Athletic','Average', 'Slim', 'Large', 'Muscular','Unimportant']
}
]
});
}
}
function actionSheet(){
var first_number,second_number;
if (Number(f_uid) > Number(targetid) ) {second_number = f_uid;first_number = targetid;}
else {first_number = f_uid;second_number = targetid;}
if ($('.chatpop').length === 0 || ($('.chatpop').length === 1 && $('.chatpop').css('z-index') === '10000')){
var disabledattribute;
if (targetreported){disabledattribute=true;}else{disabledattribute=false;}
var buttons = [
{
text: 'View Profile',
bold: true,
onClick: function () {
if ($('.infopopup').length > 0) {
scrolltoTop();
}
else{questions();scrolltoTop();}
}
},
{
text: 'View Profile Photos ('+new_all[myPhotoBrowser.swiper.activeIndex].photocount+')',
bold: true,
onClick: function () {
if ($('.infopopup').length > 0) {
myApp.closeModal() ;backtoProfile();
}
else{}
}
},
{
text: 'View Photo Bombs (0)',
disabled:true,
color: 'green',
onClick: function () {
imagesPopup();
}
},
{
text: 'Block',
onClick: function () {
more();
}
},{
text: 'Report',
disabled:disabledattribute,
onClick: function () {
report();
}
},
{
text: 'Cancel',
color: 'red'
},
];
}
else {
var elementPos = new_all.map(function(x) {return x.id; }).indexOf(targetid);
//var elementPos = new_all.findIndex(x => x.id==targetid);
var disabledattribute;
if (targetreported){disabledattribute=true;}else{disabledattribute=false;}
var buttons = [
{
text: 'View Profile',
bold: true,
onClick: function () {
if($( ".center" ).hasClass( "close-popup" )){
myApp.closeModal('.chatpop');
if ($('.infopopup').length > 0) {
scrolltoTop();
}
else{questions();scrolltoTop();}
}else{viewscroll = true;singleUser(targetid,targetname);}
}
},
{
text: 'View Profile Photos ('+new_all[elementPos].photocount+')',
bold: true,
onClick: function () {
if($( ".center" ).hasClass( "close-popup" )){
myApp.closeModal('.chatpop');
backtoProfile();
}else{viewphotos = true;singleUser(targetid,targetname);}
}
},
{ text: 'View Photo Bombs (0)',
disabled:true,
color: 'green',
onClick: function () {
imagesPopup();
}
},
{
text: 'Block',
onClick: function () {
more();
}
},{
text: 'Report',
disabled:disabledattribute,
onClick: function () {
report();
}
},
{
text: 'Cancel',
color: 'red'
},
];
}
myApp.actions(buttons);
var photobombsheet = firebase.database().ref('photochats/' + first_number + '/'+ second_number);
photobombsheet.once('value', function(snapshot) {
if(snapshot.val()){$(".color-green").removeClass('disabled');
$(".color-green").html('View Photo Bombs ('+snapshot.numChildren()+')');
}
});
}
function triggerCam(){
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
//$('#takePictureField_').trigger('click');
}
|
Update app.js
|
www/js/app.js
|
Update app.js
|
<ide><path>ww/js/app.js
<ide> function dateConfirmationPage(details){
<ide> $( ".messagebararea" ).css("height","44px");
<ide> $( ".messagebar" ).css("height","44px");
<add> $( ".messages-content" ).css("padding-bottom","0px");
<ide>
<ide> $( ".datetoolbar" ).show();
<ide>
|
|
Java
|
apache-2.0
|
92708bf392d14377ea04c0116d0113c9b86e2ce5
| 0 |
openwis-ss/elasticsearch,openwis-ss/elasticsearch,jrslv/elasticsearch,frankscholten/elasticsearch,jhftrifork/elasticsearch,jrslv/elasticsearch,frankscholten/elasticsearch,openwis-ss/elasticsearch,frankscholten/elasticsearch,jhftrifork/elasticsearch,mesos/elasticsearch,jhftrifork/elasticsearch,mwl/elasticsearch,jrslv/elasticsearch,mwl/elasticsearch,jrslv/elasticsearch,pekermert/elasticsearch,jhftrifork/elasticsearch,mesos/elasticsearch,openwis-ss/elasticsearch,pekermert/elasticsearch,pekermert/elasticsearch,mesos/elasticsearch,mwl/elasticsearch,frankscholten/elasticsearch,mwl/elasticsearch,pekermert/elasticsearch,mesos/elasticsearch
|
package org.apache.mesos.elasticsearch.systemtest;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Container;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.mesos.mini.MesosCluster;
import org.apache.mesos.mini.container.AbstractContainer;
import org.apache.mesos.mini.mesos.MesosClusterConfig;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
/**
* Tests cluster state monitoring and reconciliation.
*/
public class ReconcilliationTest {
private static final Logger LOGGER = Logger.getLogger(ReconcilliationTest.class);
public static final int CLUSTER_SIZE = 3;
public static final int TIMEOUT = 60;
public static final String MESOS_LOCAL_IMAGE_NAME = "mesos-local";
private static final ContainerLifecycleManagement containerManger = new ContainerLifecycleManagement();
protected static final MesosClusterConfig config = MesosClusterConfig.builder()
.numberOfSlaves(CLUSTER_SIZE)
.privateRegistryPort(15000) // Currently you have to choose an available port by yourself
.slaveResources(new String[]{"ports(*):[9200-9200,9300-9300]", "ports(*):[9201-9201,9301-9301]", "ports(*):[9202-9202,9302-9302]"})
.build();
@ClassRule
public static final MesosCluster cluster = new MesosCluster(config);
private static String mesosClusterId;
@BeforeClass
public static void beforeScheduler() throws Exception {
LOGGER.debug("Injecting executor");
cluster.injectImage("mesos/elasticsearch-executor");
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> config.dockerClient.listContainersCmd().exec().size() == CLUSTER_SIZE);
List<Container> containers = config.dockerClient.listContainersCmd().exec();
// Find the mesos-local container so we can do docker in docker commands.
mesosClusterId = "";
for (Container container : containers) {
if (container.getImage().contains(MESOS_LOCAL_IMAGE_NAME)) {
mesosClusterId = container.getId();
break;
}
}
LOGGER.debug("Mini-mesos container ID: " + mesosClusterId);
}
@After
public void after() {
containerManger.stopAll();
}
@Test
public void ifSchedulerLostShouldReconcileExecutors() throws IOException {
ElasticsearchSchedulerContainer scheduler = startSchedulerContainer();
assertCorrectNumberOfExecutors();
// Stop and restart container
containerManger.stopContainer(scheduler);
startSchedulerContainer();
assertCorrectNumberOfExecutors();
}
@Test
public void ifExecutorIsLostShouldStartAnother() throws IOException {
startSchedulerContainer();
assertCorrectNumberOfExecutors();
String id = clusterKillOne();
LOGGER.debug("Deleted " + id);
// Should restart an executor, so there should still be three
assertCorrectNumberOfExecutors();
}
private void assertCorrectNumberOfExecutors() throws IOException {
await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> clusterPs().size() == CLUSTER_SIZE);
List<String> result = clusterPs();
LOGGER.debug("Mini-mesos PS command = " + Arrays.toString(result.toArray()));
assertEquals(CLUSTER_SIZE, result.size());
}
private String clusterKillOne() throws IOException {
String executorId = getLastExecutor();
ExecCreateCmdResponse exec = config.dockerClient.execCreateCmd(mesosClusterId).withAttachStdout().withAttachStderr().withCmd("docker", "kill", executorId).exec();
InputStream execCmdStream = config.dockerClient.execStartCmd(exec.getId()).exec();
return IOUtils.toString(execCmdStream, "UTF-8");
}
// Note: we cant use the task response again because the tasks are only added when created.
private List<String> clusterPs() throws IOException {
ExecCreateCmdResponse exec = config.dockerClient.execCreateCmd(mesosClusterId).withAttachStdout().withAttachStderr().withCmd("docker", "ps", "-q").exec();
InputStream execCmdStream = config.dockerClient.execStartCmd(exec.getId()).exec();
String result = IOUtils.toString(execCmdStream, "UTF-8");
return Arrays.asList(result.replaceAll("[^0-9a-zA-Z\n.]", "").split("\n"));
}
private String getLastExecutor() throws IOException {
return clusterPs().get(0);
}
private static ElasticsearchSchedulerContainer startSchedulerContainer() {
ElasticsearchSchedulerContainer scheduler = new ElasticsearchSchedulerContainer(config.dockerClient, cluster.getMesosContainer().getIpAddress());
containerManger.addAndStart(scheduler);
return scheduler;
}
/**
* Simple class to monitor lifecycle of scheduler container.
*/
private static class ContainerLifecycleManagement {
private List<AbstractContainer> containers = new ArrayList<>();
public void addAndStart(AbstractContainer container) {
container.start();
containers.add(container);
}
public void stopContainer(AbstractContainer container) {
container.remove();
containers.remove(container);
}
public void stopAll() {
containers.forEach(AbstractContainer::remove);
containers.clear();
}
}
}
|
system-test/src/systemTest/java/org/apache/mesos/elasticsearch/systemtest/ReconcilliationTest.java
|
package org.apache.mesos.elasticsearch.systemtest;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.model.Container;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.mesos.mini.MesosCluster;
import org.apache.mesos.mini.mesos.MesosClusterConfig;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.jayway.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
/**
* Tests cluster state monitoring and reconcilliation.
*/
public class ReconcilliationTest {
protected static final MesosClusterConfig config = MesosClusterConfig.builder()
.numberOfSlaves(3)
.privateRegistryPort(15000) // Currently you have to choose an available port by yourself
.slaveResources(new String[]{"ports(*):[9200-9200,9300-9300]", "ports(*):[9201-9201,9301-9301]", "ports(*):[9202-9202,9302-9302]"})
.build();
private static final Logger LOGGER = Logger.getLogger(ReconcilliationTest.class);
@ClassRule
public static final MesosCluster cluster = new MesosCluster(config);
private static String mesosClusterId;
@BeforeClass
public static void beforeScheduler() throws Exception {
cluster.injectImage("mesos/elasticsearch-executor");
await().atMost(60, TimeUnit.SECONDS).until(() -> config.dockerClient.listContainersCmd().exec().size() == 3);
List<Container> containers = config.dockerClient.listContainersCmd().exec();
// Find a single executor container
mesosClusterId = "";
for (Container container : containers) {
if (container.getImage().contains("mesos-local")) {
mesosClusterId = container.getId();
break;
}
}
}
@Test
public void ifSchedulerLostShouldReconcileExecutors() throws IOException {
ElasticsearchSchedulerContainer scheduler = startSchedulerContainer();
await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
List<String> result = clusterPs();
assertEquals(3, result.size());
// Stop and restart container
scheduler.remove();
scheduler = startSchedulerContainer();
await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
result = clusterPs();
assertEquals(3, result.size());
scheduler.remove();
}
@Test
public void ifExecutorIsLostShouldStartAnother() throws IOException {
ElasticsearchSchedulerContainer scheduler = startSchedulerContainer();
await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
List<String> result = clusterPs();
assertEquals(3, result.size());
await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
result = clusterPs();
assertEquals(3, result.size());
String another = clusterKillOne();
LOGGER.debug("Deleted " + another);
// Should restart an executor, so there should still be three
await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
result = clusterPs();
assertEquals(3, result.size());
}
private String clusterKillOne() throws IOException {
String executorId = getLastExecutor();
ExecCreateCmdResponse exec = config.dockerClient.execCreateCmd(mesosClusterId).withAttachStdout().withAttachStderr().withCmd("docker", "kill", executorId).exec();
InputStream execCmdStream = config.dockerClient.execStartCmd(exec.getId()).exec();
return IOUtils.toString(execCmdStream, "UTF-8");
}
// Note: we cant use the task response again because the tasks are only added when created.
private List<String> clusterPs() throws IOException {
ExecCreateCmdResponse exec = config.dockerClient.execCreateCmd(mesosClusterId).withAttachStdout().withAttachStderr().withCmd("docker", "ps", "-q").exec();
InputStream execCmdStream = config.dockerClient.execStartCmd(exec.getId()).exec();
String result = IOUtils.toString(execCmdStream, "UTF-8");
return Arrays.asList(result.split("\n"));
}
private String getLastExecutor() throws IOException {
return clusterPs().get(0).replaceAll("[^0-9a-zA-Z.]", "");
}
private static ElasticsearchSchedulerContainer startSchedulerContainer() {
ElasticsearchSchedulerContainer scheduler = new ElasticsearchSchedulerContainer(config.dockerClient, cluster.getMesosContainer().getIpAddress());
scheduler.start();
return scheduler;
}
}
|
Comments and refactoring for reconciliation test.
|
system-test/src/systemTest/java/org/apache/mesos/elasticsearch/systemtest/ReconcilliationTest.java
|
Comments and refactoring for reconciliation test.
|
<ide><path>ystem-test/src/systemTest/java/org/apache/mesos/elasticsearch/systemtest/ReconcilliationTest.java
<ide> import org.apache.commons.io.IOUtils;
<ide> import org.apache.log4j.Logger;
<ide> import org.apache.mesos.mini.MesosCluster;
<add>import org.apache.mesos.mini.container.AbstractContainer;
<ide> import org.apache.mesos.mini.mesos.MesosClusterConfig;
<add>import org.junit.After;
<ide> import org.junit.BeforeClass;
<ide> import org.junit.ClassRule;
<ide> import org.junit.Test;
<ide>
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.concurrent.TimeUnit;
<ide> import static org.junit.Assert.assertEquals;
<ide>
<ide> /**
<del> * Tests cluster state monitoring and reconcilliation.
<add> * Tests cluster state monitoring and reconciliation.
<ide> */
<ide> public class ReconcilliationTest {
<add> private static final Logger LOGGER = Logger.getLogger(ReconcilliationTest.class);
<add> public static final int CLUSTER_SIZE = 3;
<add> public static final int TIMEOUT = 60;
<add> public static final String MESOS_LOCAL_IMAGE_NAME = "mesos-local";
<add>
<add> private static final ContainerLifecycleManagement containerManger = new ContainerLifecycleManagement();
<ide> protected static final MesosClusterConfig config = MesosClusterConfig.builder()
<del> .numberOfSlaves(3)
<add> .numberOfSlaves(CLUSTER_SIZE)
<ide> .privateRegistryPort(15000) // Currently you have to choose an available port by yourself
<ide> .slaveResources(new String[]{"ports(*):[9200-9200,9300-9300]", "ports(*):[9201-9201,9301-9301]", "ports(*):[9202-9202,9302-9302]"})
<ide> .build();
<del>
<del> private static final Logger LOGGER = Logger.getLogger(ReconcilliationTest.class);
<del>
<ide> @ClassRule
<ide> public static final MesosCluster cluster = new MesosCluster(config);
<add>
<ide> private static String mesosClusterId;
<ide>
<ide> @BeforeClass
<ide> public static void beforeScheduler() throws Exception {
<add> LOGGER.debug("Injecting executor");
<ide> cluster.injectImage("mesos/elasticsearch-executor");
<del> await().atMost(60, TimeUnit.SECONDS).until(() -> config.dockerClient.listContainersCmd().exec().size() == 3);
<add> await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> config.dockerClient.listContainersCmd().exec().size() == CLUSTER_SIZE);
<ide> List<Container> containers = config.dockerClient.listContainersCmd().exec();
<ide>
<del> // Find a single executor container
<add> // Find the mesos-local container so we can do docker in docker commands.
<ide> mesosClusterId = "";
<ide> for (Container container : containers) {
<del> if (container.getImage().contains("mesos-local")) {
<add> if (container.getImage().contains(MESOS_LOCAL_IMAGE_NAME)) {
<ide> mesosClusterId = container.getId();
<ide> break;
<ide> }
<ide> }
<add> LOGGER.debug("Mini-mesos container ID: " + mesosClusterId);
<add> }
<add>
<add> @After
<add> public void after() {
<add> containerManger.stopAll();
<ide> }
<ide>
<ide> @Test
<ide> public void ifSchedulerLostShouldReconcileExecutors() throws IOException {
<ide> ElasticsearchSchedulerContainer scheduler = startSchedulerContainer();
<del> await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
<del> List<String> result = clusterPs();
<del> assertEquals(3, result.size());
<add> assertCorrectNumberOfExecutors();
<ide>
<ide> // Stop and restart container
<del> scheduler.remove();
<del> scheduler = startSchedulerContainer();
<del> await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
<del> result = clusterPs();
<del> assertEquals(3, result.size());
<del> scheduler.remove();
<add> containerManger.stopContainer(scheduler);
<add> startSchedulerContainer();
<add> assertCorrectNumberOfExecutors();
<ide> }
<ide>
<ide> @Test
<ide> public void ifExecutorIsLostShouldStartAnother() throws IOException {
<del> ElasticsearchSchedulerContainer scheduler = startSchedulerContainer();
<del> await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
<del> List<String> result = clusterPs();
<del> assertEquals(3, result.size());
<add> startSchedulerContainer();
<add> assertCorrectNumberOfExecutors();
<ide>
<del> await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
<del> result = clusterPs();
<del> assertEquals(3, result.size());
<del>
<del> String another = clusterKillOne();
<del>
<del> LOGGER.debug("Deleted " + another);
<add> String id = clusterKillOne();
<add> LOGGER.debug("Deleted " + id);
<ide>
<ide> // Should restart an executor, so there should still be three
<del> await().atMost(60, TimeUnit.SECONDS).until(() -> clusterPs().size() == 3);
<del> result = clusterPs();
<del> assertEquals(3, result.size());
<add> assertCorrectNumberOfExecutors();
<add>
<add> }
<add>
<add> private void assertCorrectNumberOfExecutors() throws IOException {
<add> await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> clusterPs().size() == CLUSTER_SIZE);
<add> List<String> result = clusterPs();
<add> LOGGER.debug("Mini-mesos PS command = " + Arrays.toString(result.toArray()));
<add> assertEquals(CLUSTER_SIZE, result.size());
<ide> }
<ide>
<ide> private String clusterKillOne() throws IOException {
<ide> ExecCreateCmdResponse exec = config.dockerClient.execCreateCmd(mesosClusterId).withAttachStdout().withAttachStderr().withCmd("docker", "ps", "-q").exec();
<ide> InputStream execCmdStream = config.dockerClient.execStartCmd(exec.getId()).exec();
<ide> String result = IOUtils.toString(execCmdStream, "UTF-8");
<del> return Arrays.asList(result.split("\n"));
<add> return Arrays.asList(result.replaceAll("[^0-9a-zA-Z\n.]", "").split("\n"));
<ide> }
<ide>
<ide> private String getLastExecutor() throws IOException {
<del> return clusterPs().get(0).replaceAll("[^0-9a-zA-Z.]", "");
<add> return clusterPs().get(0);
<ide> }
<ide>
<ide> private static ElasticsearchSchedulerContainer startSchedulerContainer() {
<ide> ElasticsearchSchedulerContainer scheduler = new ElasticsearchSchedulerContainer(config.dockerClient, cluster.getMesosContainer().getIpAddress());
<del> scheduler.start();
<add> containerManger.addAndStart(scheduler);
<ide> return scheduler;
<ide> }
<ide>
<add> /**
<add> * Simple class to monitor lifecycle of scheduler container.
<add> */
<add> private static class ContainerLifecycleManagement {
<add> private List<AbstractContainer> containers = new ArrayList<>();
<add> public void addAndStart(AbstractContainer container) {
<add> container.start();
<add> containers.add(container);
<add> }
<add>
<add> public void stopContainer(AbstractContainer container) {
<add> container.remove();
<add> containers.remove(container);
<add> }
<add>
<add> public void stopAll() {
<add> containers.forEach(AbstractContainer::remove);
<add> containers.clear();
<add> }
<add> }
<add>
<ide> }
|
|
Java
|
apache-2.0
|
388f319e2f8e39bb6e360c3455b0a9426a54f960
| 0 |
cn-cerc/summer-mis,cn-cerc/summer-mis
|
summer-mis/src/main/java/cn/cerc/mis/mail/Component.java
|
package cn.cerc.mis.mail;
@Deprecated
public class Component extends HtmlComponent {
}
|
Delete Component.java
|
summer-mis/src/main/java/cn/cerc/mis/mail/Component.java
|
Delete Component.java
|
<ide><path>ummer-mis/src/main/java/cn/cerc/mis/mail/Component.java
<del>package cn.cerc.mis.mail;
<del>
<del>@Deprecated
<del>public class Component extends HtmlComponent {
<del>
<del>}
|
||
Java
|
mit
|
6afa0cba80b4db9a1e1ee4549e5c61c9f3180309
| 0 |
kingargyle/serenity-android,kingargyle/serenity-android,NineWorlds/serenity-android,NineWorlds/serenity-android,kingargyle/serenity-android,NineWorlds/serenity-android
|
/**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* 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 us.nineworlds.serenity.ui.video.player;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Collection;
import us.nineworlds.plex.rest.PlexappFactory;
import us.nineworlds.serenity.SerenityApplication;
import us.nineworlds.serenity.core.services.CompletedVideoRequest;
import us.nineworlds.serenity.core.subtitles.formats.Caption;
import us.nineworlds.serenity.core.subtitles.formats.FormatASS;
import us.nineworlds.serenity.core.subtitles.formats.FormatSRT;
import us.nineworlds.serenity.core.subtitles.formats.TimedTextObject;
import us.nineworlds.serenity.ui.activity.SerenityActivity;
import us.nineworlds.serenity.R;
import com.google.analytics.tracking.android.EasyTracker;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
/**
* A view that handles the internal video playback and representation of a movie
* or tv show.
*
* @author dcarver
*
*/
public class SerenitySurfaceViewVideoActivity extends SerenityActivity
implements SurfaceHolder.Callback {
/**
*
*/
static final int PROGRESS_UPDATE_DELAY = 5000;
static final int SUBTITLE_DISPLAY_CHECK = 100;
static final String TAG = "SerenitySurfaceViewVideoActivity";
static final int CONTROLLER_DELAY = 16000; // Sixteen seconds
private MediaPlayer mediaPlayer;
private String videoURL;
private SurfaceView surfaceView;
private MediaController mediaController;
private String aspectRatio;
private String videoId;
private int resumeOffset;
private boolean mediaplayer_error_state = false;
private boolean mediaplayer_released = false;
private String subtitleURL;
private String subtitleType;
private String mediaTagIdentifier;
private TimedTextObject subtitleTimedText;
private boolean subtitlesPlaybackEnabled = true;
private Handler subtitleDisplayHandler = new Handler();
private Runnable subtitle = new Runnable() {
@Override
public void run() {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
if (hasSubtitles()) {
int currentPos = mediaPlayer.getCurrentPosition();
Collection<Caption> subtitles = subtitleTimedText.captions
.values();
for (Caption caption : subtitles) {
if (currentPos >= caption.start.getMilliseconds()
&& currentPos <= caption.end.getMilliseconds()) {
onTimedText(caption);
break;
} else if (currentPos > caption.end.getMilliseconds()) {
onTimedText(null);
}
}
} else {
subtitlesPlaybackEnabled = false;
Toast.makeText(getApplicationContext(), "Invalid or Missing Subtitle. Subtitle playback disabled.", Toast.LENGTH_LONG).show();
}
}
if (subtitlesPlaybackEnabled) {
subtitleDisplayHandler.postDelayed(this, SUBTITLE_DISPLAY_CHECK);
}
}
/**
* @return
*/
protected boolean hasSubtitles() {
return subtitleTimedText != null
&& subtitleTimedText.captions != null;
};
};
private Handler progressReportinghandler = new Handler();
private Runnable progressRunnable = new Runnable() {
@Override
public void run() {
try {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
new UpdateProgressRequest().execute();
progressReportinghandler.postDelayed(this,
PROGRESS_UPDATE_DELAY); // Update progress every 5
// seconds
}
} catch (IllegalStateException ex) {
Log.w(getClass().getName(),
"Illegalstate exception occurred durring progress update. No further updates will occur.",
ex);
}
};
};
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource(videoURL);
mediaPlayer.setOnPreparedListener(new VideoPlayerPrepareListener(
this, mediaPlayer, mediaController, surfaceView,
resumeOffset, videoId, aspectRatio,
progressReportinghandler, progressRunnable, subtitleURL));
mediaPlayer
.setOnCompletionListener(new VideoPlayerOnCompletionListener());
mediaPlayer.prepareAsync();
} catch (Exception ex) {
Log.e(TAG, "Video Playback Error. ", ex);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (!mediaplayer_released) {
mediaPlayer.release();
mediaplayer_released = true;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_playback);
init();
}
/**
* Initialize the mediaplayer and mediacontroller.
*/
protected void init() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new SerenityOnErrorListener());
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.setKeepScreenOn(true);
SurfaceHolder holder = surfaceView.getHolder();
holder.addCallback(this);
holder.setSizeFromLayout();
retrieveIntentExtras();
}
protected void retrieveIntentExtras() {
Bundle extras = getIntent().getExtras();
videoURL = extras.getString("videoUrl");
if (videoURL == null) {
videoURL = extras.getString("encodedvideoUrl");
if (videoURL != null) {
videoURL = URLDecoder.decode(videoURL);
}
}
videoId = extras.getString("id");
String summary = extras.getString("summary");
String title = extras.getString("title");
String posterURL = extras.getString("posterUrl");
aspectRatio = extras.getString("aspectRatio");
String videoFormat = extras.getString("videoFormat");
String videoResolution = extras.getString("videoResolution");
String audioFormat = extras.getString("audioFormat");
String audioChannels = extras.getString("audioChannels");
resumeOffset = extras.getInt("resumeOffset");
subtitleURL = extras.getString("subtitleURL");
subtitleType = extras.getString("subtitleFormat");
mediaTagIdentifier = extras.getString("mediaTagId");
new SubtitleAsyncTask().execute();
initMediaController(summary, title, posterURL, videoFormat,
videoResolution, audioFormat, audioChannels);
}
/**
* @param summary
* @param title
* @param posterURL
* @param videoFormat
* @param videoResolution
* @param audioFormat
* @param audioChannels
*/
protected void initMediaController(String summary, String title,
String posterURL, String videoFormat, String videoResolution,
String audioFormat, String audioChannels) {
mediaController = new MediaController(this, summary, title, posterURL,
videoResolution, videoFormat, audioFormat, audioChannels,
mediaTagIdentifier);
mediaController.setAnchorView(surfaceView);
mediaController.setMediaPlayer(new SerenityMediaPlayerControl(
mediaPlayer));
}
@Override
public void finish() {
super.finish();
subtitleDisplayHandler.removeCallbacks(subtitle);
progressReportinghandler.removeCallbacks(progressRunnable);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mediaController.isShowing()) {
if (isKeyCodeBack(keyCode)) {
mediaController.hide();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
return super.onKeyDown(keyCode, event);
}
} else {
if (isKeyCodeBack(keyCode)) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
return super.onKeyDown(keyCode, event);
}
}
if (isKeyCodeInfo(keyCode)) {
if (isMediaPlayerStateValid()) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isKeyCodePauseResume(keyCode)) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mediaController.show(CONTROLLER_DELAY);
progressReportinghandler.removeCallbacks(progressRunnable);
} else {
mediaPlayer.start();
mediaController.hide();
progressReportinghandler.postDelayed(progressRunnable, 5000);
}
return true;
}
if (isKeyCodeSkipForward(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = 10000 + mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (skipOffset > duration) {
skipOffset = duration - 1;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeSkipBack(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = mediaPlayer.getCurrentPosition() - 10000;
if (skipOffset < 0) {
skipOffset = 0;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeStop(keyCode) && isMediaPlayerStateValid()) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isMediaPlayerStateValid()) {
if (keyCode == KeyEvent.KEYCODE_1) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.10f);
mediaPlayer.seekTo(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_2) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.20f);
mediaPlayer.seekTo(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_3) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.30f);
mediaPlayer.seekTo(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_4) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.40f);
mediaPlayer.seekTo(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_5) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.50f);
mediaPlayer.seekTo(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_6) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.60f);
mediaPlayer.seekTo(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_8) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.80f);
mediaPlayer.seekTo(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_9) {
int duration = mediaPlayer.getDuration();
int newPos = Math.round(duration * 0.90f);
mediaPlayer.seekTo(newPos);
return true;
}
if (keyCode == KeyEvent.KEYCODE_0) {
mediaPlayer.seekTo(0);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
/**
* @param keyCode
* @return
*/
protected boolean isKeyCodeStop(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_STOP
|| keyCode == KeyEvent.KEYCODE_S;
}
/**
* @param keyCode
* @return
*/
@Override
protected boolean isKeyCodeSkipBack(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_REWIND
|| keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS
|| keyCode == KeyEvent.KEYCODE_R;
}
/**
* @param keyCode
* @return
*/
@Override
protected boolean isKeyCodeSkipForward(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD
|| keyCode == KeyEvent.KEYCODE_MEDIA_NEXT
|| keyCode == KeyEvent.KEYCODE_F;
}
/**
* @param keyCode
* @return
*/
protected boolean isKeyCodePauseResume(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY
|| keyCode == KeyEvent.KEYCODE_P
|| keyCode == KeyEvent.KEYCODE_SPACE;
}
protected boolean isKeyCodeInfo(int keyCode) {
return keyCode == KeyEvent.KEYCODE_INFO
|| keyCode == KeyEvent.KEYCODE_I;
}
protected boolean isKeyCodeBack(int keyCode) {
return keyCode == KeyEvent.KEYCODE_BACK
|| keyCode == KeyEvent.KEYCODE_ESCAPE;
}
protected boolean isMediaPlayerStateValid() {
if (mediaPlayer != null && mediaplayer_error_state == false
&& mediaplayer_released == false) {
return true;
}
return false;
}
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
/**
* A task that updates the progress position of a video while it is being
* played.
*
* @author dcarver
*
*/
protected class UpdateProgressRequest extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
PlexappFactory factory = SerenityApplication.getPlexFactory();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
String offset = Integer.valueOf(
mediaPlayer.getCurrentPosition()).toString();
factory.setProgress(videoId, offset);
}
return null;
}
}
/* (non-Javadoc)
* @see us.nineworlds.serenity.ui.activity.SerenityActivity#createSideMenu()
*/
@Override
protected void createSideMenu() {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show();
}
return true;
}
return super.onTouchEvent(event);
}
protected class VideoPlayerOnCompletionListener implements
OnCompletionListener {
@Override
public void onCompletion(MediaPlayer mp) {
new CompletedVideoRequest(videoId).execute();
if (!mediaplayer_released) {
if (isMediaPlayerStateValid()) {
if (mediaController.isShowing()) {
mediaController.hide();
}
}
mp.release();
mediaplayer_released = true;
}
finish();
}
}
/*
* (non-Javadoc)
*
* @see
* android.media.MediaPlayer.OnTimedTextListener#onTimedText(android.media
* .MediaPlayer, android.media.TimedText)
*/
public void onTimedText(Caption text) {
TextView subtitles = (TextView) findViewById(R.id.txtSubtitles);
if (text == null) {
subtitles.setVisibility(View.INVISIBLE);
return;
}
subtitles.setText(Html.fromHtml(text.content));
subtitles.setVisibility(View.VISIBLE);
}
public class SubtitleAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
if (subtitleURL != null) {
try {
URL url = new URL(subtitleURL);
InputStream stream = url.openStream();
if ("srt".equals(subtitleType)) {
FormatSRT formatSRT = new FormatSRT();
subtitleTimedText = formatSRT.parseFile(stream);
} else if ("ass".equals(subtitleType)) {
FormatASS formatASS = new FormatASS();
subtitleTimedText = formatASS.parseFile(stream);
}
subtitleDisplayHandler.post(subtitle);
} catch (Exception e) {
Log.e(getClass().getName(), e.getMessage(), e);
}
}
return null;
}
}
}
|
serenity-app/src/main/java/us/nineworlds/serenity/ui/video/player/SerenitySurfaceViewVideoActivity.java
|
/**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* 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 us.nineworlds.serenity.ui.video.player;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Collection;
import us.nineworlds.plex.rest.PlexappFactory;
import us.nineworlds.serenity.SerenityApplication;
import us.nineworlds.serenity.core.services.CompletedVideoRequest;
import us.nineworlds.serenity.core.subtitles.formats.Caption;
import us.nineworlds.serenity.core.subtitles.formats.FormatASS;
import us.nineworlds.serenity.core.subtitles.formats.FormatSRT;
import us.nineworlds.serenity.core.subtitles.formats.TimedTextObject;
import us.nineworlds.serenity.ui.activity.SerenityActivity;
import us.nineworlds.serenity.R;
import com.google.analytics.tracking.android.EasyTracker;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
/**
* A view that handles the internal video playback and representation of a movie
* or tv show.
*
* @author dcarver
*
*/
public class SerenitySurfaceViewVideoActivity extends SerenityActivity
implements SurfaceHolder.Callback {
/**
*
*/
static final int PROGRESS_UPDATE_DELAY = 5000;
static final int SUBTITLE_DISPLAY_CHECK = 100;
static final String TAG = "SerenitySurfaceViewVideoActivity";
static final int CONTROLLER_DELAY = 16000; // Sixteen seconds
private MediaPlayer mediaPlayer;
private String videoURL;
private SurfaceView surfaceView;
private MediaController mediaController;
private String aspectRatio;
private String videoId;
private int resumeOffset;
private boolean mediaplayer_error_state = false;
private boolean mediaplayer_released = false;
private String subtitleURL;
private String subtitleType;
private String mediaTagIdentifier;
private TimedTextObject subtitleTimedText;
private boolean subtitlesPlaybackEnabled = true;
private Handler subtitleDisplayHandler = new Handler();
private Runnable subtitle = new Runnable() {
@Override
public void run() {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
if (hasSubtitles()) {
int currentPos = mediaPlayer.getCurrentPosition();
Collection<Caption> subtitles = subtitleTimedText.captions
.values();
for (Caption caption : subtitles) {
if (currentPos >= caption.start.getMilliseconds()
&& currentPos <= caption.end.getMilliseconds()) {
onTimedText(caption);
break;
} else if (currentPos > caption.end.getMilliseconds()) {
onTimedText(null);
}
}
} else {
subtitlesPlaybackEnabled = false;
Toast.makeText(getApplicationContext(), "Invalid or Missing Subtitle. Subtitle playback disabled.", Toast.LENGTH_LONG).show();
}
}
if (subtitlesPlaybackEnabled) {
subtitleDisplayHandler.postDelayed(this, SUBTITLE_DISPLAY_CHECK);
}
}
/**
* @return
*/
protected boolean hasSubtitles() {
return subtitleTimedText != null
&& subtitleTimedText.captions != null;
};
};
private Handler progressReportinghandler = new Handler();
private Runnable progressRunnable = new Runnable() {
@Override
public void run() {
try {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
new UpdateProgressRequest().execute();
progressReportinghandler.postDelayed(this,
PROGRESS_UPDATE_DELAY); // Update progress every 5
// seconds
}
} catch (IllegalStateException ex) {
Log.w(getClass().getName(),
"Illegalstate exception occurred durring progress update. No further updates will occur.",
ex);
}
};
};
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource(videoURL);
mediaPlayer.setOnPreparedListener(new VideoPlayerPrepareListener(
this, mediaPlayer, mediaController, surfaceView,
resumeOffset, videoId, aspectRatio,
progressReportinghandler, progressRunnable, subtitleURL));
mediaPlayer
.setOnCompletionListener(new VideoPlayerOnCompletionListener());
mediaPlayer.prepareAsync();
} catch (Exception ex) {
Log.e(TAG, "Video Playback Error. ", ex);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (!mediaplayer_released) {
mediaPlayer.release();
mediaplayer_released = true;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_playback);
init();
}
/**
* Initialize the mediaplayer and mediacontroller.
*/
protected void init() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new SerenityOnErrorListener());
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.setKeepScreenOn(true);
SurfaceHolder holder = surfaceView.getHolder();
holder.addCallback(this);
holder.setSizeFromLayout();
retrieveIntentExtras();
}
protected void retrieveIntentExtras() {
Bundle extras = getIntent().getExtras();
videoURL = extras.getString("videoUrl");
if (videoURL == null) {
videoURL = extras.getString("encodedvideoUrl");
if (videoURL != null) {
videoURL = URLDecoder.decode(videoURL);
}
}
videoId = extras.getString("id");
String summary = extras.getString("summary");
String title = extras.getString("title");
String posterURL = extras.getString("posterUrl");
aspectRatio = extras.getString("aspectRatio");
String videoFormat = extras.getString("videoFormat");
String videoResolution = extras.getString("videoResolution");
String audioFormat = extras.getString("audioFormat");
String audioChannels = extras.getString("audioChannels");
resumeOffset = extras.getInt("resumeOffset");
subtitleURL = extras.getString("subtitleURL");
subtitleType = extras.getString("subtitleFormat");
mediaTagIdentifier = extras.getString("mediaTagId");
new SubtitleAsyncTask().execute();
initMediaController(summary, title, posterURL, videoFormat,
videoResolution, audioFormat, audioChannels);
}
/**
* @param summary
* @param title
* @param posterURL
* @param videoFormat
* @param videoResolution
* @param audioFormat
* @param audioChannels
*/
protected void initMediaController(String summary, String title,
String posterURL, String videoFormat, String videoResolution,
String audioFormat, String audioChannels) {
mediaController = new MediaController(this, summary, title, posterURL,
videoResolution, videoFormat, audioFormat, audioChannels,
mediaTagIdentifier);
mediaController.setAnchorView(surfaceView);
mediaController.setMediaPlayer(new SerenityMediaPlayerControl(
mediaPlayer));
}
@Override
public void finish() {
super.finish();
subtitleDisplayHandler.removeCallbacks(subtitle);
progressReportinghandler.removeCallbacks(progressRunnable);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mediaController.isShowing()) {
if (isKeyCodeBack(keyCode)) {
mediaController.hide();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
return super.onKeyDown(keyCode, event);
}
} else {
if (isKeyCodeBack(keyCode)) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
return super.onKeyDown(keyCode, event);
}
}
if (isKeyCodeInfo(keyCode)) {
if (isMediaPlayerStateValid()) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
if (isKeyCodePauseResume(keyCode)) {
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mediaController.show(CONTROLLER_DELAY);
progressReportinghandler.removeCallbacks(progressRunnable);
} else {
mediaPlayer.start();
mediaController.hide();
progressReportinghandler.postDelayed(progressRunnable, 5000);
}
return true;
}
if (isKeyCodeSkipForward(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = 10000 + mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (skipOffset > duration) {
skipOffset = duration - 1;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeSkipBack(keyCode) && isMediaPlayerStateValid()) {
int skipOffset = mediaPlayer.getCurrentPosition() - 10000;
if (skipOffset < 0) {
skipOffset = 0;
}
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
mediaPlayer.seekTo(skipOffset);
return true;
}
if (isKeyCodeStop(keyCode) && isMediaPlayerStateValid()) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (!mediaController.isShowing()) {
mediaController.show(CONTROLLER_DELAY);
}
}
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* @param keyCode
* @return
*/
protected boolean isKeyCodeStop(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_STOP
|| keyCode == KeyEvent.KEYCODE_S;
}
/**
* @param keyCode
* @return
*/
@Override
protected boolean isKeyCodeSkipBack(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_REWIND
|| keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS
|| keyCode == KeyEvent.KEYCODE_R;
}
/**
* @param keyCode
* @return
*/
@Override
protected boolean isKeyCodeSkipForward(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD
|| keyCode == KeyEvent.KEYCODE_MEDIA_NEXT
|| keyCode == KeyEvent.KEYCODE_F;
}
/**
* @param keyCode
* @return
*/
protected boolean isKeyCodePauseResume(int keyCode) {
return keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY
|| keyCode == KeyEvent.KEYCODE_P
|| keyCode == KeyEvent.KEYCODE_SPACE;
}
protected boolean isKeyCodeInfo(int keyCode) {
return keyCode == KeyEvent.KEYCODE_INFO
|| keyCode == KeyEvent.KEYCODE_I;
}
protected boolean isKeyCodeBack(int keyCode) {
return keyCode == KeyEvent.KEYCODE_BACK
|| keyCode == KeyEvent.KEYCODE_ESCAPE;
}
protected boolean isMediaPlayerStateValid() {
if (mediaPlayer != null && mediaplayer_error_state == false
&& mediaplayer_released == false) {
return true;
}
return false;
}
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
/**
* A task that updates the progress position of a video while it is being
* played.
*
* @author dcarver
*
*/
protected class UpdateProgressRequest extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
PlexappFactory factory = SerenityApplication.getPlexFactory();
if (isMediaPlayerStateValid() && mediaPlayer.isPlaying()) {
String offset = Integer.valueOf(
mediaPlayer.getCurrentPosition()).toString();
factory.setProgress(videoId, offset);
}
return null;
}
}
/* (non-Javadoc)
* @see us.nineworlds.serenity.ui.activity.SerenityActivity#createSideMenu()
*/
@Override
protected void createSideMenu() {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mediaController.isShowing()) {
mediaController.hide();
} else {
mediaController.show();
}
return true;
}
return super.onTouchEvent(event);
}
protected class VideoPlayerOnCompletionListener implements
OnCompletionListener {
@Override
public void onCompletion(MediaPlayer mp) {
new CompletedVideoRequest(videoId).execute();
if (!mediaplayer_released) {
if (isMediaPlayerStateValid()) {
if (mediaController.isShowing()) {
mediaController.hide();
}
}
mp.release();
mediaplayer_released = true;
}
finish();
}
}
/*
* (non-Javadoc)
*
* @see
* android.media.MediaPlayer.OnTimedTextListener#onTimedText(android.media
* .MediaPlayer, android.media.TimedText)
*/
public void onTimedText(Caption text) {
TextView subtitles = (TextView) findViewById(R.id.txtSubtitles);
if (text == null) {
subtitles.setVisibility(View.INVISIBLE);
return;
}
subtitles.setText(Html.fromHtml(text.content));
subtitles.setVisibility(View.VISIBLE);
}
public class SubtitleAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
if (subtitleURL != null) {
try {
URL url = new URL(subtitleURL);
InputStream stream = url.openStream();
if ("srt".equals(subtitleType)) {
FormatSRT formatSRT = new FormatSRT();
subtitleTimedText = formatSRT.parseFile(stream);
} else if ("ass".equals(subtitleType)) {
FormatASS formatASS = new FormatASS();
subtitleTimedText = formatASS.parseFile(stream);
}
subtitleDisplayHandler.post(subtitle);
} catch (Exception e) {
Log.e(getClass().getName(), e.getMessage(), e);
}
}
return null;
}
}
}
|
Seek video by percentage.
Using numeric keys, navigate the video by a percentage of the duration.
Allows for quick jumping by percentage 1 = 10 percent, 2, = 20 percent.
|
serenity-app/src/main/java/us/nineworlds/serenity/ui/video/player/SerenitySurfaceViewVideoActivity.java
|
Seek video by percentage.
|
<ide><path>erenity-app/src/main/java/us/nineworlds/serenity/ui/video/player/SerenitySurfaceViewVideoActivity.java
<ide> }
<ide> return true;
<ide> }
<add>
<add> if (isMediaPlayerStateValid()) {
<add> if (keyCode == KeyEvent.KEYCODE_1) {
<add> int duration = mediaPlayer.getDuration();
<add> int newPos = Math.round(duration * 0.10f);
<add> mediaPlayer.seekTo(newPos);
<add> return true;
<add> }
<add> if (keyCode == KeyEvent.KEYCODE_2) {
<add> int duration = mediaPlayer.getDuration();
<add> int newPos = Math.round(duration * 0.20f);
<add> mediaPlayer.seekTo(newPos);
<add> return true;
<add> }
<add> if (keyCode == KeyEvent.KEYCODE_3) {
<add> int duration = mediaPlayer.getDuration();
<add> int newPos = Math.round(duration * 0.30f);
<add> mediaPlayer.seekTo(newPos);
<add> return true;
<add> }
<add> if (keyCode == KeyEvent.KEYCODE_4) {
<add> int duration = mediaPlayer.getDuration();
<add> int newPos = Math.round(duration * 0.40f);
<add> mediaPlayer.seekTo(newPos);
<add> return true;
<add> }
<add> if (keyCode == KeyEvent.KEYCODE_5) {
<add> int duration = mediaPlayer.getDuration();
<add> int newPos = Math.round(duration * 0.50f);
<add> mediaPlayer.seekTo(newPos);
<add> return true;
<add> }
<add> if (keyCode == KeyEvent.KEYCODE_6) {
<add> int duration = mediaPlayer.getDuration();
<add> int newPos = Math.round(duration * 0.60f);
<add> mediaPlayer.seekTo(newPos);
<add> return true;
<add> }
<add> if (keyCode == KeyEvent.KEYCODE_8) {
<add> int duration = mediaPlayer.getDuration();
<add> int newPos = Math.round(duration * 0.80f);
<add> mediaPlayer.seekTo(newPos);
<add> return true;
<add> }
<add> if (keyCode == KeyEvent.KEYCODE_9) {
<add> int duration = mediaPlayer.getDuration();
<add> int newPos = Math.round(duration * 0.90f);
<add> mediaPlayer.seekTo(newPos);
<add> return true;
<add> }
<add> if (keyCode == KeyEvent.KEYCODE_0) {
<add> mediaPlayer.seekTo(0);
<add> return true;
<add> }
<add> }
<ide>
<ide> return super.onKeyDown(keyCode, event);
<ide> }
|
|
Java
|
mit
|
1a21f5390b568e6c822e744ab93e5d57c6f7eafd
| 0 |
1fish2/the-blue-alliance-android,the-blue-alliance/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,nwalters512/the-blue-alliance-android,the-blue-alliance/the-blue-alliance-android,1fish2/the-blue-alliance-android,nwalters512/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,nwalters512/the-blue-alliance-android,the-blue-alliance/the-blue-alliance-android,1fish2/the-blue-alliance-android
|
package com.thebluealliance.androidclient.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.thebluealliance.androidclient.BuildConfig;
import com.thebluealliance.androidclient.Constants;
import com.thebluealliance.androidclient.NfcUris;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.Utilities;
import com.thebluealliance.androidclient.background.RecreateSearchIndexes;
import com.thebluealliance.androidclient.background.firstlaunch.LoadTBAData;
import com.thebluealliance.androidclient.database.Database;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LaunchActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Database.getInstance(this);
// Create intent to launch data download activity
Intent redownloadIntent = new Intent(this, RedownloadActivity.class);
boolean redownload = checkDataRedownload(redownloadIntent);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.ALL_DATA_LOADED_KEY, false) && !redownload) {
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage message = (NdefMessage) rawMsgs[0];
String uri = new String(message.getRecords()[0].getPayload());
Log.d(Constants.LOG_TAG, "NFC URI: " + uri);
processNfcUri(uri);
return;
} else if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
Uri data = getIntent().getData();
Log.d(Constants.LOG_TAG, "VIEW URI: " + data.toString());
if (data != null) {
//we caught an Action.VIEW intent, so
//now we generate the proper intent to view
//the requested content
Intent intent = Utilities.getIntentForTBAUrl(this, data);
if (intent != null) {
startActivity(intent);
finish();
return;
} else {
goToHome();
return;
}
} else {
goToHome();
return;
}
} else {
goToHome();
return;
}
} else if (redownload) {
// Start redownload activity
startActivity(redownloadIntent);
} else {
// Go to onboarding activity
startActivity(new Intent(this, OnboardingActivity.class));
finish();
}
}
private boolean checkDataRedownload(Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastVersion = prefs.getInt(Constants.APP_VERSION_KEY, -1);
if (lastVersion == -1 && !prefs.getBoolean(Constants.ALL_DATA_LOADED_KEY, false)) {
// on a clean install, don't think we're updating
return false;
}
boolean redownload = false;
Log.d(Constants.LOG_TAG, "Last version: " + lastVersion + "/" + BuildConfig.VERSION_CODE + " " + prefs.contains(Constants.APP_VERSION_KEY));
if (prefs.contains(Constants.APP_VERSION_KEY) && lastVersion < BuildConfig.VERSION_CODE) {
// We are updating the app. Do stuffs, if necessary.
// TODO: make sure to modify changelog.txt with any recent changes
if (lastVersion < 14) {
// addition of districts. Download the required data
redownload = true;
intent.putExtra(LoadTBAData.DATA_TO_LOAD, new short[]{LoadTBAData.LOAD_EVENTS, LoadTBAData.LOAD_DISTRICTS});
}
if (lastVersion < 16) {
// addition of myTBA - Prompt the user for an account
redownload = true;
intent.putExtra(LoadTBAData.DATA_TO_LOAD, new short[]{LoadTBAData.LOAD_EVENTS});
}
if (lastVersion < 21) {
// redownload to get event short names
redownload = true;
intent.putExtra(LoadTBAData.DATA_TO_LOAD, new short[]{LoadTBAData.LOAD_EVENTS});
}
if (lastVersion < 46) {
// recreate search indexes to contain foreign keys
redownload = false;
RecreateSearchIndexes.startActionRecreateSearchIndexes(this);
}
if (lastVersion < 3000000) {
// v3.0 - Reload everything to warm okhttp caches
redownload = true;
intent.putExtra(LoadTBAData.DATA_TO_LOAD, new short[]{LoadTBAData.LOAD_EVENTS, LoadTBAData.LOAD_TEAMS, LoadTBAData.LOAD_DISTRICTS});
}
}
// If we don't have to redownload, store the version code here. Otherwise, let the
// RedownloadActivity store the version code upcn completion
if (!redownload) {
prefs.edit().putInt(Constants.APP_VERSION_KEY, BuildConfig.VERSION_CODE).apply();
}
return redownload;
}
private void goToHome() {
startActivity(new Intent(this, HomeActivity.class));
finish();
}
private void processNfcUri(String uri) {
Pattern regexPattern = Pattern.compile(NfcUris.URI_EVENT_MATCHER);
Matcher m = regexPattern.matcher(uri);
if (m.matches()) {
String eventKey = m.group(1);
TaskStackBuilder.create(this).addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_events))
.addNextIntent(ViewEventActivity.newInstance(this, eventKey)).startActivities();
finish();
return;
}
regexPattern = Pattern.compile(NfcUris.URI_TEAM_MATCHER);
m = regexPattern.matcher(uri);
if (m.matches()) {
String teamKey = m.group(1);
TaskStackBuilder.create(this).addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_teams))
.addNextIntent(ViewTeamActivity.newInstance(this, teamKey)).startActivities();
finish();
return;
}
regexPattern = Pattern.compile(NfcUris.URI_TEAM_AT_EVENT_MATCHER);
m = regexPattern.matcher(uri);
if (m.matches()) {
String eventKey = m.group(1);
String teamKey = m.group(2);
TaskStackBuilder.create(this).addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_events))
.addNextIntent(ViewEventActivity.newInstance(this, eventKey))
.addNextIntent(TeamAtEventActivity.newInstance(this, eventKey, teamKey)).startActivities();
finish();
return;
}
regexPattern = Pattern.compile(NfcUris.URI_TEAM_IN_YEAR_MATCHER);
m = regexPattern.matcher(uri);
if (m.matches()) {
String teamKey = m.group(1);
String teamYear = m.group(2);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_events))
.addNextIntent(ViewTeamActivity.newInstance(this, teamKey, Integer.valueOf(teamYear))).startActivities();
finish();
return;
}
regexPattern = Pattern.compile(NfcUris.URI_MATCH_MATCHER);
m = regexPattern.matcher(uri);
if (m.matches()) {
String matchKey = m.group(1);
String eventKey = matchKey.substring(0, matchKey.indexOf("_"));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_events))
.addNextIntent(ViewEventActivity.newInstance(this, eventKey))
.addNextIntent(ViewMatchActivity.newInstance(this, matchKey)).startActivities();
finish();
return;
}
// Default to kicking the user to the events list if none of the URIs match
goToHome();
}
}
|
android/src/main/java/com/thebluealliance/androidclient/activities/LaunchActivity.java
|
package com.thebluealliance.androidclient.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.thebluealliance.androidclient.BuildConfig;
import com.thebluealliance.androidclient.Constants;
import com.thebluealliance.androidclient.NfcUris;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.Utilities;
import com.thebluealliance.androidclient.background.RecreateSearchIndexes;
import com.thebluealliance.androidclient.background.firstlaunch.LoadTBAData;
import com.thebluealliance.androidclient.database.Database;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LaunchActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Database.getInstance(this);
// Create intent to launch data download activity
Intent redownloadIntent = new Intent(this, RedownloadActivity.class);
boolean redownload = checkDataRedownload(redownloadIntent);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.ALL_DATA_LOADED_KEY, false) && !redownload) {
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage message = (NdefMessage) rawMsgs[0];
String uri = new String(message.getRecords()[0].getPayload());
Log.d(Constants.LOG_TAG, "NFC URI: " + uri);
processNfcUri(uri);
return;
} else if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
Uri data = getIntent().getData();
Log.d(Constants.LOG_TAG, "VIEW URI: " + data.toString());
if (data != null) {
//we caught an Action.VIEW intent, so
//now we generate the proper intent to view
//the requested content
Intent intent = Utilities.getIntentForTBAUrl(this, data);
if (intent != null) {
startActivity(intent);
finish();
return;
} else {
goToHome();
return;
}
} else {
goToHome();
return;
}
} else {
goToHome();
return;
}
} else if (redownload) {
// Start redownload activity
startActivity(redownloadIntent);
} else {
// Go to onboarding activity
startActivity(new Intent(this, OnboardingActivity.class));
finish();
}
}
private boolean checkDataRedownload(Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastVersion = prefs.getInt(Constants.APP_VERSION_KEY, -1);
if (lastVersion == -1 && !prefs.getBoolean(Constants.ALL_DATA_LOADED_KEY, false)) {
// on a clean install, don't think we're updating
return false;
}
boolean redownload = false;
Log.d(Constants.LOG_TAG, "Last version: " + lastVersion + "/" + BuildConfig.VERSION_CODE + " " + prefs.contains(Constants.APP_VERSION_KEY));
if (prefs.contains(Constants.APP_VERSION_KEY) && lastVersion < BuildConfig.VERSION_CODE) {
// We are updating the app. Do stuffs, if necessary.
// TODO: make sure to modify changelog.txt with any recent changes
if (lastVersion < 14) {
// addition of districts. Download the required data
redownload = true;
intent.putExtra(LoadTBAData.DATA_TO_LOAD, new short[]{LoadTBAData.LOAD_EVENTS, LoadTBAData.LOAD_DISTRICTS});
}
if (lastVersion < 16) {
// addition of myTBA - Prompt the user for an account
redownload = true;
intent.putExtra(LoadTBAData.DATA_TO_LOAD, new short[]{LoadTBAData.LOAD_EVENTS});
}
if (lastVersion < 21) {
// redownload to get event short names
redownload = true;
intent.putExtra(LoadTBAData.DATA_TO_LOAD, new short[]{LoadTBAData.LOAD_EVENTS});
}
if (lastVersion < 46) {
// recreate search indexes to contain foreign keys
redownload = false;
RecreateSearchIndexes.startActionRecreateSearchIndexes(this);
}
}
// If we don't have to redownload, store the version code here. Otherwise, let the
// RedownloadActivity store the version code upcn completion
if (!redownload) {
prefs.edit().putInt(Constants.APP_VERSION_KEY, BuildConfig.VERSION_CODE).apply();
}
return redownload;
}
private void goToHome() {
startActivity(new Intent(this, HomeActivity.class));
finish();
}
private void processNfcUri(String uri) {
Pattern regexPattern = Pattern.compile(NfcUris.URI_EVENT_MATCHER);
Matcher m = regexPattern.matcher(uri);
if (m.matches()) {
String eventKey = m.group(1);
TaskStackBuilder.create(this).addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_events))
.addNextIntent(ViewEventActivity.newInstance(this, eventKey)).startActivities();
finish();
return;
}
regexPattern = Pattern.compile(NfcUris.URI_TEAM_MATCHER);
m = regexPattern.matcher(uri);
if (m.matches()) {
String teamKey = m.group(1);
TaskStackBuilder.create(this).addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_teams))
.addNextIntent(ViewTeamActivity.newInstance(this, teamKey)).startActivities();
finish();
return;
}
regexPattern = Pattern.compile(NfcUris.URI_TEAM_AT_EVENT_MATCHER);
m = regexPattern.matcher(uri);
if (m.matches()) {
String eventKey = m.group(1);
String teamKey = m.group(2);
TaskStackBuilder.create(this).addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_events))
.addNextIntent(ViewEventActivity.newInstance(this, eventKey))
.addNextIntent(TeamAtEventActivity.newInstance(this, eventKey, teamKey)).startActivities();
finish();
return;
}
regexPattern = Pattern.compile(NfcUris.URI_TEAM_IN_YEAR_MATCHER);
m = regexPattern.matcher(uri);
if (m.matches()) {
String teamKey = m.group(1);
String teamYear = m.group(2);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_events))
.addNextIntent(ViewTeamActivity.newInstance(this, teamKey, Integer.valueOf(teamYear))).startActivities();
finish();
return;
}
regexPattern = Pattern.compile(NfcUris.URI_MATCH_MATCHER);
m = regexPattern.matcher(uri);
if (m.matches()) {
String matchKey = m.group(1);
String eventKey = matchKey.substring(0, matchKey.indexOf("_"));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(HomeActivity.newInstance(this, R.id.nav_item_events))
.addNextIntent(ViewEventActivity.newInstance(this, eventKey))
.addNextIntent(ViewMatchActivity.newInstance(this, matchKey)).startActivities();
finish();
return;
}
// Default to kicking the user to the events list if none of the URIs match
goToHome();
}
}
|
Force data redownload on update to warm caches
|
android/src/main/java/com/thebluealliance/androidclient/activities/LaunchActivity.java
|
Force data redownload on update to warm caches
|
<ide><path>ndroid/src/main/java/com/thebluealliance/androidclient/activities/LaunchActivity.java
<ide> redownload = false;
<ide> RecreateSearchIndexes.startActionRecreateSearchIndexes(this);
<ide> }
<add>
<add> if (lastVersion < 3000000) {
<add> // v3.0 - Reload everything to warm okhttp caches
<add> redownload = true;
<add> intent.putExtra(LoadTBAData.DATA_TO_LOAD, new short[]{LoadTBAData.LOAD_EVENTS, LoadTBAData.LOAD_TEAMS, LoadTBAData.LOAD_DISTRICTS});
<add> }
<ide> }
<ide> // If we don't have to redownload, store the version code here. Otherwise, let the
<ide> // RedownloadActivity store the version code upcn completion
|
|
Java
|
apache-2.0
|
4d67e31db098dd6e2179cef9efca65b0b51d44cb
| 0 |
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
|
/*
* $Header: /usr/local/cvs/module/src/java/File.java,v 1.7 2004/01/16 22:23:11
* keith Exp $ $Revision: 1.2 $ $Date: 2004-08-26 05:14:19 $
*
* Copyright Computer Science Innovations (CSI), 2004. All rights reserved.
*/
package org.springframework.rules.values;
import junit.framework.TestCase;
public class FormModelTests extends TestCase {
public void testNestedProperties() {
Company c = new Company();
Contact contact = new Contact();
contact.setAddress(new Address());
c.setPrimaryContact(contact);
ValidatingFormModel model = new ValidatingFormModel(c);
model.setBufferChangesDefault(false);
ValueModel city = model.add("primaryContact.address.city");
city.addValueListener(new ValueListener() {
public void valueChanged() {
System.out.println("city changed");
}
});
ValueModel addr = model.add("primaryContact.address");
addr.set(new Address());
}
public static class Company {
private String name;
private Contact primaryContact;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Contact getPrimaryContact() {
return primaryContact;
}
public void setPrimaryContact(Contact primaryContact) {
this.primaryContact = primaryContact;
}
}
public static class Contact {
private String name;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
System.out.println("Address set");
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class Address {
private String city;
private String state;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
}
|
sandbox/test/org/springframework/rules/values/FormModelTests.java
|
/*
* $Header: /usr/local/cvs/module/src/java/File.java,v 1.7 2004/01/16 22:23:11
* keith Exp $ $Revision: 1.1 $ $Date: 2004-08-26 03:29:35 $
*
* Copyright Computer Science Innovations (CSI), 2004. All rights reserved.
*/
package org.springframework.rules.values;
import junit.framework.TestCase;
public class FormModelTests extends TestCase {
public void testGetPropertyTokens() {
DefaultFormModel form = new DefaultFormModel();
String propertyPath = "my.test.property.path[0]";
}
}
|
*** empty log message ***
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@3629 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
|
sandbox/test/org/springframework/rules/values/FormModelTests.java
|
*** empty log message ***
|
<ide><path>andbox/test/org/springframework/rules/values/FormModelTests.java
<ide> /*
<ide> * $Header: /usr/local/cvs/module/src/java/File.java,v 1.7 2004/01/16 22:23:11
<del> * keith Exp $ $Revision: 1.1 $ $Date: 2004-08-26 03:29:35 $
<add> * keith Exp $ $Revision: 1.2 $ $Date: 2004-08-26 05:14:19 $
<ide> *
<ide> * Copyright Computer Science Innovations (CSI), 2004. All rights reserved.
<ide> */
<ide> import junit.framework.TestCase;
<ide>
<ide> public class FormModelTests extends TestCase {
<del> public void testGetPropertyTokens() {
<del> DefaultFormModel form = new DefaultFormModel();
<del> String propertyPath = "my.test.property.path[0]";
<add> public void testNestedProperties() {
<add> Company c = new Company();
<add> Contact contact = new Contact();
<add> contact.setAddress(new Address());
<add> c.setPrimaryContact(contact);
<add>
<add> ValidatingFormModel model = new ValidatingFormModel(c);
<add> model.setBufferChangesDefault(false);
<add> ValueModel city = model.add("primaryContact.address.city");
<add> city.addValueListener(new ValueListener() {
<add> public void valueChanged() {
<add> System.out.println("city changed");
<add> }
<add> });
<add> ValueModel addr = model.add("primaryContact.address");
<add> addr.set(new Address());
<add> }
<add>
<add> public static class Company {
<add> private String name;
<add>
<add> private Contact primaryContact;
<add>
<add> public String getName() {
<add> return name;
<add> }
<add>
<add> public void setName(String name) {
<add> this.name = name;
<add> }
<add>
<add> public Contact getPrimaryContact() {
<add> return primaryContact;
<add> }
<add>
<add> public void setPrimaryContact(Contact primaryContact) {
<add> this.primaryContact = primaryContact;
<add> }
<add> }
<add>
<add> public static class Contact {
<add> private String name;
<add>
<add> private Address address;
<add>
<add> public Address getAddress() {
<add> return address;
<add> }
<add>
<add> public void setAddress(Address address) {
<add> System.out.println("Address set");
<add> this.address = address;
<add> }
<add>
<add> public String getName() {
<add> return name;
<add> }
<add>
<add> public void setName(String name) {
<add> this.name = name;
<add> }
<add> }
<add>
<add> public static class Address {
<add> private String city;
<add>
<add> private String state;
<add>
<add> public String getCity() {
<add> return city;
<add> }
<add>
<add> public void setCity(String city) {
<add> this.city = city;
<add> }
<add>
<add> public String getState() {
<add> return state;
<add> }
<add>
<add> public void setState(String state) {
<add> this.state = state;
<add> }
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
e3c468a086e912832299eaca9f887ab71f0ffdbf
| 0 |
apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo
|
/**
* 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.geronimo.mavenplugins.car;
import java.io.File;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.geronimo.deployment.PluginBootstrap2;
import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.AbstractNameQuery;
import org.apache.geronimo.gbean.GBeanData;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.ReferencePatterns;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.kernel.KernelFactory;
import org.apache.geronimo.kernel.KernelRegistry;
import org.apache.geronimo.kernel.Naming;
import org.apache.geronimo.kernel.config.ConfigurationData;
import org.apache.geronimo.kernel.config.ConfigurationManager;
import org.apache.geronimo.kernel.config.ConfigurationUtil;
import org.apache.geronimo.kernel.config.KernelConfigurationManager;
import org.apache.geronimo.kernel.config.LifecycleException;
import org.apache.geronimo.kernel.config.RecordingLifecycleMonitor;
import org.apache.geronimo.kernel.management.State;
import org.apache.geronimo.kernel.repository.DefaultArtifactManager;
import org.apache.geronimo.system.configuration.RepositoryConfigurationStore;
import org.apache.geronimo.system.repository.Maven2Repository;
import org.apache.geronimo.system.resolver.ExplicitDefaultArtifactResolver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.FileUtils;
/**
* Build a Geronimo Configuration using the local Maven infrastructure.
*
* @goal package
* @requiresDependencyResolution compile
*
* @version $Rev$ $Date$
*/
public class PackageMojo extends AbstractCarMojo {
/**
* Directory containing the generated archive.
*
* @parameter expression="${project.build.directory}"
* @required
*/
private File outputDirectory = null;
/**
* The local Maven repository which will be used to pull artifacts into the Geronimo repository when packaging.
*
* @parameter expression="${settings.localRepository}"
* @required
* @readonly
*/
private File repository = null;
/**
* The Geronimo repository where modules will be packaged up from.
*
* @parameter expression="${project.build.directory}/repository"
* @required
*/
private File targetRepository = null;
/**
* The default deployer module to be used when no other deployer modules are configured.
*
* @parameter expression="org.apache.geronimo.framework/geronimo-gbean-deployer/${geronimoVersion}/car"
* @required
* @readonly
*/
private String defaultDeploymentConfig = null;
/**
* Ther deployer modules to be used when packaging.
*
* @parameter
*/
private String[] deploymentConfigs;
/**
* The name of the deployer which will be used to deploy the CAR.
*
* @parameter expression="org.apache.geronimo.framework/geronimo-gbean-deployer/${geronimoVersion}/car?j2eeType=Deployer,name=Deployer"
* @required
*/
private String deployerName = null;
/**
* The plan file for the CAR.
*
* @parameter expression="${project.build.directory}/resources/META-INF/plan.xml"
* @required
*/
private File planFile = null;
/**
* The file to include as a module of the CAR.
*
* @parameter
*/
private File moduleFile = null;
/**
* An {@link Dependency} to include as a module of the CAR.
*
* @parameter
*/
private Dependency module = null;
/**
* The location where the properties mapping will be generated.
* <p/>
* <p>
* Probably don't want to change this.
* </p>
*
* @parameter expression="${project.build.directory}/explicit-versions.properties"
*/
private File explicitResolutionProperties = null;
/**
* True to enable the bootshell when packaging.
*
* @parameter
*/
private boolean bootstrap = false;
/**
* Holds a local repo lookup instance so that we can use the current project to resolve.
* This is required since the Kernel used to deploy is cached.
*/
private static ThreadLocal<Maven2RepositoryAdapter.ArtifactLookup> lookupHolder = new ThreadLocal<Maven2RepositoryAdapter.ArtifactLookup>();
//
// Mojo
//
public void execute() throws MojoExecutionException, MojoFailureException {
try {
// We need to make sure to clean up any previous work first or this operation will fail
FileUtils.forceDelete(targetRepository);
FileUtils.forceMkdir(targetRepository);
if (!planFile.exists()) {
return;
}
// Use the default configs if none specified
if (deploymentConfigs == null) {
if (!bootstrap) {
deploymentConfigs = new String[]{defaultDeploymentConfig};
} else {
deploymentConfigs = new String[]{};
}
}
getLog().debug("Deployment configs: " + Arrays.asList(deploymentConfigs));
getDependencies(project, false);
// If module is set, then resolve the artifact and set moduleFile
if (module != null) {
Artifact artifact = resolveArtifact(module.getGroupId(), module.getArtifactId(), module.getType());
if (artifact == null) {
throw new MojoExecutionException("Could not resolve module " + module.getGroupId() + ":" + module.getArtifactId() + ":" + module.getType() + ". Perhaps it is not listed as a dependency");
}
moduleFile = artifact.getFile();
getLog().debug("Using module file: " + moduleFile);
}
generateExplicitVersionProperties(explicitResolutionProperties, dependencies);
//
// NOTE: Install a local lookup, so that the cached kernel can resolve based on the current project
// and not the project where the kernel was first initialized.
//
lookupHolder.set(new ArtifactLookupImpl());
if (bootstrap) {
executeBootShell();
} else {
buildPackage();
}
} catch (Exception e) {
throw new MojoExecutionException("could not package plugin", e);
}
}
private File getArtifactInRepositoryDir() {
//
// HACK: Generate the filename in the repo... really should delegate this to the repo impl
//
File dir = new File(targetRepository, project.getGroupId().replace('.', '/'));
dir = new File(dir, project.getArtifactId());
dir = new File(dir, project.getVersion());
dir = new File(dir, project.getArtifactId() + "-" + project.getVersion() + ".car");
return dir;
}
public void executeBootShell() throws Exception {
getLog().debug("Starting bootstrap shell...");
PluginBootstrap2 boot = new PluginBootstrap2();
boot.setBuildDir(outputDirectory);
boot.setCarFile(getArtifactInRepositoryDir());
boot.setLocalRepo(repository);
boot.setPlan(planFile);
// Generate expanded so we can use Maven to generate the archive
boot.setExpanded(true);
boot.bootstrap();
}
//
// Deployment
//
private static final String KERNEL_NAME = "geronimo.maven";
/**
* Reference to the kernel that will last the lifetime of this classloader.
* The KernelRegistry keeps soft references that may be garbage collected.
*/
private Kernel kernel;
private AbstractName targetConfigStoreAName;
private AbstractName targetRepositoryAName;
private boolean targetSet;
public void buildPackage() throws Exception {
getLog().info("Packaging module configuration: " + planFile);
Kernel kernel = createKernel();
if (!targetSet) {
kernel.stopGBean(targetRepositoryAName);
kernel.setAttribute(targetRepositoryAName, "root", targetRepository.toURI());
kernel.startGBean(targetRepositoryAName);
if (kernel.getGBeanState(targetConfigStoreAName) != State.RUNNING_INDEX) {
throw new IllegalStateException("After restarted repository then config store is not running");
}
targetSet = true;
}
getLog().debug("Starting configurations..." + Arrays.asList(deploymentConfigs));
// start the Configuration we're going to use for this deployment
ConfigurationManager configurationManager = ConfigurationUtil.getConfigurationManager(kernel);
try {
for (String artifactName : deploymentConfigs) {
org.apache.geronimo.kernel.repository.Artifact configName = org.apache.geronimo.kernel.repository.Artifact.create(artifactName);
if (!configurationManager.isLoaded(configName)) {
RecordingLifecycleMonitor monitor = new RecordingLifecycleMonitor();
try {
configurationManager.loadConfiguration(configName, monitor);
} catch (LifecycleException e) {
getLog().error("Could not load deployer configuration: " + configName + "\n" + monitor.toString(), e);
}
monitor = new RecordingLifecycleMonitor();
try {
configurationManager.startConfiguration(configName, monitor);
getLog().info("Started deployer: " + configName);
} catch (LifecycleException e) {
getLog().error("Could not start deployer configuration: " + configName + "\n" + monitor.toString(), e);
}
}
}
} finally {
ConfigurationUtil.releaseConfigurationManager(kernel, configurationManager);
}
getLog().debug("Deploying...");
AbstractName deployer = locateDeployer(kernel);
invokeDeployer(kernel, deployer, targetConfigStoreAName.toString());
//use a fresh kernel for each module
kernel.shutdown();
kernel = null;
}
/**
* Create a Geronimo Kernel to contain the deployment configurations.
*/
private synchronized Kernel createKernel() throws Exception {
// first return our cached version
if (kernel != null) {
return kernel;
}
getLog().debug("Creating kernel...");
// check the registry in case someone else created one
kernel = KernelRegistry.getKernel(KERNEL_NAME);
if (kernel != null) {
return kernel;
}
// boot one ourselves
kernel = KernelFactory.newInstance().createKernel(KERNEL_NAME);
kernel.boot();
bootDeployerSystem();
return kernel;
}
/**
* Boot the in-Maven deployment system.
* <p/>
* <p>
* This contains Repository and ConfigurationStore GBeans that map to
* the local maven installation.
* </p>
*/
private void bootDeployerSystem() throws Exception {
getLog().debug("Booting deployer system...");
org.apache.geronimo.kernel.repository.Artifact baseId =
new org.apache.geronimo.kernel.repository.Artifact("geronimo", "packaging", "fixed", "car");
Naming naming = kernel.getNaming();
ConfigurationData bootstrap = new ConfigurationData(baseId, naming);
ClassLoader cl = getClass().getClassLoader();
Set<AbstractName> repoNames = new HashSet<AbstractName>();
//
// NOTE: Install an adapter for the source repository that will leverage the Maven2 repository subsystem
// to allow for better handling of SNAPSHOT values.
//
GBeanData repoGBean = bootstrap.addGBean("SourceRepository", GBeanInfo.getGBeanInfo(Maven2RepositoryAdapter.class.getName(), cl));
Maven2RepositoryAdapter.ArtifactLookup lookup = new Maven2RepositoryAdapter.ArtifactLookup() {
private Maven2RepositoryAdapter.ArtifactLookup getDelegate() {
return lookupHolder.get();
}
public File getBasedir() {
return getDelegate().getBasedir();
}
public File getLocation(final org.apache.geronimo.kernel.repository.Artifact artifact) {
return getDelegate().getLocation(artifact);
}
};
repoGBean.setAttribute("lookup", lookup);
repoGBean.setAttribute("dependencies", dependencies);
repoNames.add(repoGBean.getAbstractName());
// Target repo
GBeanData targetRepoGBean = bootstrap.addGBean("TargetRepository", GBeanInfo.getGBeanInfo(Maven2Repository.class.getName(), cl));
URI targetRepositoryURI = targetRepository.toURI();
targetRepoGBean.setAttribute("root", targetRepositoryURI);
repoNames.add(targetRepoGBean.getAbstractName());
targetRepositoryAName = targetRepoGBean.getAbstractName();
GBeanData artifactManagerGBean = bootstrap.addGBean("ArtifactManager", DefaultArtifactManager.GBEAN_INFO);
GBeanData artifactResolverGBean = bootstrap.addGBean("ArtifactResolver", ExplicitDefaultArtifactResolver.GBEAN_INFO);
artifactResolverGBean.setAttribute("versionMapLocation", explicitResolutionProperties.getAbsolutePath());
ReferencePatterns repoPatterns = new ReferencePatterns(repoNames);
artifactResolverGBean.setReferencePatterns("Repositories", repoPatterns);
artifactResolverGBean.setReferencePattern("ArtifactManager", artifactManagerGBean.getAbstractName());
Set storeNames = new HashSet();
// Source config store
GBeanInfo configStoreInfo = GBeanInfo.getGBeanInfo(MavenConfigStore.class.getName(), cl);
GBeanData storeGBean = bootstrap.addGBean("ConfigStore", configStoreInfo);
if (configStoreInfo.getReference("Repository") != null) {
storeGBean.setReferencePattern("Repository", repoGBean.getAbstractName());
}
storeNames.add(storeGBean.getAbstractName());
// Target config store
GBeanInfo targetConfigStoreInfo = GBeanInfo.getGBeanInfo(RepositoryConfigurationStore.class.getName(), cl);
GBeanData targetStoreGBean = bootstrap.addGBean("TargetConfigStore", targetConfigStoreInfo);
if (targetConfigStoreInfo.getReference("Repository") != null) {
targetStoreGBean.setReferencePattern("Repository", targetRepoGBean.getAbstractName());
}
storeNames.add(targetStoreGBean.getAbstractName());
targetConfigStoreAName = targetStoreGBean.getAbstractName();
targetSet = true;
GBeanData attrManagerGBean = bootstrap.addGBean("AttributeStore", MavenAttributeStore.GBEAN_INFO);
GBeanData configManagerGBean = bootstrap.addGBean("ConfigManager", KernelConfigurationManager.GBEAN_INFO);
configManagerGBean.setReferencePatterns("Stores", new ReferencePatterns(storeNames));
configManagerGBean.setReferencePattern("AttributeStore", attrManagerGBean.getAbstractName());
configManagerGBean.setReferencePattern("ArtifactManager", artifactManagerGBean.getAbstractName());
configManagerGBean.setReferencePattern("ArtifactResolver", artifactResolverGBean.getAbstractName());
configManagerGBean.setReferencePatterns("Repositories", repoPatterns);
ConfigurationUtil.loadBootstrapConfiguration(kernel, bootstrap, cl);
}
/**
* Locate a Deployer GBean matching the deployerName pattern.
*
* @param kernel the kernel to search.
* @return the ObjectName of the Deployer GBean
* @throws IllegalStateException if there is not exactly one GBean matching the deployerName pattern
*/
private AbstractName locateDeployer(final Kernel kernel) {
AbstractName name = new AbstractName(URI.create(deployerName));
Iterator i = kernel.listGBeans(new AbstractNameQuery(name)).iterator();
if (!i.hasNext()) {
throw new IllegalStateException("No deployer found matching deployerName: " + name);
}
AbstractName deployer = (AbstractName) i.next();
if (i.hasNext()) {
throw new IllegalStateException("Multiple deployers found matching deployerName: " + name);
}
return deployer;
}
private static final String[] DEPLOY_SIGNATURE = {
boolean.class.getName(),
File.class.getName(),
File.class.getName(),
File.class.getName(),
Boolean.TYPE.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
};
private List invokeDeployer(final Kernel kernel, final AbstractName deployer, final String targetConfigStore) throws Exception {
Object[] args = {
Boolean.FALSE, // Not in-place
moduleFile,
planFile,
null, // Target file
Boolean.TRUE, // Install
null, // main-class
null, // main-gbean
null, // main-method
null, // Manifest configurations
null, // class-path
null, // endorsed-dirs
null, // extension-dirs
targetConfigStore
};
return (List) kernel.invoke(deployer, "deploy", args, DEPLOY_SIGNATURE);
}
}
|
buildsupport/car-maven-plugin/src/main/java/org/apache/geronimo/mavenplugins/car/PackageMojo.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.geronimo.mavenplugins.car;
import java.io.File;
import java.net.URI;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.geronimo.deployment.PluginBootstrap2;
import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.AbstractNameQuery;
import org.apache.geronimo.gbean.GBeanData;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.ReferencePatterns;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.kernel.KernelFactory;
import org.apache.geronimo.kernel.KernelRegistry;
import org.apache.geronimo.kernel.Naming;
import org.apache.geronimo.kernel.config.ConfigurationData;
import org.apache.geronimo.kernel.config.ConfigurationManager;
import org.apache.geronimo.kernel.config.ConfigurationUtil;
import org.apache.geronimo.kernel.config.KernelConfigurationManager;
import org.apache.geronimo.kernel.config.LifecycleException;
import org.apache.geronimo.kernel.config.RecordingLifecycleMonitor;
import org.apache.geronimo.kernel.management.State;
import org.apache.geronimo.kernel.repository.DefaultArtifactManager;
import org.apache.geronimo.system.configuration.RepositoryConfigurationStore;
import org.apache.geronimo.system.repository.Maven2Repository;
import org.apache.geronimo.system.resolver.ExplicitDefaultArtifactResolver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.FileUtils;
/**
* Build a Geronimo Configuration using the local Maven infrastructure.
*
* @goal package
* @requiresDependencyResolution compile
*
* @version $Rev$ $Date$
*/
public class PackageMojo extends AbstractCarMojo {
/**
* Directory containing the generated archive.
*
* @parameter expression="${project.build.directory}"
* @required
*/
private File outputDirectory = null;
/**
* The local Maven repository which will be used to pull artifacts into the Geronimo repository when packaging.
*
* @parameter expression="${settings.localRepository}"
* @required
* @readonly
*/
private File repository = null;
/**
* The Geronimo repository where modules will be packaged up from.
*
* @parameter expression="${project.build.directory}/repository"
* @required
*/
private File targetRepository = null;
/**
* The default deployer module to be used when no other deployer modules are configured.
*
* @parameter expression="org.apache.geronimo.framework/geronimo-gbean-deployer/${geronimoVersion}/car"
* @required
* @readonly
*/
private String defaultDeploymentConfig = null;
/**
* Ther deployer modules to be used when packaging.
*
* @parameter
*/
private String[] deploymentConfigs;
/**
* The name of the deployer which will be used to deploy the CAR.
*
* @parameter expression="org.apache.geronimo.framework/geronimo-gbean-deployer/${geronimoVersion}/car?j2eeType=Deployer,name=Deployer"
* @required
*/
private String deployerName = null;
/**
* The plan file for the CAR.
*
* @parameter expression="${project.build.directory}/resources/META-INF/plan.xml"
* @required
*/
private File planFile = null;
/**
* The file to include as a module of the CAR.
*
* @parameter
*/
private File moduleFile = null;
/**
* An {@link Dependency} to include as a module of the CAR.
*
* @parameter
*/
private Dependency module = null;
/**
* The location where the properties mapping will be generated.
* <p/>
* <p>
* Probably don't want to change this.
* </p>
*
* @parameter expression="${project.build.directory}/explicit-versions.properties"
*/
private File explicitResolutionProperties = null;
/**
* True to enable the bootshell when packaging.
*
* @parameter
*/
private boolean bootstrap = false;
/**
* Holds a local repo lookup instance so that we can use the current project to resolve.
* This is required since the Kernel used to deploy is cached.
*/
private static ThreadLocal<Maven2RepositoryAdapter.ArtifactLookup> lookupHolder = new ThreadLocal<Maven2RepositoryAdapter.ArtifactLookup>();
//
// Mojo
//
public void execute() throws MojoExecutionException, MojoFailureException {
try {
// We need to make sure to clean up any previous work first or this operation will fail
FileUtils.forceDelete(targetRepository);
FileUtils.forceMkdir(targetRepository);
if (!planFile.exists()) {
return;
}
// Use the default configs if none specified
if (deploymentConfigs == null) {
if (!bootstrap) {
deploymentConfigs = new String[]{defaultDeploymentConfig};
} else {
deploymentConfigs = new String[]{};
}
}
getLog().debug("Deployment configs: " + Arrays.asList(deploymentConfigs));
getDependencies(project, false);
// If module is set, then resolve the artifact and set moduleFile
if (module != null) {
Artifact artifact = resolveArtifact(module.getGroupId(), module.getArtifactId(), module.getType());
moduleFile = artifact.getFile();
getLog().debug("Using module file: " + moduleFile);
}
generateExplicitVersionProperties(explicitResolutionProperties, dependencies);
//
// NOTE: Install a local lookup, so that the cached kernel can resolve based on the current project
// and not the project where the kernel was first initialized.
//
lookupHolder.set(new ArtifactLookupImpl());
if (bootstrap) {
executeBootShell();
} else {
buildPackage();
}
} catch (Exception e) {
throw new MojoExecutionException("could not package plugin", e);
}
}
private File getArtifactInRepositoryDir() {
//
// HACK: Generate the filename in the repo... really should delegate this to the repo impl
//
File dir = new File(targetRepository, project.getGroupId().replace('.', '/'));
dir = new File(dir, project.getArtifactId());
dir = new File(dir, project.getVersion());
dir = new File(dir, project.getArtifactId() + "-" + project.getVersion() + ".car");
return dir;
}
public void executeBootShell() throws Exception {
getLog().debug("Starting bootstrap shell...");
PluginBootstrap2 boot = new PluginBootstrap2();
boot.setBuildDir(outputDirectory);
boot.setCarFile(getArtifactInRepositoryDir());
boot.setLocalRepo(repository);
boot.setPlan(planFile);
// Generate expanded so we can use Maven to generate the archive
boot.setExpanded(true);
boot.bootstrap();
}
//
// Deployment
//
private static final String KERNEL_NAME = "geronimo.maven";
/**
* Reference to the kernel that will last the lifetime of this classloader.
* The KernelRegistry keeps soft references that may be garbage collected.
*/
private Kernel kernel;
private AbstractName targetConfigStoreAName;
private AbstractName targetRepositoryAName;
private boolean targetSet;
public void buildPackage() throws Exception {
getLog().info("Packaging module configuration: " + planFile);
Kernel kernel = createKernel();
if (!targetSet) {
kernel.stopGBean(targetRepositoryAName);
kernel.setAttribute(targetRepositoryAName, "root", targetRepository.toURI());
kernel.startGBean(targetRepositoryAName);
if (kernel.getGBeanState(targetConfigStoreAName) != State.RUNNING_INDEX) {
throw new IllegalStateException("After restarted repository then config store is not running");
}
targetSet = true;
}
getLog().debug("Starting configurations..." + Arrays.asList(deploymentConfigs));
// start the Configuration we're going to use for this deployment
ConfigurationManager configurationManager = ConfigurationUtil.getConfigurationManager(kernel);
try {
for (String artifactName : deploymentConfigs) {
org.apache.geronimo.kernel.repository.Artifact configName = org.apache.geronimo.kernel.repository.Artifact.create(artifactName);
if (!configurationManager.isLoaded(configName)) {
RecordingLifecycleMonitor monitor = new RecordingLifecycleMonitor();
try {
configurationManager.loadConfiguration(configName, monitor);
} catch (LifecycleException e) {
getLog().error("Could not load deployer configuration: " + configName + "\n" + monitor.toString(), e);
}
monitor = new RecordingLifecycleMonitor();
try {
configurationManager.startConfiguration(configName, monitor);
getLog().info("Started deployer: " + configName);
} catch (LifecycleException e) {
getLog().error("Could not start deployer configuration: " + configName + "\n" + monitor.toString(), e);
}
}
}
} finally {
ConfigurationUtil.releaseConfigurationManager(kernel, configurationManager);
}
getLog().debug("Deploying...");
AbstractName deployer = locateDeployer(kernel);
invokeDeployer(kernel, deployer, targetConfigStoreAName.toString());
//use a fresh kernel for each module
kernel.shutdown();
kernel = null;
}
/**
* Create a Geronimo Kernel to contain the deployment configurations.
*/
private synchronized Kernel createKernel() throws Exception {
// first return our cached version
if (kernel != null) {
return kernel;
}
getLog().debug("Creating kernel...");
// check the registry in case someone else created one
kernel = KernelRegistry.getKernel(KERNEL_NAME);
if (kernel != null) {
return kernel;
}
// boot one ourselves
kernel = KernelFactory.newInstance().createKernel(KERNEL_NAME);
kernel.boot();
bootDeployerSystem();
return kernel;
}
/**
* Boot the in-Maven deployment system.
* <p/>
* <p>
* This contains Repository and ConfigurationStore GBeans that map to
* the local maven installation.
* </p>
*/
private void bootDeployerSystem() throws Exception {
getLog().debug("Booting deployer system...");
org.apache.geronimo.kernel.repository.Artifact baseId =
new org.apache.geronimo.kernel.repository.Artifact("geronimo", "packaging", "fixed", "car");
Naming naming = kernel.getNaming();
ConfigurationData bootstrap = new ConfigurationData(baseId, naming);
ClassLoader cl = getClass().getClassLoader();
Set<AbstractName> repoNames = new HashSet<AbstractName>();
//
// NOTE: Install an adapter for the source repository that will leverage the Maven2 repository subsystem
// to allow for better handling of SNAPSHOT values.
//
GBeanData repoGBean = bootstrap.addGBean("SourceRepository", GBeanInfo.getGBeanInfo(Maven2RepositoryAdapter.class.getName(), cl));
Maven2RepositoryAdapter.ArtifactLookup lookup = new Maven2RepositoryAdapter.ArtifactLookup() {
private Maven2RepositoryAdapter.ArtifactLookup getDelegate() {
return lookupHolder.get();
}
public File getBasedir() {
return getDelegate().getBasedir();
}
public File getLocation(final org.apache.geronimo.kernel.repository.Artifact artifact) {
return getDelegate().getLocation(artifact);
}
};
repoGBean.setAttribute("lookup", lookup);
repoGBean.setAttribute("dependencies", dependencies);
repoNames.add(repoGBean.getAbstractName());
// Target repo
GBeanData targetRepoGBean = bootstrap.addGBean("TargetRepository", GBeanInfo.getGBeanInfo(Maven2Repository.class.getName(), cl));
URI targetRepositoryURI = targetRepository.toURI();
targetRepoGBean.setAttribute("root", targetRepositoryURI);
repoNames.add(targetRepoGBean.getAbstractName());
targetRepositoryAName = targetRepoGBean.getAbstractName();
GBeanData artifactManagerGBean = bootstrap.addGBean("ArtifactManager", DefaultArtifactManager.GBEAN_INFO);
GBeanData artifactResolverGBean = bootstrap.addGBean("ArtifactResolver", ExplicitDefaultArtifactResolver.GBEAN_INFO);
artifactResolverGBean.setAttribute("versionMapLocation", explicitResolutionProperties.getAbsolutePath());
ReferencePatterns repoPatterns = new ReferencePatterns(repoNames);
artifactResolverGBean.setReferencePatterns("Repositories", repoPatterns);
artifactResolverGBean.setReferencePattern("ArtifactManager", artifactManagerGBean.getAbstractName());
Set storeNames = new HashSet();
// Source config store
GBeanInfo configStoreInfo = GBeanInfo.getGBeanInfo(MavenConfigStore.class.getName(), cl);
GBeanData storeGBean = bootstrap.addGBean("ConfigStore", configStoreInfo);
if (configStoreInfo.getReference("Repository") != null) {
storeGBean.setReferencePattern("Repository", repoGBean.getAbstractName());
}
storeNames.add(storeGBean.getAbstractName());
// Target config store
GBeanInfo targetConfigStoreInfo = GBeanInfo.getGBeanInfo(RepositoryConfigurationStore.class.getName(), cl);
GBeanData targetStoreGBean = bootstrap.addGBean("TargetConfigStore", targetConfigStoreInfo);
if (targetConfigStoreInfo.getReference("Repository") != null) {
targetStoreGBean.setReferencePattern("Repository", targetRepoGBean.getAbstractName());
}
storeNames.add(targetStoreGBean.getAbstractName());
targetConfigStoreAName = targetStoreGBean.getAbstractName();
targetSet = true;
GBeanData attrManagerGBean = bootstrap.addGBean("AttributeStore", MavenAttributeStore.GBEAN_INFO);
GBeanData configManagerGBean = bootstrap.addGBean("ConfigManager", KernelConfigurationManager.GBEAN_INFO);
configManagerGBean.setReferencePatterns("Stores", new ReferencePatterns(storeNames));
configManagerGBean.setReferencePattern("AttributeStore", attrManagerGBean.getAbstractName());
configManagerGBean.setReferencePattern("ArtifactManager", artifactManagerGBean.getAbstractName());
configManagerGBean.setReferencePattern("ArtifactResolver", artifactResolverGBean.getAbstractName());
configManagerGBean.setReferencePatterns("Repositories", repoPatterns);
ConfigurationUtil.loadBootstrapConfiguration(kernel, bootstrap, cl);
}
/**
* Locate a Deployer GBean matching the deployerName pattern.
*
* @param kernel the kernel to search.
* @return the ObjectName of the Deployer GBean
* @throws IllegalStateException if there is not exactly one GBean matching the deployerName pattern
*/
private AbstractName locateDeployer(final Kernel kernel) {
AbstractName name = new AbstractName(URI.create(deployerName));
Iterator i = kernel.listGBeans(new AbstractNameQuery(name)).iterator();
if (!i.hasNext()) {
throw new IllegalStateException("No deployer found matching deployerName: " + name);
}
AbstractName deployer = (AbstractName) i.next();
if (i.hasNext()) {
throw new IllegalStateException("Multiple deployers found matching deployerName: " + name);
}
return deployer;
}
private static final String[] DEPLOY_SIGNATURE = {
boolean.class.getName(),
File.class.getName(),
File.class.getName(),
File.class.getName(),
Boolean.TYPE.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
String.class.getName(),
};
private List invokeDeployer(final Kernel kernel, final AbstractName deployer, final String targetConfigStore) throws Exception {
Object[] args = {
Boolean.FALSE, // Not in-place
moduleFile,
planFile,
null, // Target file
Boolean.TRUE, // Install
null, // main-class
null, // main-gbean
null, // main-method
null, // Manifest configurations
null, // class-path
null, // endorsed-dirs
null, // extension-dirs
targetConfigStore
};
return (List) kernel.invoke(deployer, "deploy", args, DEPLOY_SIGNATURE);
}
}
|
more info on a common error
git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@696509 13f79535-47bb-0310-9956-ffa450edef68
|
buildsupport/car-maven-plugin/src/main/java/org/apache/geronimo/mavenplugins/car/PackageMojo.java
|
more info on a common error
|
<ide><path>uildsupport/car-maven-plugin/src/main/java/org/apache/geronimo/mavenplugins/car/PackageMojo.java
<ide> // If module is set, then resolve the artifact and set moduleFile
<ide> if (module != null) {
<ide> Artifact artifact = resolveArtifact(module.getGroupId(), module.getArtifactId(), module.getType());
<add> if (artifact == null) {
<add> throw new MojoExecutionException("Could not resolve module " + module.getGroupId() + ":" + module.getArtifactId() + ":" + module.getType() + ". Perhaps it is not listed as a dependency");
<add> }
<ide> moduleFile = artifact.getFile();
<ide> getLog().debug("Using module file: " + moduleFile);
<ide> }
|
|
Java
|
apache-2.0
|
41eed9862ea8634446d904af973e64dd1d54b4b2
| 0 |
baomidou/mybatis-plus,baomidou/mybatis-plus
|
/*
* Copyright (c) 2011-2020, baomidou ([email protected]).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.baomidou.mybatisplus.core.toolkit;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.scripting.LanguageDriver;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static java.util.stream.Collectors.toList;
/**
* <p>
* 实体类反射表辅助类
* </p>
*
* @author hubin sjy
* @since 2016-09-09
*/
public class TableInfoHelper {
private static final Log logger = LogFactory.getLog(TableInfoHelper.class);
/**
* 储存反射类表信息
*/
private static final Map<Class<?>, TableInfo> TABLE_INFO_CACHE = new ConcurrentHashMap<>();
/**
* 默认表主键名称
*/
private static final String DEFAULT_ID_NAME = "id";
/**
* <p>
* 获取实体映射表信息
* </p>
*
* @param clazz 反射实体类
* @return 数据库表反射信息
*/
public static TableInfo getTableInfo(Class<?> clazz) {
if (clazz == null
|| ReflectionKit.isPrimitiveOrWrapper(clazz)
|| clazz == String.class) {
return null;
}
// https://github.com/baomidou/mybatis-plus/issues/299
TableInfo tableInfo = TABLE_INFO_CACHE.get(ClassUtils.getUserClass(clazz));
if (null != tableInfo) {
return tableInfo;
}
//尝试获取父类缓存
Class<?> currentClass = clazz;
while (null == tableInfo && Object.class != currentClass) {
currentClass = currentClass.getSuperclass();
tableInfo = TABLE_INFO_CACHE.get(ClassUtils.getUserClass(currentClass));
}
if (tableInfo != null) {
TABLE_INFO_CACHE.put(ClassUtils.getUserClass(clazz), tableInfo);
}
return tableInfo;
}
/**
* <p>
* 获取所有实体映射表信息
* </p>
*
* @return 数据库表反射信息集合
*/
@SuppressWarnings("unused")
public static List<TableInfo> getTableInfos() {
return new ArrayList<>(TABLE_INFO_CACHE.values());
}
/**
* <p>
* 实体类反射获取表信息【初始化】
* </p>
*
* @param clazz 反射实体类
* @return 数据库表反射信息
*/
public synchronized static TableInfo initTableInfo(MapperBuilderAssistant builderAssistant, Class<?> clazz) {
TableInfo tableInfo = TABLE_INFO_CACHE.get(clazz);
if (tableInfo != null) {
if (builderAssistant != null) {
tableInfo.setConfiguration(builderAssistant.getConfiguration());
}
return tableInfo;
}
/* 没有获取到缓存信息,则初始化 */
tableInfo = new TableInfo(clazz);
GlobalConfig globalConfig;
if (null != builderAssistant) {
tableInfo.setCurrentNamespace(builderAssistant.getCurrentNamespace());
tableInfo.setConfiguration(builderAssistant.getConfiguration());
globalConfig = GlobalConfigUtils.getGlobalConfig(builderAssistant.getConfiguration());
} else {
// 兼容测试场景
globalConfig = GlobalConfigUtils.defaults();
}
/* 初始化表名相关 */
initTableName(clazz, globalConfig, tableInfo);
/* 初始化字段相关 */
initTableFields(clazz, globalConfig, tableInfo);
/* 放入缓存 */
TABLE_INFO_CACHE.put(clazz, tableInfo);
/* 缓存 lambda */
LambdaUtils.installCache(tableInfo);
// todo 暂时不开放 tableInfo.initResultMapIfNeed();
return tableInfo;
}
/**
* <p>
* 初始化 表数据库类型,表名,resultMap
* </p>
*
* @param clazz 实体类
* @param globalConfig 全局配置
* @param tableInfo 数据库表反射信息
*/
private static void initTableName(Class<?> clazz, GlobalConfig globalConfig, TableInfo tableInfo) {
/* 数据库全局配置 */
GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
TableName table = clazz.getAnnotation(TableName.class);
String tableName = clazz.getSimpleName();
String tablePrefix = dbConfig.getTablePrefix();
String schema = dbConfig.getSchema();
boolean tablePrefixEffect = true;
if (table != null) {
if (StringUtils.isNotEmpty(table.value())) {
tableName = table.value();
if (StringUtils.isNotEmpty(tablePrefix) && !table.keepGlobalPrefix()) {
tablePrefixEffect = false;
}
} else {
tableName = initTableNameWithDbConfig(tableName, dbConfig);
}
if (StringUtils.isNotEmpty(table.schema())) {
schema = table.schema();
}
/* 表结果集映射 */
if (StringUtils.isNotEmpty(table.resultMap())) {
tableInfo.setResultMap(table.resultMap());
}
tableInfo.setAutoInitResultMap(table.autoResultMap());
} else {
tableName = initTableNameWithDbConfig(tableName, dbConfig);
}
String targetTableName = tableName;
if (StringUtils.isNotEmpty(tablePrefix) && tablePrefixEffect) {
targetTableName = tablePrefix + targetTableName;
}
if (StringUtils.isNotEmpty(schema)) {
targetTableName = schema + StringPool.DOT + targetTableName;
}
tableInfo.setTableName(targetTableName);
/* 开启了自定义 KEY 生成器 */
if (null != dbConfig.getKeyGenerator()) {
tableInfo.setKeySequence(clazz.getAnnotation(KeySequence.class));
}
}
/**
* 根据 DbConfig 初始化 表名
*
* @param className 类名
* @param dbConfig DbConfig
* @return 表名
*/
private static String initTableNameWithDbConfig(String className, GlobalConfig.DbConfig dbConfig) {
String tableName = className;
// 开启表名下划线申明
if (dbConfig.isTableUnderline()) {
tableName = StringUtils.camelToUnderline(tableName);
}
// 大写命名判断
if (dbConfig.isCapitalMode()) {
tableName = tableName.toUpperCase();
} else {
// 首字母小写
tableName = StringUtils.firstToLowerCase(tableName);
}
return tableName;
}
/**
* <p>
* 初始化 表主键,表字段
* </p>
*
* @param clazz 实体类
* @param globalConfig 全局配置
* @param tableInfo 数据库表反射信息
*/
public static void initTableFields(Class<?> clazz, GlobalConfig globalConfig, TableInfo tableInfo) {
/* 数据库全局配置 */
GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
List<Field> list = getAllFields(clazz);
// 标记是否读取到主键
boolean isReadPK = false;
// 是否存在 @TableId 注解
boolean existTableId = isExistTableId(list);
List<TableFieldInfo> fieldList = new ArrayList<>();
for (Field field : list) {
/*
* 主键ID 初始化
*/
if (!isReadPK) {
if (existTableId) {
isReadPK = initTableIdWithAnnotation(dbConfig, tableInfo, field, clazz);
} else {
isReadPK = initTableIdWithoutAnnotation(dbConfig, tableInfo, field, clazz);
}
if (isReadPK) {
continue;
}
}
/* 有 @TableField 注解的字段初始化 */
if (initTableFieldWithAnnotation(dbConfig, tableInfo, fieldList, field, clazz)) {
continue;
}
/* 无 @TableField 注解的字段初始化 */
fieldList.add(new TableFieldInfo(dbConfig, tableInfo, field));
}
/* 检查逻辑删除字段只能有最多一个 */
Assert.isTrue(fieldList.parallelStream().filter(TableFieldInfo::isLogicDelete).count() < 2L,
String.format("annotation of @TableLogic can't more than one in class : %s.", clazz.getName()));
/* 字段列表 */
tableInfo.setFieldList(fieldList);
/* 未发现主键注解,提示警告信息 */
if (StringUtils.isEmpty(tableInfo.getKeyColumn())) {
logger.warn(String.format("Warn: Could not find @TableId in Class: %s.", clazz.getName()));
}
}
/**
* <p>
* 判断主键注解是否存在
* </p>
*
* @param list 字段列表
* @return true 为存在 @TableId 注解;
*/
public static boolean isExistTableId(List<Field> list) {
for (Field field : list) {
TableId tableId = field.getAnnotation(TableId.class);
if (tableId != null) {
return true;
}
}
return false;
}
/**
* <p>
* 主键属性初始化
* </p>
*
* @param dbConfig 全局配置信息
* @param tableInfo 表信息
* @param field 字段
* @param clazz 实体类
* @return true 继续下一个属性判断,返回 continue;
*/
private static boolean initTableIdWithAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
Field field, Class<?> clazz) {
TableId tableId = field.getAnnotation(TableId.class);
boolean underCamel = tableInfo.isUnderCamel();
if (tableId != null) {
if (StringUtils.isEmpty(tableInfo.getKeyColumn())) {
/* 主键策略( 注解 > 全局 ) */
// 设置 Sequence 其他策略无效
if (IdType.NONE == tableId.type()) {
tableInfo.setIdType(dbConfig.getIdType());
} else {
tableInfo.setIdType(tableId.type());
}
/* 字段 */
String column = field.getName();
if (StringUtils.isNotEmpty(tableId.value())) {
column = tableId.value();
} else {
// 开启字段下划线申明
if (underCamel) {
column = StringUtils.camelToUnderline(column);
}
// 全局大写命名
if (dbConfig.isCapitalMode()) {
column = column.toUpperCase();
}
}
tableInfo.setKeyRelated(checkRelated(underCamel, field.getName(), column))
.setKeyColumn(column)
.setKeyProperty(field.getName())
.setKeyType(field.getType());
return true;
} else {
throwExceptionId(clazz);
}
}
return false;
}
/**
* <p>
* 主键属性初始化
* </p>
*
* @param tableInfo 表信息
* @param field 字段
* @param clazz 实体类
* @return true 继续下一个属性判断,返回 continue;
*/
private static boolean initTableIdWithoutAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
Field field, Class<?> clazz) {
String column = field.getName();
if (dbConfig.isCapitalMode()) {
column = column.toUpperCase();
}
if (DEFAULT_ID_NAME.equalsIgnoreCase(column)) {
if (StringUtils.isEmpty(tableInfo.getKeyColumn())) {
tableInfo.setKeyRelated(checkRelated(tableInfo.isUnderCamel(), field.getName(), column))
.setIdType(dbConfig.getIdType())
.setKeyColumn(column)
.setKeyProperty(field.getName())
.setKeyType(field.getType());
return true;
} else {
throwExceptionId(clazz);
}
}
return false;
}
/**
* <p>
* 字段属性初始化
* </p>
*
* @param dbConfig 数据库全局配置
* @param tableInfo 表信息
* @param fieldList 字段列表
* @param clazz 当前表对象类
* @return true 继续下一个属性判断,返回 continue;
*/
private static boolean initTableFieldWithAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
List<TableFieldInfo> fieldList, Field field, Class<?> clazz) {
/* 获取注解属性,自定义字段 */
TableField tableField = field.getAnnotation(TableField.class);
if (null == tableField) {
return false;
}
String columnName = field.getName();
boolean columnNameFromTableField = false;
if (StringUtils.isNotEmpty(tableField.value())) {
columnName = tableField.value();
columnNameFromTableField = true;
}
String el = StringUtils.isNotEmpty(tableField.el()) ? tableField.el() : field.getName();
String columnFormat = dbConfig.getColumnFormat();
if (StringUtils.isNotEmpty(columnFormat) && (!columnNameFromTableField || tableField.keepGlobalFormat())) {
columnName = String.format(columnFormat, columnName);
}
fieldList.add(new TableFieldInfo(dbConfig, tableInfo, field, columnName, el, tableField));
return true;
}
/**
* <p>
* 判定 related 的值
* </p>
*
* @param underCamel 驼峰命名
* @param property 属性名
* @param column 字段名
* @return related
*/
public static boolean checkRelated(boolean underCamel, String property, String column) {
if (StringUtils.isNotColumnName(column)) {
// 首尾有转义符,手动在注解里设置了转义符,去除掉转义符
column = column.substring(1, column.length() - 1);
}
String propertyUpper = property.toUpperCase(Locale.ENGLISH);
String columnUpper = column.toUpperCase(Locale.ENGLISH);
if (underCamel) {
// 开启了驼峰并且 column 包含下划线
return !(propertyUpper.equals(columnUpper) ||
propertyUpper.equals(columnUpper.replace(StringPool.UNDERSCORE, StringPool.EMPTY)));
} else {
// 未开启驼峰,直接判断 property 是否与 column 相同(全大写)
return !propertyUpper.equals(columnUpper);
}
}
/**
* 发现设置多个主键注解抛出异常
*/
private static void throwExceptionId(Class<?> clazz) {
throw ExceptionUtils.mpe("There must be only one, Discover multiple @TableId annotation in %s", clazz.getName());
}
/**
* <p>
* 获取该类的所有属性列表
* </p>
*
* @param clazz 反射类
* @return 属性集合
*/
public static List<Field> getAllFields(Class<?> clazz) {
List<Field> fieldList = ReflectionKit.getFieldList(ClassUtils.getUserClass(clazz));
if (CollectionUtils.isNotEmpty(fieldList)) {
return fieldList.stream()
.filter(i -> {
/* 过滤注解非表字段属性 */
TableField tableField = i.getAnnotation(TableField.class);
return (tableField == null || tableField.exist());
}).collect(toList());
}
return fieldList;
}
/**
* 自定义 KEY 生成器
*/
public static KeyGenerator genKeyGenerator(TableInfo tableInfo, MapperBuilderAssistant builderAssistant,
String baseStatementId, LanguageDriver languageDriver) {
IKeyGenerator keyGenerator = GlobalConfigUtils.getKeyGenerator(builderAssistant.getConfiguration());
if (null == keyGenerator) {
throw new IllegalArgumentException("not configure IKeyGenerator implementation class.");
}
String id = baseStatementId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
Class<?> resultTypeClass = tableInfo.getKeySequence().clazz();
StatementType statementType = StatementType.PREPARED;
String keyProperty = tableInfo.getKeyProperty();
String keyColumn = tableInfo.getKeyColumn();
SqlSource sqlSource = languageDriver.createSqlSource(builderAssistant.getConfiguration(),
keyGenerator.executeSql(tableInfo.getKeySequence().value()), null);
builderAssistant.addMappedStatement(id, sqlSource, statementType, SqlCommandType.SELECT, null, null, null,
null, null, resultTypeClass, null, false, false, false,
new NoKeyGenerator(), keyProperty, keyColumn, null, languageDriver, null);
id = builderAssistant.applyCurrentNamespace(id, false);
MappedStatement keyStatement = builderAssistant.getConfiguration().getMappedStatement(id, false);
SelectKeyGenerator selectKeyGenerator = new SelectKeyGenerator(keyStatement, true);
builderAssistant.getConfiguration().addKeyGenerator(id, selectKeyGenerator);
return selectKeyGenerator;
}
}
|
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/toolkit/TableInfoHelper.java
|
/*
* Copyright (c) 2011-2020, baomidou ([email protected]).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.baomidou.mybatisplus.core.toolkit;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.scripting.LanguageDriver;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static java.util.stream.Collectors.toList;
/**
* <p>
* 实体类反射表辅助类
* </p>
*
* @author hubin sjy
* @since 2016-09-09
*/
public class TableInfoHelper {
private static final Log logger = LogFactory.getLog(TableInfoHelper.class);
/**
* 储存反射类表信息
*/
private static final Map<Class<?>, TableInfo> TABLE_INFO_CACHE = new ConcurrentHashMap<>();
/**
* 默认表主键名称
*/
private static final String DEFAULT_ID_NAME = "id";
/**
* <p>
* 获取实体映射表信息
* </p>
*
* @param clazz 反射实体类
* @return 数据库表反射信息
*/
public static TableInfo getTableInfo(Class<?> clazz) {
if (clazz == null
|| ReflectionKit.isPrimitiveOrWrapper(clazz)
|| clazz == String.class) {
return null;
}
// https://github.com/baomidou/mybatis-plus/issues/299
TableInfo tableInfo = TABLE_INFO_CACHE.get(ClassUtils.getUserClass(clazz));
if (null != tableInfo) {
return tableInfo;
}
//尝试获取父类缓存
Class<?> currentClass = clazz;
while (null == tableInfo && Object.class != currentClass) {
currentClass = currentClass.getSuperclass();
tableInfo = TABLE_INFO_CACHE.get(ClassUtils.getUserClass(currentClass));
}
if (tableInfo != null) {
TABLE_INFO_CACHE.put(ClassUtils.getUserClass(clazz), tableInfo);
}
return tableInfo;
}
/**
* <p>
* 获取所有实体映射表信息
* </p>
*
* @return 数据库表反射信息集合
*/
@SuppressWarnings("unused")
public static List<TableInfo> getTableInfos() {
return new ArrayList<>(TABLE_INFO_CACHE.values());
}
/**
* <p>
* 实体类反射获取表信息【初始化】
* </p>
*
* @param clazz 反射实体类
* @return 数据库表反射信息
*/
public synchronized static TableInfo initTableInfo(MapperBuilderAssistant builderAssistant, Class<?> clazz) {
TableInfo tableInfo = TABLE_INFO_CACHE.get(clazz);
if (tableInfo != null) {
if (builderAssistant != null) {
tableInfo.setConfiguration(builderAssistant.getConfiguration());
}
return tableInfo;
}
/* 没有获取到缓存信息,则初始化 */
tableInfo = new TableInfo(clazz);
GlobalConfig globalConfig;
if (null != builderAssistant) {
tableInfo.setCurrentNamespace(builderAssistant.getCurrentNamespace());
tableInfo.setConfiguration(builderAssistant.getConfiguration());
globalConfig = GlobalConfigUtils.getGlobalConfig(builderAssistant.getConfiguration());
} else {
// 兼容测试场景
globalConfig = GlobalConfigUtils.defaults();
}
/* 初始化表名相关 */
initTableName(clazz, globalConfig, tableInfo);
/* 初始化字段相关 */
initTableFields(clazz, globalConfig, tableInfo);
/* 放入缓存 */
TABLE_INFO_CACHE.put(clazz, tableInfo);
/* 缓存 lambda */
LambdaUtils.installCache(tableInfo);
// todo 暂时不开放 tableInfo.initResultMapIfNeed();
return tableInfo;
}
/**
* <p>
* 初始化 表数据库类型,表名,resultMap
* </p>
*
* @param clazz 实体类
* @param globalConfig 全局配置
* @param tableInfo 数据库表反射信息
*/
private static void initTableName(Class<?> clazz, GlobalConfig globalConfig, TableInfo tableInfo) {
/* 数据库全局配置 */
GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
TableName table = clazz.getAnnotation(TableName.class);
String tableName = clazz.getSimpleName();
String tablePrefix = dbConfig.getTablePrefix();
String schema = dbConfig.getSchema();
boolean tablePrefixEffect = true;
if (table != null) {
if (StringUtils.isNotEmpty(table.value())) {
tableName = table.value();
if (StringUtils.isNotEmpty(tablePrefix) && !table.keepGlobalPrefix()) {
tablePrefixEffect = false;
}
} else {
tableName = initTableNameWithDbConfig(tableName, dbConfig);
}
if (StringUtils.isNotEmpty(table.schema())) {
schema = table.schema();
}
/* 表结果集映射 */
if (StringUtils.isNotEmpty(table.resultMap())) {
tableInfo.setResultMap(table.resultMap());
}
tableInfo.setAutoInitResultMap(table.autoResultMap());
} else {
tableName = initTableNameWithDbConfig(tableName, dbConfig);
}
String targetTableName = tableName;
if (StringUtils.isNotEmpty(tablePrefix) && tablePrefixEffect) {
targetTableName = tablePrefix + targetTableName;
}
if (StringUtils.isNotEmpty(schema)) {
targetTableName = schema + StringPool.DOT + targetTableName;
}
tableInfo.setTableName(targetTableName);
/* 开启了自定义 KEY 生成器 */
if (null != dbConfig.getKeyGenerator()) {
tableInfo.setKeySequence(clazz.getAnnotation(KeySequence.class));
}
}
/**
* 根据 DbConfig 初始化 表名
*
* @param className 类名
* @param dbConfig DbConfig
* @return 表名
*/
private static String initTableNameWithDbConfig(String className, GlobalConfig.DbConfig dbConfig) {
String tableName = className;
// 开启表名下划线申明
if (dbConfig.isTableUnderline()) {
tableName = StringUtils.camelToUnderline(tableName);
}
// 大写命名判断
if (dbConfig.isCapitalMode()) {
tableName = tableName.toUpperCase();
} else {
// 首字母小写
tableName = StringUtils.firstToLowerCase(tableName);
}
return tableName;
}
/**
* <p>
* 初始化 表主键,表字段
* </p>
*
* @param clazz 实体类
* @param globalConfig 全局配置
* @param tableInfo 数据库表反射信息
*/
public static void initTableFields(Class<?> clazz, GlobalConfig globalConfig, TableInfo tableInfo) {
/* 数据库全局配置 */
GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
List<Field> list = getAllFields(clazz);
// 标记是否读取到主键
boolean isReadPK = false;
// 是否存在 @TableId 注解
boolean existTableId = isExistTableId(list);
List<TableFieldInfo> fieldList = new ArrayList<>();
for (Field field : list) {
/*
* 主键ID 初始化
*/
if (!isReadPK) {
if (existTableId) {
isReadPK = initTableIdWithAnnotation(dbConfig, tableInfo, field, clazz);
} else {
isReadPK = initTableIdWithoutAnnotation(dbConfig, tableInfo, field, clazz);
}
if (isReadPK) {
continue;
}
}
/* 有 @TableField 注解的字段初始化 */
if (initTableFieldWithAnnotation(dbConfig, tableInfo, fieldList, field, clazz)) {
continue;
}
/* 无 @TableField 注解的字段初始化 */
fieldList.add(new TableFieldInfo(dbConfig, tableInfo, field));
}
/* 检查逻辑删除字段只能有最多一个 */
Assert.isTrue(fieldList.parallelStream().filter(TableFieldInfo::isLogicDelete).count() < 2L,
String.format("annotation of @TableLogic can't more than one in class : %s.", clazz.getName()));
/* 字段列表 */
tableInfo.setFieldList(fieldList);
/* 未发现主键注解,提示警告信息 */
if (StringUtils.isEmpty(tableInfo.getKeyColumn())) {
logger.warn(String.format("Warn: Could not find @TableId in Class: %s.", clazz.getName()));
}
}
/**
* <p>
* 判断主键注解是否存在
* </p>
*
* @param list 字段列表
* @return true 为存在 @TableId 注解;
*/
public static boolean isExistTableId(List<Field> list) {
for (Field field : list) {
TableId tableId = field.getAnnotation(TableId.class);
if (tableId != null) {
return true;
}
}
return false;
}
/**
* <p>
* 主键属性初始化
* </p>
*
* @param dbConfig 全局配置信息
* @param tableInfo 表信息
* @param field 字段
* @param clazz 实体类
* @return true 继续下一个属性判断,返回 continue;
*/
private static boolean initTableIdWithAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
Field field, Class<?> clazz) {
TableId tableId = field.getAnnotation(TableId.class);
boolean underCamel = tableInfo.isUnderCamel();
if (tableId != null) {
if (StringUtils.isEmpty(tableInfo.getKeyColumn())) {
/* 主键策略( 注解 > 全局 ) */
// 设置 Sequence 其他策略无效
if (IdType.NONE == tableId.type()) {
tableInfo.setIdType(dbConfig.getIdType());
} else {
tableInfo.setIdType(tableId.type());
}
/* 字段 */
String column = field.getName();
if (StringUtils.isNotEmpty(tableId.value())) {
column = tableId.value();
} else {
// 开启字段下划线申明
if (underCamel) {
column = StringUtils.camelToUnderline(column);
}
// 全局大写命名
if (dbConfig.isCapitalMode()) {
column = column.toUpperCase();
}
}
tableInfo.setKeyRelated(checkRelated(underCamel, field.getName(), column))
.setKeyColumn(column)
.setKeyProperty(field.getName())
.setKeyType(field.getType());
return true;
} else {
throwExceptionId(clazz);
}
}
return false;
}
/**
* <p>
* 主键属性初始化
* </p>
*
* @param tableInfo 表信息
* @param field 字段
* @param clazz 实体类
* @return true 继续下一个属性判断,返回 continue;
*/
private static boolean initTableIdWithoutAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
Field field, Class<?> clazz) {
String column = field.getName();
if (dbConfig.isCapitalMode()) {
column = column.toUpperCase();
}
if (DEFAULT_ID_NAME.equalsIgnoreCase(column)) {
if (StringUtils.isEmpty(tableInfo.getKeyColumn())) {
tableInfo.setKeyRelated(checkRelated(tableInfo.isUnderCamel(), field.getName(), column))
.setIdType(dbConfig.getIdType())
.setKeyColumn(column)
.setKeyProperty(field.getName())
.setKeyType(field.getType());
return true;
} else {
throwExceptionId(clazz);
}
}
return false;
}
/**
* <p>
* 字段属性初始化
* </p>
*
* @param dbConfig 数据库全局配置
* @param tableInfo 表信息
* @param fieldList 字段列表
* @param clazz 当前表对象类
* @return true 继续下一个属性判断,返回 continue;
*/
private static boolean initTableFieldWithAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
List<TableFieldInfo> fieldList, Field field, Class<?> clazz) {
/* 获取注解属性,自定义字段 */
TableField tableField = field.getAnnotation(TableField.class);
if (null == tableField) {
return false;
}
String columnName = field.getName();
boolean columnNameFromTableField = false;
if (StringUtils.isNotEmpty(tableField.value())) {
columnName = tableField.value();
columnNameFromTableField = true;
}
/*
* el 语法支持,可以传入多个参数以逗号分开
*/
String el = field.getName();
if (StringUtils.isNotEmpty(tableField.el())) {
el = tableField.el();
}
String[] columns = columnName.split(StringPool.SEMICOLON);
String columnFormat = dbConfig.getColumnFormat();
if (StringUtils.isNotEmpty(columnFormat) && (!columnNameFromTableField || tableField.keepGlobalFormat())) {
for (int i = 0; i < columns.length; i++) {
String column = columns[i];
column = String.format(columnFormat, column);
columns[i] = column;
}
}
String[] els = el.split(StringPool.SEMICOLON);
if (columns.length == els.length) {
for (int i = 0; i < columns.length; i++) {
fieldList.add(new TableFieldInfo(dbConfig, tableInfo, field, columns[i], els[i], tableField));
}
return true;
}
throw ExceptionUtils.mpe("Class: %s, Field: %s, 'value' 'el' Length must be consistent.",
clazz.getName(), field.getName());
}
/**
* <p>
* 判定 related 的值
* </p>
*
* @param underCamel 驼峰命名
* @param property 属性名
* @param column 字段名
* @return related
*/
public static boolean checkRelated(boolean underCamel, String property, String column) {
if (StringUtils.isNotColumnName(column)) {
// 首尾有转义符,手动在注解里设置了转义符,去除掉转义符
column = column.substring(1, column.length() - 1);
}
String propertyUpper = property.toUpperCase(Locale.ENGLISH);
String columnUpper = column.toUpperCase(Locale.ENGLISH);
if (underCamel) {
// 开启了驼峰并且 column 包含下划线
return !(propertyUpper.equals(columnUpper) ||
propertyUpper.equals(columnUpper.replace(StringPool.UNDERSCORE, StringPool.EMPTY)));
} else {
// 未开启驼峰,直接判断 property 是否与 column 相同(全大写)
return !propertyUpper.equals(columnUpper);
}
}
/**
* 发现设置多个主键注解抛出异常
*/
private static void throwExceptionId(Class<?> clazz) {
throw ExceptionUtils.mpe("There must be only one, Discover multiple @TableId annotation in %s", clazz.getName());
}
/**
* <p>
* 获取该类的所有属性列表
* </p>
*
* @param clazz 反射类
* @return 属性集合
*/
public static List<Field> getAllFields(Class<?> clazz) {
List<Field> fieldList = ReflectionKit.getFieldList(ClassUtils.getUserClass(clazz));
if (CollectionUtils.isNotEmpty(fieldList)) {
return fieldList.stream()
.filter(i -> {
/* 过滤注解非表字段属性 */
TableField tableField = i.getAnnotation(TableField.class);
return (tableField == null || tableField.exist());
}).collect(toList());
}
return fieldList;
}
/**
* 自定义 KEY 生成器
*/
public static KeyGenerator genKeyGenerator(TableInfo tableInfo, MapperBuilderAssistant builderAssistant,
String baseStatementId, LanguageDriver languageDriver) {
IKeyGenerator keyGenerator = GlobalConfigUtils.getKeyGenerator(builderAssistant.getConfiguration());
if (null == keyGenerator) {
throw new IllegalArgumentException("not configure IKeyGenerator implementation class.");
}
String id = baseStatementId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
Class<?> resultTypeClass = tableInfo.getKeySequence().clazz();
StatementType statementType = StatementType.PREPARED;
String keyProperty = tableInfo.getKeyProperty();
String keyColumn = tableInfo.getKeyColumn();
SqlSource sqlSource = languageDriver.createSqlSource(builderAssistant.getConfiguration(),
keyGenerator.executeSql(tableInfo.getKeySequence().value()), null);
builderAssistant.addMappedStatement(id, sqlSource, statementType, SqlCommandType.SELECT, null, null, null,
null, null, resultTypeClass, null, false, false, false,
new NoKeyGenerator(), keyProperty, keyColumn, null, languageDriver, null);
id = builderAssistant.applyCurrentNamespace(id, false);
MappedStatement keyStatement = builderAssistant.getConfiguration().getMappedStatement(id, false);
SelectKeyGenerator selectKeyGenerator = new SelectKeyGenerator(keyStatement, true);
builderAssistant.getConfiguration().addKeyGenerator(id, selectKeyGenerator);
return selectKeyGenerator;
}
}
|
移除苗老板的骚操作(咩咩说的).
|
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/toolkit/TableInfoHelper.java
|
移除苗老板的骚操作(咩咩说的).
|
<ide><path>ybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/toolkit/TableInfoHelper.java
<ide> columnName = tableField.value();
<ide> columnNameFromTableField = true;
<ide> }
<del> /*
<del> * el 语法支持,可以传入多个参数以逗号分开
<del> */
<del> String el = field.getName();
<del> if (StringUtils.isNotEmpty(tableField.el())) {
<del> el = tableField.el();
<del> }
<del> String[] columns = columnName.split(StringPool.SEMICOLON);
<del>
<add> String el = StringUtils.isNotEmpty(tableField.el()) ? tableField.el() : field.getName();
<ide> String columnFormat = dbConfig.getColumnFormat();
<ide> if (StringUtils.isNotEmpty(columnFormat) && (!columnNameFromTableField || tableField.keepGlobalFormat())) {
<del> for (int i = 0; i < columns.length; i++) {
<del> String column = columns[i];
<del> column = String.format(columnFormat, column);
<del> columns[i] = column;
<del> }
<del> }
<del>
<del> String[] els = el.split(StringPool.SEMICOLON);
<del> if (columns.length == els.length) {
<del> for (int i = 0; i < columns.length; i++) {
<del> fieldList.add(new TableFieldInfo(dbConfig, tableInfo, field, columns[i], els[i], tableField));
<del> }
<del> return true;
<del> }
<del> throw ExceptionUtils.mpe("Class: %s, Field: %s, 'value' 'el' Length must be consistent.",
<del> clazz.getName(), field.getName());
<add> columnName = String.format(columnFormat, columnName);
<add> }
<add> fieldList.add(new TableFieldInfo(dbConfig, tableInfo, field, columnName, el, tableField));
<add> return true;
<ide> }
<ide>
<ide> /**
|
|
Java
|
apache-2.0
|
a5b9fbb5c330282c22c97e8ea4b93189775e41e2
| 0 |
aloubyansky/pm
|
/*
* Copyright 2016-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.provisioning.plugin.wildfly;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jboss.provisioning.ArtifactCoords;
import org.jboss.provisioning.Constants;
import org.jboss.provisioning.Errors;
import org.jboss.provisioning.MessageWriter;
import org.jboss.provisioning.ProvisioningDescriptionException;
import org.jboss.provisioning.ProvisioningException;
import org.jboss.provisioning.plugin.ProvisionedConfigHandler;
import org.jboss.provisioning.runtime.ProvisioningRuntime;
import org.jboss.provisioning.runtime.ResolvedFeatureSpec;
import org.jboss.provisioning.spec.FeatureAnnotation;
import org.jboss.provisioning.state.ProvisionedConfig;
import org.jboss.provisioning.state.ProvisionedFeature;
import org.jboss.provisioning.util.IoUtils;
/**
*
* @author Alexey Loubyansky
*/
class WfProvisionedConfigHandler implements ProvisionedConfigHandler {
private static final int OP = 0;
private static final int WRITE_ATTR = 1;
private static final int LIST_ADD = 2;
private static final String TMP_DOMAIN_XML = "pm-tmp-domain.xml";
private static final String TMP_HOST_XML = "pm-tmp-host.xml";
private interface NameFilter {
boolean accepts(String name);
}
private class ManagedOp {
String line;
String addrPref;
String name;
List<String> addrParams = Collections.emptyList();
List<String> opParams = Collections.emptyList();
int op;
void reset() {
line = null;
addrPref = null;
name = null;
addrParams = Collections.emptyList();
opParams = Collections.emptyList();
op = OP;
}
String toCommandLine(ProvisionedFeature feature) throws ProvisioningDescriptionException {
final String line;
if (this.line != null) {
line = this.line;
} else {
final StringBuilder buf = new StringBuilder();
if (addrPref != null) {
buf.append(addrPref);
}
int i = 0;
while(i < addrParams.size()) {
final String value = feature.getParam(addrParams.get(i++));
if (value == null) {
continue;
}
buf.append('/').append(addrParams.get(i++)).append('=').append(value);
}
buf.append(':').append(name);
switch(op) {
case OP: {
if (!opParams.isEmpty()) {
boolean comma = false;
i = 0;
while(i < opParams.size()) {
final String value = feature.getParam(opParams.get(i++));
if (value == null) {
continue;
}
if (comma) {
buf.append(',');
} else {
comma = true;
buf.append('(');
}
buf.append(opParams.get(i++)).append('=');
if(value.trim().isEmpty()) {
buf.append('\"').append(value).append('\"');
} else {
buf.append(value);
}
}
if (comma) {
buf.append(')');
}
}
break;
}
case WRITE_ATTR: {
final String value = feature.getParam(opParams.get(0));
if (value == null) {
throw new ProvisioningDescriptionException(opParams.get(0) + " parameter is null: " + feature);
}
buf.append("(name=").append(opParams.get(1)).append(",value=").append(value).append(')');
break;
}
case LIST_ADD: {
final String value = feature.getParam(opParams.get(0));
if (value == null) {
throw new ProvisioningDescriptionException(opParams.get(0) + " parameter is null: " + feature);
}
buf.append("(name=").append(opParams.get(1)).append(",value=").append(value).append(')');
break;
}
default:
}
line = buf.toString();
}
return line;
}
}
private final ProvisioningRuntime runtime;
private final MessageWriter messageWriter;
private int opsTotal;
private ManagedOp[] ops = new ManagedOp[]{new ManagedOp()};
private NameFilter paramFilter;
private Path script;
private String tmpConfig;
private BufferedWriter opsWriter;
WfProvisionedConfigHandler(ProvisioningRuntime runtime) {
this.runtime = runtime;
this.messageWriter = runtime.getMessageWriter();
}
private void initOpsWriter(String name, String op) throws ProvisioningException {
script = runtime.getTmpPath("cli", name);
try {
Files.createDirectories(script.getParent());
opsWriter = Files.newBufferedWriter(script);
writeOp(op);
} catch (IOException e) {
throw new ProvisioningException(Errors.openFile(script));
}
}
private void writeOp(String op) throws ProvisioningException {
try {
opsWriter.write(op);
opsWriter.newLine();
} catch (IOException e) {
throw new ProvisioningException("Failed to write operation to a file", e);
}
}
@Override
public void prepare(ProvisionedConfig config) throws ProvisioningException {
final String logFile;
if("standalone".equals(config.getModel())) {
logFile = config.getProperties().get("config-name");
if(logFile == null) {
throw new ProvisioningException("Config " + config.getName() + " of model " + config.getModel() + " is missing property config-name");
}
final StringBuilder buf = new StringBuilder();
buf.append("embed-server --admin-only=true --empty-config --remove-existing --server-config=")
.append(logFile).append(" --jboss-home=").append(runtime.getStagedDir());
initOpsWriter(logFile, buf.toString());
paramFilter = new NameFilter() {
@Override
public boolean accepts(String name) {
return !("profile".equals(name) || "host".equals(name));
}
};
} else {
if("domain".equals(config.getModel())) {
logFile = config.getProperties().get("domain-config-name");
if (logFile == null) {
throw new ProvisioningException("Config " + config.getName() + " of model " + config.getModel()
+ " is missing property domain-config-name");
}
tmpConfig = TMP_HOST_XML;
final StringBuilder buf = new StringBuilder();
buf.append("embed-host-controller --empty-host-config --remove-existing-host-config --empty-domain-config --remove-existing-domain-config --host-config=")
.append(TMP_HOST_XML)
.append(" --domain-config=").append(logFile)
.append(" --jboss-home=").append(runtime.getStagedDir());
initOpsWriter(logFile, buf.toString());
paramFilter = new NameFilter() {
@Override
public boolean accepts(String name) {
return !"host".equals(name);
}
};
} else if ("host".equals(config.getModel())) {
logFile = config.getProperties().get("host-config-name");
if (logFile == null) {
throw new ProvisioningException("Config " + config.getName() + " of model " + config.getModel()
+ " is missing property host-config-name");
}
final StringBuilder buf = new StringBuilder();
buf.append("embed-host-controller --empty-host-config --remove-existing-host-config --host-config=")
.append(logFile);
final String domainConfig = config.getProperties().get("domain-config-name");
if (domainConfig == null) {
tmpConfig = TMP_DOMAIN_XML;
buf.append(" --empty-domain-config --remove-existing-domain-config --domain-config=").append(TMP_DOMAIN_XML);
} else {
buf.append(" --domain-config=").append(domainConfig);
}
buf.append(" --jboss-home=").append(runtime.getStagedDir());
initOpsWriter(logFile, buf.toString());
paramFilter = new NameFilter() {
@Override
public boolean accepts(String name) {
return !"profile".equals(name);
}
};
} else {
throw new ProvisioningException("Unsupported config model " + config.getModel());
}
}
}
@Override
public void nextFeaturePack(ArtifactCoords.Gav fpGav) throws ProvisioningException {
messageWriter.print(" " + fpGav);
}
@Override
public void nextSpec(ResolvedFeatureSpec spec) throws ProvisioningException {
messageWriter.print(" SPEC " + spec.getName());
if(!spec.hasAnnotations()) {
opsTotal = 0;
return;
}
final List<FeatureAnnotation> annotations = spec.getAnnotations();
opsTotal = annotations.size();
if(annotations.size() > 1) {
if(ops.length < opsTotal) {
final ManagedOp[] tmp = ops;
ops = new ManagedOp[opsTotal];
System.arraycopy(tmp, 0, ops, 0, tmp.length);
for(int i = tmp.length; i < ops.length; ++i) {
ops[i] = new ManagedOp();
}
}
}
int i = 0;
while (i < opsTotal) {
final FeatureAnnotation annotation = annotations.get(i);
messageWriter.print(" Annotation: " + annotation);
final ManagedOp mop = ops[i++];
mop.reset();
mop.line = annotation.getElem(WfConstants.LINE);
if(mop.line != null) {
continue;
}
mop.name = annotation.getName();
if(mop.name.equals(WfConstants.ADD)) {
mop.op = OP;
} else if(mop.name.equals(WfConstants.WRITE_ATTRIBUTE)) {
mop.op = WRITE_ATTR;
} else if(mop.name.equals(WfConstants.LIST_ADD)) {
mop.op = LIST_ADD;
} else {
mop.op = OP;
}
mop.addrPref = annotation.getElem(WfConstants.ADDR_PREF);
String elemValue = annotation.getElem(WfConstants.SKIP_IF_FILTERED);
final Set<String> skipIfFiltered;
if (elemValue != null) {
skipIfFiltered = parseSet(elemValue);
} else {
skipIfFiltered = Collections.emptySet();
}
final String addrParamMapping = annotation.getElem(WfConstants.ADDR_PARAMS_MAPPING);
elemValue = annotation.getElem(WfConstants.ADDR_PARAMS);
if (elemValue == null) {
throw new ProvisioningException("Required element " + WfConstants.ADDR_PARAMS + " is missing for " + spec.getId());
}
try {
mop.addrParams = parseList(elemValue, paramFilter, skipIfFiltered, addrParamMapping);
} catch (ProvisioningDescriptionException e) {
throw new ProvisioningDescriptionException("Saw an empty parameter name in annotation " + WfConstants.ADDR_PARAMS + "="
+ elemValue + " of " + spec.getId());
}
if(mop.addrParams == null) {
// skip
mop.reset();
--opsTotal;
--i;
continue;
}
final String paramsMapping = annotation.getElem(WfConstants.OP_PARAMS_MAPPING);
elemValue = annotation.getElem(WfConstants.OP_PARAMS, Constants.PM_UNDEFINED);
if (elemValue == null) {
mop.opParams = Collections.emptyList();
} else if (Constants.PM_UNDEFINED.equals(elemValue)) {
if (spec.hasParams()) {
final Set<String> allParams = spec.getParamNames();
final int opParams = allParams.size() - mop.addrParams.size() / 2;
if(opParams == 0) {
mop.opParams = Collections.emptyList();
} else {
mop.opParams = new ArrayList<>(opParams*2);
for (String paramName : allParams) {
boolean inAddr = false;
int j = 0;
while(!inAddr && j < mop.addrParams.size()) {
if(mop.addrParams.get(j).equals(paramName)) {
inAddr = true;
}
j += 2;
}
if (!inAddr) {
if(paramFilter.accepts(paramName)) {
mop.opParams.add(paramName);
mop.opParams.add(paramName);
} else if(skipIfFiltered.contains(paramName)) {
// skip
mop.reset();
--opsTotal;
--i;
continue;
}
}
}
}
} else {
mop.opParams = Collections.emptyList();
}
} else {
try {
mop.opParams = parseList(elemValue, paramFilter, skipIfFiltered, paramsMapping);
} catch (ProvisioningDescriptionException e) {
throw new ProvisioningDescriptionException("Saw empty parameter name in note " + WfConstants.ADDR_PARAMS
+ "=" + elemValue + " of " + spec.getId());
}
}
if(mop.op == WRITE_ATTR && mop.opParams.size() != 2) {
throw new ProvisioningDescriptionException(WfConstants.OP_PARAMS + " element of "
+ WfConstants.WRITE_ATTRIBUTE + " annotation of " + spec.getId()
+ " accepts only one parameter: " + annotation);
}
}
}
@Override
public void nextFeature(ProvisionedFeature feature) throws ProvisioningException {
if (opsTotal == 0) {
messageWriter.print(" " + feature.getParams());
return;
}
for(int i = 0; i < opsTotal; ++i) {
final String line = ops[i].toCommandLine(feature);
messageWriter.print(" " + line);
writeOp(line);
}
}
@Override
public void startBatch() throws ProvisioningException {
messageWriter.print(" START BATCH");
writeOp("batch");
}
@Override
public void endBatch() throws ProvisioningException {
messageWriter.print(" END BATCH");
writeOp("run-batch");
}
@Override
public void done() throws ProvisioningException {
try {
opsWriter.close();
} catch (IOException e) {
throw new ProvisioningException("Failed to close " + script, e);
}
messageWriter.print(" Generating %s configuration", script.getFileName().toString());
CliScriptRunner.runCliScript(runtime.getStagedDir(), script, messageWriter);
if(tmpConfig != null) {
final Path tmpPath = runtime.getStagedDir().resolve("domain").resolve("configuration").resolve(tmpConfig);
if(Files.exists(tmpPath)) {
IoUtils.recursiveDelete(tmpPath);
} else {
messageWriter.error("Expected path does not exist " + tmpPath);
}
tmpConfig = null;
}
}
private static Set<String> parseSet(String str) throws ProvisioningDescriptionException {
if (str.isEmpty()) {
return Collections.emptySet();
}
int comma = str.indexOf(',');
if (comma < 1) {
return Collections.singleton(str.trim());
}
final Set<String> set = new HashSet<>();
int start = 0;
while (comma > 0) {
final String paramName = str.substring(start, comma).trim();
if (paramName.isEmpty()) {
throw new ProvisioningDescriptionException("Saw an empty list item in note '" + str);
}
set.add(paramName);
start = comma + 1;
comma = str.indexOf(',', start);
}
if (start == str.length()) {
throw new ProvisioningDescriptionException("Saw an empty list item in note '" + str);
}
set.add(str.substring(start).trim());
return set;
}
private static List<String> parseList(String str, NameFilter filter, Set<String> skipIfFiltered, String mappingStr) throws ProvisioningDescriptionException {
if (str.isEmpty()) {
return Collections.emptyList();
}
int strComma = str.indexOf(',');
List<String> list = new ArrayList<>();
if (strComma < 1) {
str = str.trim();
final String mapped = mappingStr == null ? str : mappingStr.trim();
if (filter.accepts(str)) {
list.add(str);
list.add(mapped);
} else if(skipIfFiltered.contains(str)) {
return null;
}
return list;
}
int mappingComma = mappingStr == null ? -1 : mappingStr.indexOf(',');
int mappingStart = mappingComma > 0 ? 0 : -1;
int start = 0;
while (strComma > 0) {
final String paramName = str.substring(start, strComma).trim();
if (paramName.isEmpty()) {
throw new ProvisioningDescriptionException("Saw en empty list item in note '" + str + "'");
}
final String mappedName;
if(mappingComma < 0) {
mappedName = paramName;
} else {
mappedName = mappingStr.substring(mappingStart, mappingComma).trim();
if (mappedName.isEmpty()) {
throw new ProvisioningDescriptionException("Saw en empty list item in note '" + mappingStr + "'");
}
}
if (filter.accepts(paramName)) {
list.add(paramName);
list.add(mappedName);
} else if(skipIfFiltered.contains(paramName)) {
return null;
}
start = strComma + 1;
strComma = str.indexOf(',', start);
if(mappingComma > 0) {
mappingStart = mappingComma + 1;
mappingComma = mappingStr.indexOf(',', mappingStart);
}
}
if (start == str.length()) {
throw new ProvisioningDescriptionException("Saw an empty list item in note '" + str);
}
final String paramName = str.substring(start).trim();
final String mappedName = mappingStart < 0 ? paramName : mappingStr.substring(mappingStart).trim();
if(filter.accepts(paramName)) {
list.add(paramName);
list.add(mappedName);
} else if(skipIfFiltered.contains(paramName)) {
return null;
}
return list;
}
}
|
wildfly-provisioning-plugin/src/main/java/org/jboss/provisioning/plugin/wildfly/WfProvisionedConfigHandler.java
|
/*
* Copyright 2016-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.provisioning.plugin.wildfly;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jboss.provisioning.ArtifactCoords;
import org.jboss.provisioning.Constants;
import org.jboss.provisioning.Errors;
import org.jboss.provisioning.MessageWriter;
import org.jboss.provisioning.ProvisioningDescriptionException;
import org.jboss.provisioning.ProvisioningException;
import org.jboss.provisioning.plugin.ProvisionedConfigHandler;
import org.jboss.provisioning.runtime.ProvisioningRuntime;
import org.jboss.provisioning.runtime.ResolvedFeatureSpec;
import org.jboss.provisioning.spec.FeatureAnnotation;
import org.jboss.provisioning.state.ProvisionedConfig;
import org.jboss.provisioning.state.ProvisionedFeature;
import org.jboss.provisioning.util.IoUtils;
/**
*
* @author Alexey Loubyansky
*/
class WfProvisionedConfigHandler implements ProvisionedConfigHandler {
private static final int OP = 0;
private static final int WRITE_ATTR = 1;
private static final int LIST_ADD = 2;
private static final String TMP_DOMAIN_XML = "pm-tmp-domain.xml";
private static final String TMP_HOST_XML = "pm-tmp-host.xml";
private interface NameFilter {
boolean accepts(String name);
}
private class ManagedOp {
String line;
String addrPref;
String name;
List<String> addrParams = Collections.emptyList();
List<String> opParams = Collections.emptyList();
int op;
void reset() {
line = null;
addrPref = null;
name = null;
addrParams = Collections.emptyList();
opParams = Collections.emptyList();
op = OP;
}
String toCommandLine(ProvisionedFeature feature) throws ProvisioningDescriptionException {
final String line;
if (this.line != null) {
line = this.line;
} else {
final StringBuilder buf = new StringBuilder();
if (addrPref != null) {
buf.append(addrPref);
}
int i = 0;
while(i < addrParams.size()) {
final String value = feature.getParam(addrParams.get(i++));
if (value == null) {
continue;
}
buf.append('/').append(addrParams.get(i++)).append('=').append(value);
}
buf.append(':').append(name);
switch(op) {
case OP: {
if (!opParams.isEmpty()) {
boolean comma = false;
i = 0;
while(i < opParams.size()) {
final String value = feature.getParam(opParams.get(i++));
if (value == null) {
continue;
}
if (comma) {
buf.append(',');
} else {
comma = true;
buf.append('(');
}
buf.append(opParams.get(i++)).append('=').append(value);
}
if (comma) {
buf.append(')');
}
}
break;
}
case WRITE_ATTR: {
final String value = feature.getParam(opParams.get(0));
if (value == null) {
throw new ProvisioningDescriptionException(opParams.get(0) + " parameter is null: " + feature);
}
buf.append("(name=").append(opParams.get(1)).append(",value=").append(value).append(')');
break;
}
case LIST_ADD: {
final String value = feature.getParam(opParams.get(0));
if (value == null) {
throw new ProvisioningDescriptionException(opParams.get(0) + " parameter is null: " + feature);
}
buf.append("(name=").append(opParams.get(1)).append(",value=").append(value).append(')');
break;
}
default:
}
line = buf.toString();
}
return line;
}
}
private final ProvisioningRuntime runtime;
private final MessageWriter messageWriter;
private int opsTotal;
private ManagedOp[] ops = new ManagedOp[]{new ManagedOp()};
private NameFilter paramFilter;
private Path script;
private String tmpConfig;
private BufferedWriter opsWriter;
WfProvisionedConfigHandler(ProvisioningRuntime runtime) {
this.runtime = runtime;
this.messageWriter = runtime.getMessageWriter();
}
private void initOpsWriter(String name, String op) throws ProvisioningException {
script = runtime.getTmpPath("cli", name);
try {
Files.createDirectories(script.getParent());
opsWriter = Files.newBufferedWriter(script);
writeOp(op);
} catch (IOException e) {
throw new ProvisioningException(Errors.openFile(script));
}
}
private void writeOp(String op) throws ProvisioningException {
try {
opsWriter.write(op);
opsWriter.newLine();
} catch (IOException e) {
throw new ProvisioningException("Failed to write operation to a file", e);
}
}
@Override
public void prepare(ProvisionedConfig config) throws ProvisioningException {
final String logFile;
if("standalone".equals(config.getModel())) {
logFile = config.getProperties().get("config-name");
if(logFile == null) {
throw new ProvisioningException("Config " + config.getName() + " of model " + config.getModel() + " is missing property config-name");
}
final StringBuilder buf = new StringBuilder();
buf.append("embed-server --admin-only=true --empty-config --remove-existing --server-config=")
.append(logFile).append(" --jboss-home=").append(runtime.getStagedDir());
initOpsWriter(logFile, buf.toString());
paramFilter = new NameFilter() {
@Override
public boolean accepts(String name) {
return !("profile".equals(name) || "host".equals(name));
}
};
} else {
if("domain".equals(config.getModel())) {
logFile = config.getProperties().get("domain-config-name");
if (logFile == null) {
throw new ProvisioningException("Config " + config.getName() + " of model " + config.getModel()
+ " is missing property domain-config-name");
}
tmpConfig = TMP_HOST_XML;
final StringBuilder buf = new StringBuilder();
buf.append("embed-host-controller --empty-host-config --remove-existing-host-config --empty-domain-config --remove-existing-domain-config --host-config=")
.append(TMP_HOST_XML)
.append(" --domain-config=").append(logFile)
.append(" --jboss-home=").append(runtime.getStagedDir());
initOpsWriter(logFile, buf.toString());
paramFilter = new NameFilter() {
@Override
public boolean accepts(String name) {
return !"host".equals(name);
}
};
} else if ("host".equals(config.getModel())) {
logFile = config.getProperties().get("host-config-name");
if (logFile == null) {
throw new ProvisioningException("Config " + config.getName() + " of model " + config.getModel()
+ " is missing property host-config-name");
}
final StringBuilder buf = new StringBuilder();
buf.append("embed-host-controller --empty-host-config --remove-existing-host-config --host-config=")
.append(logFile);
final String domainConfig = config.getProperties().get("domain-config-name");
if (domainConfig == null) {
tmpConfig = TMP_DOMAIN_XML;
buf.append(" --empty-domain-config --remove-existing-domain-config --domain-config=").append(TMP_DOMAIN_XML);
} else {
buf.append(" --domain-config=").append(domainConfig);
}
buf.append(" --jboss-home=").append(runtime.getStagedDir());
initOpsWriter(logFile, buf.toString());
paramFilter = new NameFilter() {
@Override
public boolean accepts(String name) {
return !"profile".equals(name);
}
};
} else {
throw new ProvisioningException("Unsupported config model " + config.getModel());
}
}
}
@Override
public void nextFeaturePack(ArtifactCoords.Gav fpGav) throws ProvisioningException {
messageWriter.print(" " + fpGav);
}
@Override
public void nextSpec(ResolvedFeatureSpec spec) throws ProvisioningException {
messageWriter.print(" SPEC " + spec.getName());
if(!spec.hasAnnotations()) {
opsTotal = 0;
return;
}
final List<FeatureAnnotation> annotations = spec.getAnnotations();
opsTotal = annotations.size();
if(annotations.size() > 1) {
if(ops.length < opsTotal) {
final ManagedOp[] tmp = ops;
ops = new ManagedOp[opsTotal];
System.arraycopy(tmp, 0, ops, 0, tmp.length);
for(int i = tmp.length; i < ops.length; ++i) {
ops[i] = new ManagedOp();
}
}
}
int i = 0;
while (i < opsTotal) {
final FeatureAnnotation annotation = annotations.get(i);
messageWriter.print(" Annotation: " + annotation);
final ManagedOp mop = ops[i++];
mop.reset();
mop.line = annotation.getElem(WfConstants.LINE);
if(mop.line != null) {
continue;
}
mop.name = annotation.getName();
if(mop.name.equals(WfConstants.ADD)) {
mop.op = OP;
} else if(mop.name.equals(WfConstants.WRITE_ATTRIBUTE)) {
mop.op = WRITE_ATTR;
} else if(mop.name.equals(WfConstants.LIST_ADD)) {
mop.op = LIST_ADD;
} else {
mop.op = OP;
}
mop.addrPref = annotation.getElem(WfConstants.ADDR_PREF);
String elemValue = annotation.getElem(WfConstants.SKIP_IF_FILTERED);
final Set<String> skipIfFiltered;
if (elemValue != null) {
skipIfFiltered = parseSet(elemValue);
} else {
skipIfFiltered = Collections.emptySet();
}
final String addrParamMapping = annotation.getElem(WfConstants.ADDR_PARAMS_MAPPING);
elemValue = annotation.getElem(WfConstants.ADDR_PARAMS);
if (elemValue == null) {
throw new ProvisioningException("Required element " + WfConstants.ADDR_PARAMS + " is missing for " + spec.getId());
}
try {
mop.addrParams = parseList(elemValue, paramFilter, skipIfFiltered, addrParamMapping);
} catch (ProvisioningDescriptionException e) {
throw new ProvisioningDescriptionException("Saw an empty parameter name in annotation " + WfConstants.ADDR_PARAMS + "="
+ elemValue + " of " + spec.getId());
}
if(mop.addrParams == null) {
// skip
mop.reset();
--opsTotal;
--i;
continue;
}
final String paramsMapping = annotation.getElem(WfConstants.OP_PARAMS_MAPPING);
elemValue = annotation.getElem(WfConstants.OP_PARAMS, Constants.PM_UNDEFINED);
if (elemValue == null) {
mop.opParams = Collections.emptyList();
} else if (Constants.PM_UNDEFINED.equals(elemValue)) {
if (spec.hasParams()) {
final Set<String> allParams = spec.getParamNames();
final int opParams = allParams.size() - mop.addrParams.size() / 2;
if(opParams == 0) {
mop.opParams = Collections.emptyList();
} else {
mop.opParams = new ArrayList<>(opParams*2);
for (String paramName : allParams) {
boolean inAddr = false;
int j = 0;
while(!inAddr && j < mop.addrParams.size()) {
if(mop.addrParams.get(j).equals(paramName)) {
inAddr = true;
}
j += 2;
}
if (!inAddr) {
if(paramFilter.accepts(paramName)) {
mop.opParams.add(paramName);
mop.opParams.add(paramName);
} else if(skipIfFiltered.contains(paramName)) {
// skip
mop.reset();
--opsTotal;
--i;
continue;
}
}
}
}
} else {
mop.opParams = Collections.emptyList();
}
} else {
try {
mop.opParams = parseList(elemValue, paramFilter, skipIfFiltered, paramsMapping);
} catch (ProvisioningDescriptionException e) {
throw new ProvisioningDescriptionException("Saw empty parameter name in note " + WfConstants.ADDR_PARAMS
+ "=" + elemValue + " of " + spec.getId());
}
}
if(mop.op == WRITE_ATTR && mop.opParams.size() != 2) {
throw new ProvisioningDescriptionException(WfConstants.OP_PARAMS + " element of "
+ WfConstants.WRITE_ATTRIBUTE + " annotation of " + spec.getId()
+ " accepts only one parameter: " + annotation);
}
}
}
@Override
public void nextFeature(ProvisionedFeature feature) throws ProvisioningException {
if (opsTotal == 0) {
messageWriter.print(" " + feature.getParams());
return;
}
for(int i = 0; i < opsTotal; ++i) {
final String line = ops[i].toCommandLine(feature);
messageWriter.print(" " + line);
writeOp(line);
}
}
@Override
public void startBatch() throws ProvisioningException {
messageWriter.print(" START BATCH");
writeOp("batch");
}
@Override
public void endBatch() throws ProvisioningException {
messageWriter.print(" END BATCH");
writeOp("run-batch");
}
@Override
public void done() throws ProvisioningException {
try {
opsWriter.close();
} catch (IOException e) {
throw new ProvisioningException("Failed to close " + script, e);
}
messageWriter.print(" Generating %s configuration", script.getFileName().toString());
CliScriptRunner.runCliScript(runtime.getStagedDir(), script, messageWriter);
if(tmpConfig != null) {
final Path tmpPath = runtime.getStagedDir().resolve("domain").resolve("configuration").resolve(tmpConfig);
if(Files.exists(tmpPath)) {
IoUtils.recursiveDelete(tmpPath);
} else {
messageWriter.error("Expected path does not exist " + tmpPath);
}
tmpConfig = null;
}
}
private static Set<String> parseSet(String str) throws ProvisioningDescriptionException {
if (str.isEmpty()) {
return Collections.emptySet();
}
int comma = str.indexOf(',');
if (comma < 1) {
return Collections.singleton(str.trim());
}
final Set<String> set = new HashSet<>();
int start = 0;
while (comma > 0) {
final String paramName = str.substring(start, comma).trim();
if (paramName.isEmpty()) {
throw new ProvisioningDescriptionException("Saw an empty list item in note '" + str);
}
set.add(paramName);
start = comma + 1;
comma = str.indexOf(',', start);
}
if (start == str.length()) {
throw new ProvisioningDescriptionException("Saw an empty list item in note '" + str);
}
set.add(str.substring(start).trim());
return set;
}
private static List<String> parseList(String str, NameFilter filter, Set<String> skipIfFiltered, String mappingStr) throws ProvisioningDescriptionException {
if (str.isEmpty()) {
return Collections.emptyList();
}
int strComma = str.indexOf(',');
List<String> list = new ArrayList<>();
if (strComma < 1) {
str = str.trim();
final String mapped = mappingStr == null ? str : mappingStr.trim();
if (filter.accepts(str)) {
list.add(str);
list.add(mapped);
} else if(skipIfFiltered.contains(str)) {
return null;
}
return list;
}
int mappingComma = mappingStr == null ? -1 : mappingStr.indexOf(',');
int mappingStart = mappingComma > 0 ? 0 : -1;
int start = 0;
while (strComma > 0) {
final String paramName = str.substring(start, strComma).trim();
if (paramName.isEmpty()) {
throw new ProvisioningDescriptionException("Saw en empty list item in note '" + str + "'");
}
final String mappedName;
if(mappingComma < 0) {
mappedName = paramName;
} else {
mappedName = mappingStr.substring(mappingStart, mappingComma).trim();
if (mappedName.isEmpty()) {
throw new ProvisioningDescriptionException("Saw en empty list item in note '" + mappingStr + "'");
}
}
if (filter.accepts(paramName)) {
list.add(paramName);
list.add(mappedName);
} else if(skipIfFiltered.contains(paramName)) {
return null;
}
start = strComma + 1;
strComma = str.indexOf(',', start);
if(mappingComma > 0) {
mappingStart = mappingComma + 1;
mappingComma = mappingStr.indexOf(',', mappingStart);
}
}
if (start == str.length()) {
throw new ProvisioningDescriptionException("Saw an empty list item in note '" + str);
}
final String paramName = str.substring(start).trim();
final String mappedName = mappingStart < 0 ? paramName : mappingStr.substring(mappingStart).trim();
if(filter.accepts(paramName)) {
list.add(paramName);
list.add(mappedName);
} else if(skipIfFiltered.contains(paramName)) {
return null;
}
return list;
}
}
|
WF provisioning: quote an empty string parameter argument for the cli
|
wildfly-provisioning-plugin/src/main/java/org/jboss/provisioning/plugin/wildfly/WfProvisionedConfigHandler.java
|
WF provisioning: quote an empty string parameter argument for the cli
|
<ide><path>ildfly-provisioning-plugin/src/main/java/org/jboss/provisioning/plugin/wildfly/WfProvisionedConfigHandler.java
<ide> comma = true;
<ide> buf.append('(');
<ide> }
<del> buf.append(opParams.get(i++)).append('=').append(value);
<add> buf.append(opParams.get(i++)).append('=');
<add> if(value.trim().isEmpty()) {
<add> buf.append('\"').append(value).append('\"');
<add> } else {
<add> buf.append(value);
<add> }
<ide> }
<ide> if (comma) {
<ide> buf.append(')');
|
|
Java
|
mit
|
058d68b94be06f8e6dfe0352f38f4d0967110ba5
| 0 |
ewanld/stream4j
|
package com.github.stream4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TestStream {
private static final List<Integer> emptyList = Collections.<Integer> emptyList();
private static final Predicate<Integer> gt2 = new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return t > 2;
}
};
public void testAll() {
allMatch();
anyMatch();
count();
filter();
findAny();
findFirst();
flatMap();
forEach();
groupBy();
limit();
map();
max();
min();
noneMatch();
partitionBy();
skip();
sorted();
sorted_withComparator();
toList();
toMap();
toSortedMap();
}
private void allMatch() {
assert Stream.of(emptyList).allMatch(gt2);
assert Stream.of(emptyList.iterator()).allMatch(gt2);
assert !Stream.of(1, 2, 3).allMatch(gt2);
assert !Stream.of(0, 1).allMatch(gt2);
assert Stream.of(3, 4, 5).allMatch(gt2);
}
private void anyMatch() {
assert !Stream.of(emptyList).anyMatch(gt2);
assert !Stream.of(emptyList.iterator()).anyMatch(gt2);
assert Stream.of(1, 2, 3).anyMatch(gt2);
assert !Stream.of(0, 1).anyMatch(gt2);
assert Stream.of(3, 4, 5).anyMatch(gt2);
}
private void count() {
assert Stream.of(emptyList).count() == 0;
assert Stream.of(emptyList.iterator()).count() == 0;
assert Stream.of(1, 2, 3).count() == 3;
assert Stream.of(1, 2, 3).count() == 3;
}
private void filter() {
assert Stream.of(emptyList).filter(gt2).count() == 0;
assert Stream.of(emptyList.iterator()).filter(gt2).count() == 0;
assert Stream.of(1, 2, 3).filter(gt2).toList().equals(Arrays.asList(3));
}
private void findAny() {
assert Stream.of(emptyList).findAny() == null;
assert Stream.of(1, 2, 3).findAny() == 1;
}
private void findFirst() {
assert Stream.of(emptyList).findFirst() == null;
assert Stream.of(1, 2, 3).findFirst() == 1;
}
private static class Employee {
private final Set<String> roles;
public Employee(String... roles) {
this.roles = new HashSet<String>(Arrays.asList(roles));
}
public Set<String> getRoles() {
return roles;
}
}
/**
* Returns a stream representing the roles of the employees, or null if the employee has no roles.
*/
private static final Function<Employee, Stream<String>> getRoles = new Function<Employee, Stream<String>>() {
@Override
public Stream<String> apply(Employee t) {
final Set<String> roles = t.getRoles();
return roles.size() == 0 ? null : Stream.of(roles);
}
};
private void flatMap() {
final List<Employee> noEmployees = Collections.<Employee> emptyList();
final List<String> noRoles = Collections.<String> emptyList();
assert Stream.of(noEmployees).flatMap(getRoles).toList().equals(noRoles);
final List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee("role1", "role2"));
employees.add(new Employee());
employees.add(new Employee());
employees.add(new Employee());
employees.add(new Employee("role3"));
employees.add(new Employee());
final Set<String> actual = new HashSet<String>(Stream.of(employees).flatMap(getRoles).toList());
final HashSet<String> expected = new HashSet<String>(Arrays.asList("role1", "role2", "role3"));
assert actual.equals(expected);
}
private static class Add extends Consumer<Integer> {
private final List<Integer> list;
public Add(List<Integer> list) {
this.list = list;
}
@Override
public void accept(Integer t) {
list.add(t);
}
}
private void forEach() {
{
final List<Integer> l = new ArrayList<Integer>();
final Add add = new Add(l);
Stream.of(emptyList).forEach(add);
assert l.equals(emptyList);
}
{
final List<Integer> l = new ArrayList<Integer>();
final Add add = new Add(l);
final List<Integer> expected = Arrays.asList(1, 2, 3);
Stream.of(expected).forEach(add);
assert l.equals(expected);
}
}
private static final Function<String, Character> firstChar = new Function<String, Character>() {
@Override
public Character apply(String t) {
return t.charAt(0);
}
};
private void groupBy() {
{
final Map<Character, List<String>> actual = Stream.of(Collections.<String> emptyList())
.groupBy(firstChar);
assert actual.equals(Collections.<String, Character> emptyMap());
}
{
final Map<Character, List<String>> actual = Stream.of("ab", "ac", "bb").groupBy(firstChar);
final Map<Character, List<String>> expected = new HashMap<Character, List<String>>();
expected.put('a', Arrays.asList("ab", "ac"));
expected.put('b', Arrays.asList("bb"));
assert actual.equals(expected);
}
}
private void limit() {
//TODO
}
private void map() {
//TODO
}
private void max() {
//TODO
}
private void min() {
//TODO
}
private void noneMatch() {
assert Stream.of(emptyList).noneMatch(gt2);
assert Stream.of(emptyList.iterator()).noneMatch(gt2);
assert !Stream.of(1, 2, 3).noneMatch(gt2);
assert Stream.of(0, 1).noneMatch(gt2);
assert !Stream.of(3, 4, 5).noneMatch(gt2);
}
private void partitionBy() {
//TODO
}
private void skip() {
//TODO
}
private void sorted() {
//TODO
}
private void sorted_withComparator() {
//TODO
}
private void toList() {
//TODO
}
private void toMap() {
//TODO
}
private void toSortedMap() {
//TODO
}
}
|
test/com/github/stream4j/TestStream.java
|
package com.github.stream4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TestStream {
private static final List<Integer> emptyList = Collections.<Integer> emptyList();
private static final Predicate<Integer> gt2 = new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return t > 2;
}
};
public void testAll() {
allMatch();
anyMatch();
count();
filter();
findAny();
findFirst();
flatMap();
forEach();
groupBy();
limit();
map();
max();
min();
noneMatch();
partitionBy();
skip();
sorted();
sorted_withComparator();
toList();
toMap();
toSortedMap();
}
private void allMatch() {
assert Stream.of(emptyList).allMatch(gt2);
assert Stream.of(emptyList.iterator()).allMatch(gt2);
assert !Stream.of(1, 2, 3).allMatch(gt2);
assert !Stream.of(0, 1).allMatch(gt2);
assert Stream.of(3, 4, 5).allMatch(gt2);
}
private void anyMatch() {
assert !Stream.of(emptyList).anyMatch(gt2);
assert !Stream.of(emptyList.iterator()).anyMatch(gt2);
assert Stream.of(1, 2, 3).anyMatch(gt2);
assert !Stream.of(0, 1).anyMatch(gt2);
assert Stream.of(3, 4, 5).anyMatch(gt2);
}
private void count() {
assert Stream.of(emptyList).count() == 0;
assert Stream.of(emptyList.iterator()).count() == 0;
assert Stream.of(1, 2, 3).count() == 3;
assert Stream.of(1, 2, 3).count() == 3;
}
private void filter() {
assert Stream.of(emptyList).filter(gt2).count() == 0;
assert Stream.of(emptyList.iterator()).filter(gt2).count() == 0;
assert Stream.of(1, 2, 3).filter(gt2).toList().equals(Arrays.asList(3));
}
private void findAny() {
assert Stream.of(emptyList).findAny() == null;
assert Stream.of(1, 2, 3).findAny() == 1;
}
private void findFirst() {
assert Stream.of(emptyList).findFirst() == null;
assert Stream.of(1, 2, 3).findFirst() == 1;
}
private static class Employee {
private final Set<String> roles;
public Employee(String... roles) {
this.roles = new HashSet<String>(Arrays.asList(roles));
}
public Set<String> getRoles() {
return roles;
}
}
/**
* Returns a stream representing the roles of the employees, or null if the employee has no roles.
*/
private static final Function<Employee, Stream<String>> getRoles = new Function<Employee, Stream<String>>() {
@Override
public Stream<String> apply(Employee t) {
final Set<String> roles = t.getRoles();
return roles.size() == 0 ? null : Stream.of(roles);
}
};
private void flatMap() {
final List<Employee> noEmployees = Collections.<Employee> emptyList();
final List<String> noRoles = Collections.<String> emptyList();
assert Stream.of(noEmployees).flatMap(getRoles).toList().equals(noRoles);
final Employee emp1 = new Employee("role1", "role2");
final Employee emp2 = new Employee("role3");
final Employee emp3 = new Employee();
final Set<String> actual = new HashSet<String>(Stream.of(emp1, emp2, emp3).flatMap(getRoles).toList());
final HashSet<String> expected = new HashSet<String>(Arrays.asList("role1", "role2", "role3"));
assert actual.equals(expected);
}
private static class Add extends Consumer<Integer> {
private final List<Integer> list;
public Add(List<Integer> list) {
this.list = list;
}
@Override
public void accept(Integer t) {
list.add(t);
}
}
private void forEach() {
{
final List<Integer> l = new ArrayList<Integer>();
final Add add = new Add(l);
Stream.of(emptyList).forEach(add);
assert l.equals(emptyList);
}
{
final List<Integer> l = new ArrayList<Integer>();
final Add add = new Add(l);
final List<Integer> expected = Arrays.asList(1, 2, 3);
Stream.of(expected).forEach(add);
assert l.equals(expected);
}
}
private static final Function<String, Character> firstChar = new Function<String, Character>() {
@Override
public Character apply(String t) {
return t.charAt(0);
}
};
private void groupBy() {
{
final Map<Character, List<String>> actual = Stream.of(Collections.<String> emptyList())
.groupBy(firstChar);
assert actual.equals(Collections.<String, Character> emptyMap());
}
{
final Map<Character, List<String>> actual = Stream.of("ab", "ac", "bb").groupBy(firstChar);
final Map<Character, List<String>> expected = new HashMap<Character, List<String>>();
expected.put('a', Arrays.asList("ab", "ac"));
expected.put('b', Arrays.asList("bb"));
assert actual.equals(expected);
}
}
private void limit() {
//TODO
}
private void map() {
//TODO
}
private void max() {
//TODO
}
private void min() {
//TODO
}
private void noneMatch() {
assert Stream.of(emptyList).noneMatch(gt2);
assert Stream.of(emptyList.iterator()).noneMatch(gt2);
assert !Stream.of(1, 2, 3).noneMatch(gt2);
assert Stream.of(0, 1).noneMatch(gt2);
assert !Stream.of(3, 4, 5).noneMatch(gt2);
}
private void partitionBy() {
//TODO
}
private void skip() {
//TODO
}
private void sorted() {
//TODO
}
private void sorted_withComparator() {
//TODO
}
private void toList() {
//TODO
}
private void toMap() {
//TODO
}
private void toSortedMap() {
//TODO
}
}
|
improve tests
|
test/com/github/stream4j/TestStream.java
|
improve tests
|
<ide><path>est/com/github/stream4j/TestStream.java
<ide> final List<String> noRoles = Collections.<String> emptyList();
<ide> assert Stream.of(noEmployees).flatMap(getRoles).toList().equals(noRoles);
<ide>
<del> final Employee emp1 = new Employee("role1", "role2");
<del> final Employee emp2 = new Employee("role3");
<del> final Employee emp3 = new Employee();
<del> final Set<String> actual = new HashSet<String>(Stream.of(emp1, emp2, emp3).flatMap(getRoles).toList());
<add> final List<Employee> employees = new ArrayList<Employee>();
<add> employees.add(new Employee("role1", "role2"));
<add> employees.add(new Employee());
<add> employees.add(new Employee());
<add> employees.add(new Employee());
<add> employees.add(new Employee("role3"));
<add> employees.add(new Employee());
<add> final Set<String> actual = new HashSet<String>(Stream.of(employees).flatMap(getRoles).toList());
<ide> final HashSet<String> expected = new HashSet<String>(Arrays.asList("role1", "role2", "role3"));
<ide> assert actual.equals(expected);
<ide>
|
|
Java
|
apache-2.0
|
0465bdd7694d54612e0a0f21f9289f2112477e3d
| 0 |
google/caliper
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.caliper.runner;
import static java.util.logging.Level.WARNING;
import com.google.caliper.api.ResultProcessor;
import com.google.caliper.api.SkipThisScenarioException;
import com.google.caliper.options.CaliperOptions;
import com.google.caliper.util.Stdout;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.FutureFallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.inject.CreationException;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.ProvisionException;
import com.google.inject.spi.Message;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Provider;
/**
* An execution of each {@link Experiment} for the configured number of trials.
*/
@VisibleForTesting
public final class ExperimentingCaliperRun implements CaliperRun {
private static final Logger logger = Logger.getLogger(ExperimentingCaliperRun.class.getName());
private static final FutureFallback<Object> FALLBACK_TO_NULL = new FutureFallback<Object>() {
final ListenableFuture<Object> nullFuture = Futures.immediateFuture(null);
@Override public ListenableFuture<Object> create(Throwable t) throws Exception {
return nullFuture;
}
};
private final Injector injector;
private final CaliperOptions options;
private final PrintWriter stdout;
private final BenchmarkClass benchmarkClass;
private final ImmutableSet<Instrument> instruments;
private final ImmutableSet<ResultProcessor> resultProcessors;
private final ExperimentSelector selector;
private final Provider<ScheduledTrial> scheduledTrial;
private final Provider<ListeningExecutorService> executorProvider;
@Inject @VisibleForTesting
public ExperimentingCaliperRun(
Injector injector,
CaliperOptions options,
@Stdout PrintWriter stdout,
BenchmarkClass benchmarkClass,
ImmutableSet<Instrument> instruments,
ImmutableSet<ResultProcessor> resultProcessors,
ExperimentSelector selector,
Provider<ScheduledTrial> scheduledTrial,
Provider<ListeningExecutorService> executorProvider) {
this.injector = injector;
this.options = options;
this.stdout = stdout;
this.benchmarkClass = benchmarkClass;
this.instruments = instruments;
this.resultProcessors = resultProcessors;
this.scheduledTrial = scheduledTrial;
this.selector = selector;
this.executorProvider = executorProvider;
}
@Override
public void run() throws InvalidBenchmarkException {
ImmutableSet<Experiment> allExperiments = selector.selectExperiments();
// TODO(lukes): move this standard-out handling into the ConsoleOutput class?
stdout.println("Experiment selection: ");
stdout.println(" Benchmark Methods: " + FluentIterable.from(allExperiments)
.transform(new Function<Experiment, String>() {
@Override public String apply(Experiment experiment) {
return experiment.instrumentation().benchmarkMethod().getName();
}
}).toSet());
stdout.println(" Instruments: " + FluentIterable.from(selector.instruments())
.transform(new Function<Instrument, String>() {
@Override public String apply(Instrument instrument) {
return instrument.name();
}
}));
stdout.println(" User parameters: " + selector.userParameters());
stdout.println(" Virtual machines: " + FluentIterable.from(selector.vms())
.transform(
new Function<VirtualMachine, String>() {
@Override public String apply(VirtualMachine vm) {
return vm.name;
}
}));
stdout.println(" Selection type: " + selector.selectionType());
stdout.println();
if (allExperiments.isEmpty()) {
throw new InvalidBenchmarkException(
"There were no experiments to be performed for the class %s using the instruments %s",
benchmarkClass.benchmarkClass().getSimpleName(), instruments);
}
stdout.format("This selection yields %s experiments.%n", allExperiments.size());
stdout.flush();
// always dry run first.
ImmutableSet<Experiment> experimentsToRun = dryRun(allExperiments);
if (experimentsToRun.size() != allExperiments.size()) {
stdout.format("%d experiments were skipped.%n",
allExperiments.size() - experimentsToRun.size());
}
if (experimentsToRun.isEmpty()) {
throw new InvalidBenchmarkException("All experiments were skipped.");
}
if (options.dryRun()) {
return;
}
stdout.flush();
int totalTrials = experimentsToRun.size() * options.trialsPerScenario();
Stopwatch stopwatch = Stopwatch.createStarted();
List<ScheduledTrial> trials = createScheduledTrials(experimentsToRun, totalTrials);
final ListeningExecutorService executor = executorProvider.get();
List<ListenableFuture<TrialResult>> pendingTrials = scheduleTrials(trials, executor);
ConsoleOutput output = new ConsoleOutput(stdout, totalTrials, stopwatch);
try {
// Process results as they complete.
for (ListenableFuture<TrialResult> trialFuture : inCompletionOrder(pendingTrials)) {
try {
TrialResult result = trialFuture.get();
output.processTrial(result);
for (ResultProcessor resultProcessor : resultProcessors) {
resultProcessor.processTrial(result.getTrial());
}
} catch (ExecutionException e) {
if (e.getCause() instanceof TrialFailureException) {
output.processFailedTrial((TrialFailureException) e.getCause());
} else {
for (ListenableFuture<?> toCancel : pendingTrials) {
toCancel.cancel(true);
}
throw Throwables.propagate(e.getCause());
}
} catch (InterruptedException e) {
// be responsive to interruption, cancel outstanding work and exit
for (ListenableFuture<?> toCancel : pendingTrials) {
// N.B. TrialRunLoop is responsive to interruption.
toCancel.cancel(true);
}
throw new RuntimeException(e);
}
}
} finally {
executor.shutdown();
output.close();
}
for (ResultProcessor resultProcessor : resultProcessors) {
try {
resultProcessor.close();
} catch (IOException e) {
logger.log(WARNING, "Could not close a result processor: " + resultProcessor, e);
}
}
}
/**
* Schedule all the trials.
*
* <p>This method arranges all the {@link ScheduledTrial trials} to run according to their
* scheduling criteria. The executor instance is responsible for enforcing max parallelism.
*/
private List<ListenableFuture<TrialResult>> scheduleTrials(List<ScheduledTrial> trials,
final ListeningExecutorService executor) {
List<ListenableFuture<TrialResult>> pendingTrials = Lists.newArrayList();
List<ScheduledTrial> serialTrials = Lists.newArrayList();
for (final ScheduledTrial scheduledTrial : trials) {
if (scheduledTrial.policy() == TrialSchedulingPolicy.PARALLEL) {
pendingTrials.add(executor.submit(scheduledTrial.trialTask()));
} else {
serialTrials.add(scheduledTrial);
}
}
// A future representing the completion of all prior tasks. Futures.successfulAsList allows us
// to ignore failure.
ListenableFuture<?> previous = Futures.successfulAsList(pendingTrials);
for (final ScheduledTrial scheduledTrial : serialTrials) {
// each of these trials can only start after all prior trials have finished, so we use
// Futures.transform to force the sequencing.
ListenableFuture<TrialResult> current =
Futures.transform(
previous,
new AsyncFunction<Object, TrialResult>() {
@Override public ListenableFuture<TrialResult> apply(Object ignored) {
return executor.submit(scheduledTrial.trialTask());
}
});
pendingTrials.add(current);
// ignore failure of the prior task.
previous = Futures.withFallback(current, FALLBACK_TO_NULL);
}
return pendingTrials;
}
/** Returns all the ScheduledTrials for this run. */
private List<ScheduledTrial> createScheduledTrials(ImmutableSet<Experiment> experimentsToRun,
int totalTrials) {
List<ScheduledTrial> trials = Lists.newArrayListWithCapacity(totalTrials);
/** This is 1-indexed because it's only used for display to users. E.g. "Trial 1 of 27" */
int trialNumber = 1;
for (int i = 0; i < options.trialsPerScenario(); i++) {
for (Experiment experiment : experimentsToRun) {
try {
trials.add(TrialScopes.makeContext(UUID.randomUUID(), trialNumber, experiment)
.call(new Callable<ScheduledTrial>() {
@Override public ScheduledTrial call() {
return scheduledTrial.get();
}
}));
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
trialNumber++;
}
}
}
return trials;
}
/**
* Attempts to run each given scenario once, in the current VM. Returns a set of all of the
* scenarios that didn't throw a {@link SkipThisScenarioException}.
*/
ImmutableSet<Experiment> dryRun(Iterable<Experiment> experiments)
throws InvalidBenchmarkException {
ImmutableSet.Builder<Experiment> builder = ImmutableSet.builder();
for (Experiment experiment : experiments) {
Class<?> clazz = benchmarkClass.benchmarkClass();
try {
Object benchmark = injector.createChildInjector(ExperimentModule.forExperiment(experiment))
.getInstance(Key.get(clazz));
benchmarkClass.setUpBenchmark(benchmark);
try {
experiment.instrumentation().dryRun(benchmark);
builder.add(experiment);
} finally {
// discard 'benchmark' now; the worker will have to instantiate its own anyway
benchmarkClass.cleanup(benchmark);
}
} catch (ProvisionException e) {
Throwable cause = e.getCause();
if (cause != null) {
throw new UserCodeException(cause);
}
throw e;
} catch (CreationException e) {
// Guice formatting is a little ugly
StringBuilder message = new StringBuilder(
"Could not create an instance of the benchmark class following reasons:");
int errorNum = 0;
for (Message guiceMessage : e.getErrorMessages()) {
message.append("\n ").append(++errorNum).append(") ")
.append(guiceMessage.getMessage());
}
throw new InvalidBenchmarkException(message.toString(), e);
} catch (SkipThisScenarioException innocuous) {}
}
return builder.build();
}
public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(
Iterable<? extends ListenableFuture<? extends T>> futures) {
final ConcurrentLinkedQueue<SettableFuture<T>> delegates = Queues.newConcurrentLinkedQueue();
ImmutableList.Builder<ListenableFuture<T>> listBuilder = ImmutableList.builder();
for (final ListenableFuture<? extends T> future : futures) {
SettableFuture<T> delegate = SettableFuture.create();
// Must make sure to add the delegate to the queue first in case the future is already done
delegates.add(delegate);
future.addListener(new Runnable() {
@Override public void run() {
SettableFuture<T> delegate = delegates.remove();
try {
delegate.set(Uninterruptibles.getUninterruptibly(future));
} catch (ExecutionException e) {
delegate.setException(e.getCause());
} catch (CancellationException e) {
delegate.cancel(true);
}
}
}, MoreExecutors.directExecutor());
listBuilder.add(delegate);
}
return listBuilder.build();
}
}
|
caliper/src/main/java/com/google/caliper/runner/ExperimentingCaliperRun.java
|
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.caliper.runner;
import static java.util.logging.Level.WARNING;
import com.google.caliper.api.ResultProcessor;
import com.google.caliper.api.SkipThisScenarioException;
import com.google.caliper.options.CaliperOptions;
import com.google.caliper.util.Stdout;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.FutureFallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.inject.CreationException;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.ProvisionException;
import com.google.inject.spi.Message;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Provider;
/**
* An execution of each {@link Experiment} for the configured number of trials.
*/
@VisibleForTesting
public final class ExperimentingCaliperRun implements CaliperRun {
private static final Logger logger = Logger.getLogger(ExperimentingCaliperRun.class.getName());
private static final FutureFallback<Object> FALLBACK_TO_NULL = new FutureFallback<Object>() {
final ListenableFuture<Object> nullFuture = Futures.immediateFuture(null);
@Override public ListenableFuture<Object> create(Throwable t) throws Exception {
return nullFuture;
}
};
private final Injector injector;
private final CaliperOptions options;
private final PrintWriter stdout;
private final BenchmarkClass benchmarkClass;
private final ImmutableSet<Instrument> instruments;
private final ImmutableSet<ResultProcessor> resultProcessors;
private final ExperimentSelector selector;
private final Provider<ScheduledTrial> scheduledTrial;
private final Provider<ListeningExecutorService> executorProvider;
@Inject @VisibleForTesting
public ExperimentingCaliperRun(
Injector injector,
CaliperOptions options,
@Stdout PrintWriter stdout,
BenchmarkClass benchmarkClass,
ImmutableSet<Instrument> instruments,
ImmutableSet<ResultProcessor> resultProcessors,
ExperimentSelector selector,
Provider<ScheduledTrial> scheduledTrial,
Provider<ListeningExecutorService> executorProvider) {
this.injector = injector;
this.options = options;
this.stdout = stdout;
this.benchmarkClass = benchmarkClass;
this.instruments = instruments;
this.resultProcessors = resultProcessors;
this.scheduledTrial = scheduledTrial;
this.selector = selector;
this.executorProvider = executorProvider;
}
@Override
public void run() throws InvalidBenchmarkException {
ImmutableSet<Experiment> allExperiments = selector.selectExperiments();
// TODO(lukes): move this standard-out handling into the ConsoleOutput class?
stdout.println("Experiment selection: ");
stdout.println(" Benchmark Methods: " + FluentIterable.from(allExperiments)
.transform(new Function<Experiment, String>() {
@Override public String apply(Experiment experiment) {
return experiment.instrumentation().benchmarkMethod().getName();
}
}).toSet());
stdout.println(" Instruments: " + FluentIterable.from(selector.instruments())
.transform(new Function<Instrument, String>() {
@Override public String apply(Instrument instrument) {
return instrument.name();
}
}));
stdout.println(" User parameters: " + selector.userParameters());
stdout.println(" Virtual machines: " + FluentIterable.from(selector.vms())
.transform(
new Function<VirtualMachine, String>() {
@Override public String apply(VirtualMachine vm) {
return vm.name;
}
}));
stdout.println(" Selection type: " + selector.selectionType());
stdout.println();
if (allExperiments.isEmpty()) {
throw new InvalidBenchmarkException(
"There were no experiments to be performed for the class %s using the instruments %s",
benchmarkClass.benchmarkClass().getSimpleName(), instruments);
}
stdout.format("This selection yields %s experiments.%n", allExperiments.size());
stdout.flush();
// always dry run first.
ImmutableSet<Experiment> experimentsToRun = dryRun(allExperiments);
if (experimentsToRun.size() != allExperiments.size()) {
stdout.format("%d experiments were skipped.%n",
allExperiments.size() - experimentsToRun.size());
}
if (experimentsToRun.isEmpty()) {
throw new InvalidBenchmarkException("All experiments were skipped.");
}
if (options.dryRun()) {
return;
}
stdout.flush();
int totalTrials = experimentsToRun.size() * options.trialsPerScenario();
Stopwatch stopwatch = Stopwatch.createStarted();
List<ScheduledTrial> trials = createScheduledTrials(experimentsToRun, totalTrials);
final ListeningExecutorService executor = executorProvider.get();
List<ListenableFuture<TrialResult>> pendingTrials = scheduleTrials(trials, executor);
ConsoleOutput output = new ConsoleOutput(stdout, totalTrials, stopwatch);
try {
// Process results as they complete.
for (ListenableFuture<TrialResult> trialFuture : inCompletionOrder(pendingTrials)) {
try {
TrialResult result = trialFuture.get();
output.processTrial(result);
for (ResultProcessor resultProcessor : resultProcessors) {
resultProcessor.processTrial(result.getTrial());
}
} catch (ExecutionException e) {
if (e.getCause() instanceof TrialFailureException) {
output.processFailedTrial((TrialFailureException) e.getCause());
} else {
for (ListenableFuture<?> toCancel : pendingTrials) {
toCancel.cancel(true);
}
throw Throwables.propagate(e.getCause());
}
} catch (InterruptedException e) {
// be responsive to interruption, cancel outstanding work and exit
for (ListenableFuture<?> toCancel : pendingTrials) {
// N.B. TrialRunLoop is responsive to interruption.
toCancel.cancel(true);
}
throw new RuntimeException(e);
}
}
} finally {
executor.shutdown();
output.close();
}
for (ResultProcessor resultProcessor : resultProcessors) {
try {
resultProcessor.close();
} catch (IOException e) {
logger.log(WARNING, "Could not close a result processor: " + resultProcessor, e);
}
}
}
/**
* Schedule all the trials.
*
* <p>This method arranges all the {@link ScheduledTrial trials} to run according to their
* scheduling criteria. The executor instance is responsible for enforcing max parallelism.
*/
private List<ListenableFuture<TrialResult>> scheduleTrials(List<ScheduledTrial> trials,
final ListeningExecutorService executor) {
List<ListenableFuture<TrialResult>> pendingTrials = Lists.newArrayList();
List<ScheduledTrial> serialTrials = Lists.newArrayList();
for (final ScheduledTrial scheduledTrial : trials) {
if (scheduledTrial.policy() == TrialSchedulingPolicy.PARALLEL) {
pendingTrials.add(executor.submit(scheduledTrial.trialTask()));
} else {
serialTrials.add(scheduledTrial);
}
}
// A future representing the completion of all prior tasks. Futures.successfulAsList allows us
// to ignore failure.
ListenableFuture<?> previous = Futures.successfulAsList(pendingTrials);
for (final ScheduledTrial scheduledTrial : serialTrials) {
// each of these trials can only start after all prior trials have finished, so we use
// Futures.transform to force the sequencing.
ListenableFuture<TrialResult> current =
Futures.transform(
previous,
new AsyncFunction<Object, TrialResult>() {
@Override public ListenableFuture<TrialResult> apply(Object ignored) {
return executor.submit(scheduledTrial.trialTask());
}
});
pendingTrials.add(current);
// ignore failure of the prior task.
previous = Futures.withFallback(current, FALLBACK_TO_NULL);
}
return pendingTrials;
}
/** Returns all the ScheduledTrials for this run. */
private List<ScheduledTrial> createScheduledTrials(ImmutableSet<Experiment> experimentsToRun,
int totalTrials) {
List<ScheduledTrial> trials = Lists.newArrayListWithCapacity(totalTrials);
/** This is 1-indexed because it's only used for display to users. E.g. "Trial 1 of 27" */
int trialNumber = 1;
for (int i = 0; i < options.trialsPerScenario(); i++) {
for (Experiment experiment : experimentsToRun) {
try {
trials.add(TrialScopes.makeContext(UUID.randomUUID(), trialNumber, experiment)
.call(new Callable<ScheduledTrial>() {
@Override public ScheduledTrial call() {
return scheduledTrial.get();
}
}));
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
trialNumber++;
}
}
}
return trials;
}
/**
* Attempts to run each given scenario once, in the current VM. Returns a set of all of the
* scenarios that didn't throw a {@link SkipThisScenarioException}.
*/
ImmutableSet<Experiment> dryRun(Iterable<Experiment> experiments)
throws InvalidBenchmarkException {
ImmutableSet.Builder<Experiment> builder = ImmutableSet.builder();
for (Experiment experiment : experiments) {
Class<?> clazz = benchmarkClass.benchmarkClass();
try {
Object benchmark = injector.createChildInjector(ExperimentModule.forExperiment(experiment))
.getInstance(Key.get(clazz));
benchmarkClass.setUpBenchmark(benchmark);
try {
experiment.instrumentation().dryRun(benchmark);
builder.add(experiment);
} finally {
// discard 'benchmark' now; the worker will have to instantiate its own anyway
benchmarkClass.cleanup(benchmark);
}
} catch (ProvisionException e) {
Throwable cause = e.getCause();
if (cause != null) {
throw new UserCodeException(cause);
}
throw e;
} catch (CreationException e) {
// Guice formatting is a little ugly
StringBuilder message = new StringBuilder(
"Could not create an instance of the benchmark class following reasons:");
int errorNum = 0;
for (Message guiceMessage : e.getErrorMessages()) {
message.append("\n ").append(++errorNum).append(") ")
.append(guiceMessage.getMessage());
}
throw new InvalidBenchmarkException(message.toString(), e);
} catch (SkipThisScenarioException innocuous) {}
}
return builder.build();
}
public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(
Iterable<? extends ListenableFuture<? extends T>> futures) {
final ConcurrentLinkedQueue<SettableFuture<T>> delegates = Queues.newConcurrentLinkedQueue();
ImmutableList.Builder<ListenableFuture<T>> listBuilder = ImmutableList.builder();
Executor executor = MoreExecutors.sameThreadExecutor();
for (final ListenableFuture<? extends T> future : futures) {
SettableFuture<T> delegate = SettableFuture.create();
// Must make sure to add the delegate to the queue first in case the future is already done
delegates.add(delegate);
future.addListener(new Runnable() {
@Override public void run() {
SettableFuture<T> delegate = delegates.remove();
try {
delegate.set(Uninterruptibles.getUninterruptibly(future));
} catch (ExecutionException e) {
delegate.setException(e.getCause());
} catch (CancellationException e) {
delegate.cancel(true);
}
}
}, executor);
listBuilder.add(delegate);
}
return listBuilder.build();
}
}
|
Migrate callers of MoreExecutors.sameThreadExecutor() to use either
MoreExecutors.directExecutor() or MoreExecutors.newDirectExecutorService()
based on whether the code requires an Executor or an ExecutorService instance.
This is being done to resolve some performance issues with the current
sameThreadExecutor() implementation, by allowing users who don’t need
ExecutorService#shutdown semantics to not pay for them, and to make the costs
more obvious for users who do need them.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=99197582
|
caliper/src/main/java/com/google/caliper/runner/ExperimentingCaliperRun.java
|
Migrate callers of MoreExecutors.sameThreadExecutor() to use either MoreExecutors.directExecutor() or MoreExecutors.newDirectExecutorService() based on whether the code requires an Executor or an ExecutorService instance.
|
<ide><path>aliper/src/main/java/com/google/caliper/runner/ExperimentingCaliperRun.java
<ide> import java.util.concurrent.CancellationException;
<ide> import java.util.concurrent.ConcurrentLinkedQueue;
<ide> import java.util.concurrent.ExecutionException;
<del>import java.util.concurrent.Executor;
<ide> import java.util.logging.Logger;
<ide>
<ide> import javax.inject.Inject;
<ide> Iterable<? extends ListenableFuture<? extends T>> futures) {
<ide> final ConcurrentLinkedQueue<SettableFuture<T>> delegates = Queues.newConcurrentLinkedQueue();
<ide> ImmutableList.Builder<ListenableFuture<T>> listBuilder = ImmutableList.builder();
<del> Executor executor = MoreExecutors.sameThreadExecutor();
<ide> for (final ListenableFuture<? extends T> future : futures) {
<ide> SettableFuture<T> delegate = SettableFuture.create();
<ide> // Must make sure to add the delegate to the queue first in case the future is already done
<ide> delegate.cancel(true);
<ide> }
<ide> }
<del> }, executor);
<add> }, MoreExecutors.directExecutor());
<ide> listBuilder.add(delegate);
<ide> }
<ide> return listBuilder.build();
|
|
Java
|
apache-2.0
|
8bee76ba450e23dcf064067f5dbae21368d1c4d7
| 0 |
RWTH-i5-IDSG/jamocha,RWTH-i5-IDSG/jamocha
|
/*
* Copyright 2002-2013 The Jamocha Team
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.jamocha.org/
*
* 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.jamocha.dn;
import static org.jamocha.util.ToArray.toArray;
import java.io.OutputStream;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.Getter;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.ConsoleAppender.Target;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.jamocha.dn.ConflictSet.RuleAndToken;
import org.jamocha.dn.ConstructCache.Deffacts;
import org.jamocha.dn.ConstructCache.Defrule;
import org.jamocha.dn.ConstructCache.Defrule.TranslatedPath;
import org.jamocha.dn.compiler.PathFilterConsolidator;
import org.jamocha.dn.memory.Fact;
import org.jamocha.dn.memory.FactAddress;
import org.jamocha.dn.memory.FactIdentifier;
import org.jamocha.dn.memory.MemoryFact;
import org.jamocha.dn.memory.MemoryFactToFactIdentifier;
import org.jamocha.dn.memory.MemoryFactory;
import org.jamocha.dn.memory.MemoryHandlerMain;
import org.jamocha.dn.memory.MemoryHandlerPlusTemp;
import org.jamocha.dn.memory.MemoryHandlerTerminal.Assert;
import org.jamocha.dn.memory.SlotType;
import org.jamocha.dn.memory.Template;
import org.jamocha.dn.memory.Template.Slot;
import org.jamocha.dn.nodes.AlphaNode;
import org.jamocha.dn.nodes.BetaNode;
import org.jamocha.dn.nodes.Edge;
import org.jamocha.dn.nodes.Node;
import org.jamocha.dn.nodes.ObjectTypeNode;
import org.jamocha.dn.nodes.RootNode;
import org.jamocha.dn.nodes.TerminalNode;
import org.jamocha.filter.FilterFunctionCompare;
import org.jamocha.filter.Path;
import org.jamocha.filter.PathCollector;
import org.jamocha.filter.PathFilter;
import org.jamocha.function.FunctionDictionary;
import org.jamocha.function.fwa.Assert.TemplateContainer;
import org.jamocha.languages.clips.ClipsLogFormatter;
import org.jamocha.languages.common.RuleConditionProcessor;
import org.jamocha.languages.common.ScopeStack;
import org.jamocha.logging.LayoutAdapter;
import org.jamocha.logging.LogFormatter;
import org.jamocha.logging.OutstreamAppender;
import org.jamocha.logging.TypedFilter;
/**
* The Network class encapsulates the central objects for {@link MemoryFactory} and
* {@link Scheduler} which are required all over the whole discrimination network.
*
* @author Christoph Terwelp <[email protected]>
* @author Fabian Ohler <[email protected]>
* @see MemoryFactory
* @see Scheduler
* @see Node
*/
@Getter
public class Network implements ParserToNetwork, SideEffectFunctionToNetwork {
/**
* -- GETTER --
*
* Gets the memoryFactory to generate the nodes {@link MemoryHandlerMain} and
* {@link MemoryHandlerPlusTemp}.
*
* @return the networks memory Factory
*/
private final MemoryFactory memoryFactory;
/**
* -- GETTER --
*
* Gets the capacity of the token queues in all token processing {@link Node nodes}.
*
* @return the capacity for token queues
*/
private final int tokenQueueCapacity;
/**
* -- GETTER --
*
* Gets the scheduler handling the dispatching of token processing to different threads.
*
* @return the networks scheduler
*/
private final Scheduler scheduler;
/**
* -- GETTER --
*
* Gets the {@link RootNode} of the network.
*
* @return the {@link RootNode} of the network
*/
private final RootNode rootNode;
/**
* -- GETTER --
*
* Gets the {@link ConflictSet conflict set}.
*
* @return conflict set
*/
private final ConflictSet conflictSet;
@Getter
private final ConstructCache constructCache = new ConstructCache();
@Getter(AccessLevel.PRIVATE)
private static int loggerDiscriminator = 0;
@Getter(onMethod = @__(@Override))
private final Logger interactiveEventsLogger = LogManager.getLogger(this.getClass().getCanonicalName() + Integer.valueOf(loggerDiscriminator++).toString());
@Getter(onMethod = @__(@Override))
private final TypedFilter typedFilter = new TypedFilter(true);
@Getter(onMethod = @__(@Override))
private final LogFormatter logFormatter;
@Getter(onMethod = @__(@Override))
private final ScopeStack scope = new ScopeStack();
@Getter(onMethod = @__(@Override))
private Template initialFactTemplate;
@Getter(onMethod = @__(@Override))
final EnumMap<SlotType, Object> defaultValues = new EnumMap<>(SlotType.class);
/**
* Creates a new network object.
*
* @param memoryFactory
* the {@link MemoryFactory} to use in the created network
* @param tokenQueueCapacity
* the capacity of the token queues in all token processing {@link Node nodes}
* @param scheduler
* the {@link Scheduler} to handle the dispatching of token processing
*/
public Network(final MemoryFactory memoryFactory, final LogFormatter logFormatter, final int tokenQueueCapacity, final Scheduler scheduler) {
this.memoryFactory = memoryFactory;
this.tokenQueueCapacity = tokenQueueCapacity;
this.scheduler = scheduler;
this.conflictSet = new ConflictSet(this);
this.rootNode = new RootNode();
this.logFormatter = logFormatter;
createInitialDeffact();
createDummyTemplate();
reset();
{
for (final SlotType type : EnumSet.allOf(SlotType.class)) {
switch (type) {
case BOOLEAN:
defaultValues.put(type, Boolean.FALSE);
break;
case DATETIME:
defaultValues.put(type, ZonedDateTime.now());
break;
case DOUBLE:
defaultValues.put(type, Double.valueOf(0.0));
break;
case LONG:
defaultValues.put(type, Long.valueOf(0));
break;
case NIL:
defaultValues.put(type, null);
break;
case STRING:
defaultValues.put(type, "");
break;
case SYMBOL:
defaultValues.put(type, this.getScope().getOrCreateSymbol("nil"));
break;
case FACTADDRESS:
// should be handled by createDummyFact()
assert null != defaultValues.get(SlotType.FACTADDRESS);
break;
}
}
}
FunctionDictionary.load();
{
// there seem to be two different log levels: one in the logger (aka in the
// PrivateConfig of the logger) and one in the LoggerConfig (which may be shared); the
// two values can be synchronized via LoggerContext::updateLoggers (shared -> private)
// making a change (additive, appender, filter) to the logger leads to the creation of
// an own logger config for our logger
((org.apache.logging.log4j.core.Logger) this.interactiveEventsLogger).setAdditive(false);
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final LoggerConfig loggerConfig = config.getLoggerConfig(this.getInteractiveEventsLogger().getName());
// the normal constructor is private, thus we have to use the plugin-level access
final Appender appender = ConsoleAppender.createAppender(LayoutAdapter.createLayout(config), (Filter) null, Target.SYSTEM_OUT.name(), "consoleAppender", "true", "true");
// loggerConfig.getAppenders().forEach((n, a) -> loggerConfig.removeAppender(n));
// loggerConfig.setAdditive(false);
loggerConfig.setLevel(Level.ALL);
loggerConfig.addFilter(typedFilter);
loggerConfig.addAppender(appender, Level.ALL, (Filter) null);
config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(Level.INFO);
// This causes all loggers to re-fetch information from their LoggerConfig
ctx.updateLoggers();
}
}
private void createInitialDeffact() {
this.initialFactTemplate = defTemplate("initial-fact", "");
defFacts("initial-fact", "", new TemplateContainer(initialFactTemplate));
}
private void createDummyTemplate() {
this.defTemplate("dummy-fact", "used as default value for FACT-ADDRESS");
}
private void createDummyFact() {
final FactIdentifier[] factIdentifiers = assertFacts(new TemplateContainer(this.constructCache.getTemplate("dummy-fact")).toFact());
assert 1 == factIdentifiers.length;
this.defaultValues.put(SlotType.FACTADDRESS, factIdentifiers[0]);
}
/**
* Creates a new network object using the {@link ClipsLogFormatter}.
*
* @param tokenQueueCapacity
* the capacity of the token queues in all token processing {@link Node nodes}
* @param scheduler
* the {@link Scheduler} to handle the dispatching of token processing
*/
public Network(final MemoryFactory memoryFactory, final int tokenQueueCapacity, final Scheduler scheduler) {
this(memoryFactory, ClipsLogFormatter.getMessageFormatter(), tokenQueueCapacity, scheduler);
}
/**
* Creates a new network object with the {@link org.jamocha.dn.memory.javaimpl default memory
* implementation}.
*
* @param tokenQueueCapacity
* the capacity of the token queues in all token processing {@link Node nodes}
* @param scheduler
* the {@link Scheduler} to handle the dispatching of token processing
*/
public Network(final int tokenQueueCapacity, final Scheduler scheduler) {
this(org.jamocha.dn.memory.javaimpl.MemoryFactory.getMemoryFactory(), ClipsLogFormatter.getMessageFormatter(), tokenQueueCapacity, scheduler);
}
/**
* Creates a new network object with the {@link org.jamocha.dn.memory.javaimpl default memory
* implementation} and {@link ThreadPoolScheduler scheduler}.
*/
public Network() {
this(Integer.MAX_VALUE, new ThreadPoolScheduler(10));
}
/**
* Tries to find a node performing the same filtering as the given filter and calls
* {@link Node#shareNode(java.util.Map, org.jamocha.filter.Path...)} or creates a new {@link Node} for the given
* {@link PathFilter filter}. Returns true iff a {@link Node} to share was found.
*
* @param filter
* {@link PathFilter} to find a corresponding {@link Node} for
* @return true iff a {@link Node} to share was found
* @throws IllegalArgumentException
* thrown if one of the {@link Path}s in the {@link PathFilter} was not mapped to a
* {@link Node}
*/
public boolean tryToShareNode(final PathFilter filter) throws IllegalArgumentException {
final Path[] paths = PathCollector.newLinkedHashSet().collectAll(filter).getPathsArray();
// collect the nodes of the paths
final LinkedHashSet<Node> filterPathNodes = new LinkedHashSet<>();
for (final Path path : paths) {
filterPathNodes.add(path.getCurrentlyLowestNode());
}
if (filterPathNodes.contains(null)) {
throw new IllegalArgumentException("Paths did not point to any nodes.");
}
// collect all nodes which have edges to all of the paths nodes as candidates
final LinkedHashSet<Node> candidates = identifyShareCandidates(filterPathNodes);
// get normal version of filter to share
final PathFilter normalisedFilter = filter.normalise();
// check candidates for possible node sharing
for (final Node candidate : candidates) {
// check if filter matches
final Map<Path, FactAddress> map = FilterFunctionCompare.equals(candidate, normalisedFilter);
if (null == map) continue;
candidate.shareNode(map, paths);
return true;
}
return false;
}
private LinkedHashSet<Node> identifyShareCandidates(final LinkedHashSet<Node> filterPathNodes) {
final LinkedHashSet<Node> candidates = new LinkedHashSet<>();
assert filterPathNodes.size() > 0;
final Iterator<Node> filterPathNodesIterator = filterPathNodes.iterator();
// TODO existential edges???
// add all children of the first node
final Collection<Edge> firstNodesOutgoingEdges = filterPathNodesIterator.next().getOutgoingEdges();
for (final Edge edge : firstNodesOutgoingEdges) {
try {
candidates.add(edge.getTargetNode());
} catch (final UnsupportedOperationException e) {
// triggered by terminal node, just don't add it
}
}
// remove all nodes which aren't children of all other nodes
while (filterPathNodesIterator.hasNext()) {
final Node node = filterPathNodesIterator.next();
final HashSet<Node> cutSet = new HashSet<>();
for (final Edge edge : node.getOutgoingEdges()) {
try {
cutSet.add(edge.getTargetNode());
} catch (final UnsupportedOperationException e) {
// triggered by terminal node, just don't add it
}
}
candidates.retainAll(cutSet);
}
return candidates;
}
/**
* Creates network nodes for one rule, consisting of the passed filters.
*
* @param filters
* list of filters in order of implementation in the network. Each filter is
* implemented in a separate node. Node-Sharing is used if possible
* @return created TerminalNode for the constructed rule
*/
public TerminalNode buildRule(final Defrule.TranslatedPath translatedPath, final PathFilter... filters) {
final LinkedHashSet<Path> allPaths;
{
final PathCollector<LinkedHashSet<Path>> collector = PathCollector.newLinkedHashSet();
for (final PathFilter filter : filters) {
collector.collectAll(filter);
}
this.rootNode.addPaths(this, collector.getPathsArray());
allPaths = collector.getPaths();
}
final ArrayList<Node> nodes = new ArrayList<>();
for (final PathFilter filter : filters) {
if (!tryToShareNode(filter))
if (PathCollector.newLinkedHashSet().collectAll(filter).getPaths().size() == 1) {
nodes.add(new AlphaNode(this, filter));
} else {
nodes.add(new BetaNode(this, filter));
}
}
final Node lowestNode = allPaths.iterator().next().getCurrentlyLowestNode();
assert allPaths.stream().map(Path::getCurrentlyLowestNode).distinct().count() == 1;
final TerminalNode terminalNode = new TerminalNode(this, lowestNode, translatedPath);
for (final Node node : nodes) {
node.activateTokenQueue();
}
return terminalNode;
}
@Override
public FactIdentifier[] assertFacts(final Fact... facts) {
final FactIdentifier[] assertedFacts = getRootNode().assertFacts(facts);
getLogFormatter().messageFactAssertions(this, assertedFacts);
return assertedFacts;
}
@Override
public void retractFacts(final FactIdentifier... factIdentifiers) {
getLogFormatter().messageFactRetractions(this, factIdentifiers);
getRootNode().retractFacts(factIdentifiers);
}
@Override
public MemoryFact getMemoryFact(final FactIdentifier factIdentifier) {
return getRootNode().getMemoryFact(factIdentifier);
}
@Override
public Map<FactIdentifier, MemoryFact> getMemoryFacts() {
return getRootNode().getMemoryFacts();
}
@Override
public MemoryFactToFactIdentifier getMemoryFactToFactIdentifier() {
return getRootNode();
}
@Override
public Template defTemplate(final String name, final String description, final Slot... slots) {
final Template template = getMemoryFactory().newTemplate(name, description, slots);
final ObjectTypeNode otn = new ObjectTypeNode(this, template);
getRootNode().putOTN(otn);
otn.activateTokenQueue();
this.constructCache.addTemplate(template);
return template;
}
@Override
public Template getTemplate(final String name) {
return this.constructCache.getTemplate(name);
}
@Override
public Collection<Template> getTemplates() {
return this.constructCache.getTemplates();
}
@Override
public Deffacts defFacts(final String name, final String description, final TemplateContainer... containers) {
final List<TemplateContainer> conList = Arrays.asList(containers);
final Deffacts deffacts = new Deffacts(name, description, conList);
this.constructCache.addDeffacts(deffacts);
return deffacts;
}
@Override
public Deffacts getDeffacts(final String name) {
return this.constructCache.getDeffacts(name);
}
@Override
public Collection<Deffacts> getDeffacts() {
return this.constructCache.getDeffacts();
}
@Override
public void defRules(final Defrule... defrules) {
for (final Defrule defrule : defrules) {
this.compileRule(defrule);
for (final TranslatedPath translated : defrule.getTranslatedPathVersions()) {
buildRule(translated, toArray(translated.getCondition(), PathFilter[]::new));
}
// add the rule and the contained translated versions to the construct cache
this.constructCache.addRule(defrule);
}
}
@Override
public Defrule getRule(final String name) {
return this.constructCache.getRule(name);
}
@Override
public Collection<Defrule> getRules() {
return this.constructCache.getRules();
}
@Override
public void reset() {
getRootNode().reset();
createDummyFact();
// assert all deffacts
assertFacts(toArray(this.constructCache.getDeffacts().stream().flatMap(def -> def.getContainers().stream()).map(TemplateContainer::toFact), Fact[]::new));
}
@Override
public void clear() {
this.rootNode.clear();
this.conflictSet.flush();
this.constructCache.clear();
createInitialDeffact();
createDummyTemplate();
reset();
}
@Override
public void run(final long maxNumRules) {
long numRules = 0;
do {
this.scheduler.waitForNoUnfinishedJobs();
conflictSet.deleteRevokedEntries();
final Optional<RuleAndToken> optional = ConflictResolutionStrategy.random.pick(this.conflictSet);
if (!optional.isPresent()) break;
final RuleAndToken ruleAndToken = optional.get();
this.logFormatter.messageRuleFiring(this, ruleAndToken.getRule(), (Assert) ruleAndToken.getToken());
ruleAndToken.getRule().getActionList().evaluate(ruleAndToken.getToken());
this.conflictSet.remove(ruleAndToken);
++numRules;
} while (0L == maxNumRules || numRules < maxNumRules);
}
public void shutdown() {
scheduler.shutdown();
}
public void shutdownNow() {
scheduler.shutdownNow();
}
private void compileRule(final Defrule rule) {
// Preprocess CEs
RuleConditionProcessor.flatten(rule.getCondition());
// Transform TestCEs to PathFilters
new PathFilterConsolidator(this.initialFactTemplate, rule).consolidate();
}
/**
* Adds an appender to the logging framework.
*
* @param out
* output stream
* @param plain
* true for just the content, false for log-style additional infos in front of the
* content
*/
public void addAppender(final OutputStream out, final boolean plain) {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final LoggerConfig loggerConfig = config.getLoggerConfig(this.getInteractiveEventsLogger().getName());
loggerConfig.addAppender(OutstreamAppender.newInstance(out, LayoutAdapter.createLayout(config, plain), null, true), Level.ALL, (Filter) null);
// This causes all loggers to re-fetch information from their LoggerConfig
ctx.updateLoggers();
}
/**
* A default network object with a basic setup, used for testing and other quick and dirty
* networks.
*/
public final static Network DEFAULTNETWORK = new Network(org.jamocha.dn.memory.javaimpl.MemoryFactory.getMemoryFactory(), ClipsLogFormatter.getMessageFormatter(), Integer.MAX_VALUE,
// new ThreadPoolScheduler(10)
new PlainScheduler());
}
|
src/org/jamocha/dn/Network.java
|
/*
* Copyright 2002-2013 The Jamocha Team
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.jamocha.org/
*
* 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.jamocha.dn;
import static org.jamocha.util.ToArray.toArray;
import java.io.OutputStream;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.Getter;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.ConsoleAppender.Target;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.jamocha.dn.ConflictSet.RuleAndToken;
import org.jamocha.dn.ConstructCache.Deffacts;
import org.jamocha.dn.ConstructCache.Defrule;
import org.jamocha.dn.ConstructCache.Defrule.TranslatedPath;
import org.jamocha.dn.compiler.PathFilterConsolidator;
import org.jamocha.dn.memory.Fact;
import org.jamocha.dn.memory.FactAddress;
import org.jamocha.dn.memory.FactIdentifier;
import org.jamocha.dn.memory.MemoryFact;
import org.jamocha.dn.memory.MemoryFactToFactIdentifier;
import org.jamocha.dn.memory.MemoryFactory;
import org.jamocha.dn.memory.MemoryHandlerMain;
import org.jamocha.dn.memory.MemoryHandlerPlusTemp;
import org.jamocha.dn.memory.MemoryHandlerTerminal.Assert;
import org.jamocha.dn.memory.SlotType;
import org.jamocha.dn.memory.Template;
import org.jamocha.dn.memory.Template.Slot;
import org.jamocha.dn.nodes.AlphaNode;
import org.jamocha.dn.nodes.BetaNode;
import org.jamocha.dn.nodes.Edge;
import org.jamocha.dn.nodes.Node;
import org.jamocha.dn.nodes.ObjectTypeNode;
import org.jamocha.dn.nodes.RootNode;
import org.jamocha.dn.nodes.TerminalNode;
import org.jamocha.filter.FilterFunctionCompare;
import org.jamocha.filter.Path;
import org.jamocha.filter.PathCollector;
import org.jamocha.filter.PathFilter;
import org.jamocha.function.FunctionDictionary;
import org.jamocha.function.fwa.Assert.TemplateContainer;
import org.jamocha.languages.clips.ClipsLogFormatter;
import org.jamocha.languages.common.RuleConditionProcessor;
import org.jamocha.languages.common.ScopeStack;
import org.jamocha.logging.LayoutAdapter;
import org.jamocha.logging.LogFormatter;
import org.jamocha.logging.OutstreamAppender;
import org.jamocha.logging.TypedFilter;
/**
* The Network class encapsulates the central objects for {@link MemoryFactory} and
* {@link Scheduler} which are required all over the whole discrimination network.
*
* @author Christoph Terwelp <[email protected]>
* @author Fabian Ohler <[email protected]>
* @see MemoryFactory
* @see Scheduler
* @see Node
*/
@Getter
public class Network implements ParserToNetwork, SideEffectFunctionToNetwork {
/**
* -- GETTER --
* <p>
* Gets the memoryFactory to generate the nodes {@link MemoryHandlerMain} and
* {@link MemoryHandlerPlusTemp}.
*
* @return the networks memory Factory
*/
private final MemoryFactory memoryFactory;
/**
* -- GETTER --
* <p>
* Gets the capacity of the token queues in all token processing {@link Node nodes}.
*
* @return the capacity for token queues
*/
private final int tokenQueueCapacity;
/**
* -- GETTER --
* <p>
* Gets the scheduler handling the dispatching of token processing to different threads.
*
* @return the networks scheduler
*/
private final Scheduler scheduler;
/**
* -- GETTER --
* <p>
* Gets the {@link RootNode} of the network.
*
* @return the {@link RootNode} of the network
*/
private final RootNode rootNode;
/**
* -- GETTER --
* <p>
* Gets the {@link ConflictSet conflict set}.
*
* @return conflict set
*/
private final ConflictSet conflictSet;
@Getter
private final ConstructCache constructCache = new ConstructCache();
@Getter(AccessLevel.PRIVATE)
private static int loggerDiscriminator = 0;
@Getter(onMethod = @__(@Override))
private final Logger interactiveEventsLogger = LogManager.getLogger(this.getClass().getCanonicalName() + Integer.valueOf(loggerDiscriminator++).toString());
@Getter(onMethod = @__(@Override))
private final TypedFilter typedFilter = new TypedFilter(true);
@Getter(onMethod = @__(@Override))
private final LogFormatter logFormatter;
@Getter(onMethod = @__(@Override))
private final ScopeStack scope = new ScopeStack();
@Getter(onMethod = @__(@Override))
private Template initialFactTemplate;
@Getter(onMethod = @__(@Override))
final EnumMap<SlotType, Object> defaultValues = new EnumMap<>(SlotType.class);
/**
* Creates a new network object.
*
* @param memoryFactory
* the {@link MemoryFactory} to use in the created network
* @param tokenQueueCapacity
* the capacity of the token queues in all token processing {@link Node nodes}
* @param scheduler
* the {@link Scheduler} to handle the dispatching of token processing
*/
public Network(final MemoryFactory memoryFactory, final LogFormatter logFormatter, final int tokenQueueCapacity, final Scheduler scheduler) {
this.memoryFactory = memoryFactory;
this.tokenQueueCapacity = tokenQueueCapacity;
this.scheduler = scheduler;
this.conflictSet = new ConflictSet(this);
this.rootNode = new RootNode();
this.logFormatter = logFormatter;
createInitialDeffact();
createDummyTemplate();
reset();
{
for (final SlotType type : EnumSet.allOf(SlotType.class)) {
switch (type) {
case BOOLEAN:
defaultValues.put(type, Boolean.FALSE);
break;
case DATETIME:
defaultValues.put(type, ZonedDateTime.now());
break;
case DOUBLE:
defaultValues.put(type, Double.valueOf(0.0));
break;
case LONG:
defaultValues.put(type, Long.valueOf(0));
break;
case NIL:
defaultValues.put(type, null);
break;
case STRING:
defaultValues.put(type, "");
break;
case SYMBOL:
defaultValues.put(type, this.getScope().getOrCreateSymbol("nil"));
break;
case FACTADDRESS:
// should be handled by createDummyFact()
assert null != defaultValues.get(SlotType.FACTADDRESS);
break;
}
}
}
FunctionDictionary.load();
{
// there seem to be two different log levels: one in the logger (aka in the
// PrivateConfig of the logger) and one in the LoggerConfig (which may be shared); the
// two values can be synchronized via LoggerContext::updateLoggers (shared -> private)
// making a change (additive, appender, filter) to the logger leads to the creation of
// an own logger config for our logger
((org.apache.logging.log4j.core.Logger) this.interactiveEventsLogger).setAdditive(false);
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final LoggerConfig loggerConfig = config.getLoggerConfig(this.getInteractiveEventsLogger().getName());
// the normal constructor is private, thus we have to use the plugin-level access
final Appender appender = ConsoleAppender.createAppender(LayoutAdapter.createLayout(config), (Filter) null, Target.SYSTEM_OUT.name(), "consoleAppender", "true", "true");
// loggerConfig.getAppenders().forEach((n, a) -> loggerConfig.removeAppender(n));
// loggerConfig.setAdditive(false);
loggerConfig.setLevel(Level.ALL);
loggerConfig.addFilter(typedFilter);
loggerConfig.addAppender(appender, Level.ALL, (Filter) null);
config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(Level.INFO);
// This causes all loggers to re-fetch information from their LoggerConfig
ctx.updateLoggers();
}
}
private void createInitialDeffact() {
this.initialFactTemplate = defTemplate("initial-fact", "");
defFacts("initial-fact", "", new TemplateContainer(initialFactTemplate));
}
private void createDummyTemplate() {
this.defTemplate("dummy-fact", "used as default value for FACT-ADDRESS");
}
private void createDummyFact() {
final FactIdentifier[] factIdentifiers = assertFacts(new TemplateContainer(this.constructCache.getTemplate("dummy-fact")).toFact());
assert 1 == factIdentifiers.length;
this.defaultValues.put(SlotType.FACTADDRESS, factIdentifiers[0]);
}
/**
* Creates a new network object using the {@link ClipsLogFormatter}.
*
* @param tokenQueueCapacity
* the capacity of the token queues in all token processing {@link Node nodes}
* @param scheduler
* the {@link Scheduler} to handle the dispatching of token processing
*/
public Network(final MemoryFactory memoryFactory, final int tokenQueueCapacity, final Scheduler scheduler) {
this(memoryFactory, ClipsLogFormatter.getMessageFormatter(), tokenQueueCapacity, scheduler);
}
/**
* Creates a new network object with the {@link org.jamocha.dn.memory.javaimpl default memory
* implementation}.
*
* @param tokenQueueCapacity
* the capacity of the token queues in all token processing {@link Node nodes}
* @param scheduler
* the {@link Scheduler} to handle the dispatching of token processing
*/
public Network(final int tokenQueueCapacity, final Scheduler scheduler) {
this(org.jamocha.dn.memory.javaimpl.MemoryFactory.getMemoryFactory(), ClipsLogFormatter.getMessageFormatter(), tokenQueueCapacity, scheduler);
}
/**
* Creates a new network object with the {@link org.jamocha.dn.memory.javaimpl default memory
* implementation} and {@link ThreadPoolScheduler scheduler}.
*/
public Network() {
this(Integer.MAX_VALUE, new ThreadPoolScheduler(10));
}
/**
* Tries to find a node performing the same filtering as the given filter and calls
* {@link Node#shareNode(java.util.Map, org.jamocha.filter.Path...)} or creates a new {@link Node} for the given
* {@link PathFilter filter}. Returns true iff a {@link Node} to share was found.
*
* @param filter
* {@link PathFilter} to find a corresponding {@link Node} for
* @return true iff a {@link Node} to share was found
* @throws IllegalArgumentException
* thrown if one of the {@link Path}s in the {@link PathFilter} was not mapped to a
* {@link Node}
*/
public boolean tryToShareNode(final PathFilter filter) throws IllegalArgumentException {
final Path[] paths = PathCollector.newLinkedHashSet().collectAll(filter).getPathsArray();
// collect the nodes of the paths
final LinkedHashSet<Node> filterPathNodes = new LinkedHashSet<>();
for (final Path path : paths) {
filterPathNodes.add(path.getCurrentlyLowestNode());
}
if (filterPathNodes.contains(null)) {
throw new IllegalArgumentException("Paths did not point to any nodes.");
}
// collect all nodes which have edges to all of the paths nodes as candidates
final LinkedHashSet<Node> candidates = identifyShareCandidates(filterPathNodes);
// get normal version of filter to share
final PathFilter normalisedFilter = filter.normalise();
// check candidates for possible node sharing
for (final Node candidate : candidates) {
// check if filter matches
final Map<Path, FactAddress> map = FilterFunctionCompare.equals(candidate, normalisedFilter);
if (null == map) continue;
candidate.shareNode(map, paths);
return true;
}
return false;
}
private LinkedHashSet<Node> identifyShareCandidates(final LinkedHashSet<Node> filterPathNodes) {
final LinkedHashSet<Node> candidates = new LinkedHashSet<>();
assert filterPathNodes.size() > 0;
final Iterator<Node> filterPathNodesIterator = filterPathNodes.iterator();
// TODO existential edges???
// add all children of the first node
final Collection<Edge> firstNodesOutgoingEdges = filterPathNodesIterator.next().getOutgoingEdges();
for (final Edge edge : firstNodesOutgoingEdges) {
try {
candidates.add(edge.getTargetNode());
} catch (final UnsupportedOperationException e) {
// triggered by terminal node, just don't add it
}
}
// remove all nodes which aren't children of all other nodes
while (filterPathNodesIterator.hasNext()) {
final Node node = filterPathNodesIterator.next();
final HashSet<Node> cutSet = new HashSet<>();
for (final Edge edge : node.getOutgoingEdges()) {
try {
cutSet.add(edge.getTargetNode());
} catch (final UnsupportedOperationException e) {
// triggered by terminal node, just don't add it
}
}
candidates.retainAll(cutSet);
}
return candidates;
}
/**
* Creates network nodes for one rule, consisting of the passed filters.
*
* @param filters
* list of filters in order of implementation in the network. Each filter is
* implemented in a separate node. Node-Sharing is used if possible
* @return created TerminalNode for the constructed rule
*/
public TerminalNode buildRule(final Defrule.TranslatedPath translatedPath, final PathFilter... filters) {
final LinkedHashSet<Path> allPaths;
{
final PathCollector<LinkedHashSet<Path>> collector = PathCollector.newLinkedHashSet();
for (final PathFilter filter : filters) {
collector.collectAll(filter);
}
this.rootNode.addPaths(this, collector.getPathsArray());
allPaths = collector.getPaths();
}
final ArrayList<Node> nodes = new ArrayList<>();
for (final PathFilter filter : filters) {
if (!tryToShareNode(filter))
if (PathCollector.newLinkedHashSet().collectAll(filter).getPaths().size() == 1) {
nodes.add(new AlphaNode(this, filter));
} else {
nodes.add(new BetaNode(this, filter));
}
}
final Node lowestNode = allPaths.iterator().next().getCurrentlyLowestNode();
assert allPaths.stream().map(Path::getCurrentlyLowestNode).distinct().count() == 1;
final TerminalNode terminalNode = new TerminalNode(this, lowestNode, translatedPath);
for (final Node node : nodes) {
node.activateTokenQueue();
}
return terminalNode;
}
@Override
public FactIdentifier[] assertFacts(final Fact... facts) {
final FactIdentifier[] assertedFacts = getRootNode().assertFacts(facts);
getLogFormatter().messageFactAssertions(this, assertedFacts);
return assertedFacts;
}
@Override
public void retractFacts(final FactIdentifier... factIdentifiers) {
getLogFormatter().messageFactRetractions(this, factIdentifiers);
getRootNode().retractFacts(factIdentifiers);
}
@Override
public MemoryFact getMemoryFact(final FactIdentifier factIdentifier) {
return getRootNode().getMemoryFact(factIdentifier);
}
@Override
public Map<FactIdentifier, MemoryFact> getMemoryFacts() {
return getRootNode().getMemoryFacts();
}
@Override
public MemoryFactToFactIdentifier getMemoryFactToFactIdentifier() {
return getRootNode();
}
@Override
public Template defTemplate(final String name, final String description, final Slot... slots) {
final Template template = getMemoryFactory().newTemplate(name, description, slots);
final ObjectTypeNode otn = new ObjectTypeNode(this, template);
getRootNode().putOTN(otn);
otn.activateTokenQueue();
this.constructCache.addTemplate(template);
return template;
}
@Override
public Template getTemplate(final String name) {
return this.constructCache.getTemplate(name);
}
@Override
public Collection<Template> getTemplates() {
return this.constructCache.getTemplates();
}
@Override
public Deffacts defFacts(final String name, final String description, final TemplateContainer... containers) {
final List<TemplateContainer> conList = Arrays.asList(containers);
final Deffacts deffacts = new Deffacts(name, description, conList);
this.constructCache.addDeffacts(deffacts);
return deffacts;
}
@Override
public Deffacts getDeffacts(final String name) {
return this.constructCache.getDeffacts(name);
}
@Override
public Collection<Deffacts> getDeffacts() {
return this.constructCache.getDeffacts();
}
@Override
public void defRules(final Defrule... defrules) {
for (final Defrule defrule : defrules) {
this.compileRule(defrule);
for (final TranslatedPath translated : defrule.getTranslatedPathVersions()) {
buildRule(translated, toArray(translated.getCondition(), PathFilter[]::new));
}
// add the rule and the contained translated versions to the construct cache
this.constructCache.addRule(defrule);
}
}
@Override
public Defrule getRule(final String name) {
return this.constructCache.getRule(name);
}
@Override
public Collection<Defrule> getRules() {
return this.constructCache.getRules();
}
@Override
public void reset() {
getRootNode().reset();
createDummyFact();
// assert all deffacts
assertFacts(toArray(this.constructCache.getDeffacts().stream().flatMap(def -> def.getContainers().stream()).map(TemplateContainer::toFact), Fact[]::new));
}
@Override
public void clear() {
this.rootNode.clear();
this.conflictSet.flush();
this.constructCache.clear();
createInitialDeffact();
createDummyTemplate();
reset();
}
@Override
public void run(final long maxNumRules) {
long numRules = 0;
do {
this.scheduler.waitForNoUnfinishedJobs();
conflictSet.deleteRevokedEntries();
final Optional<RuleAndToken> optional = ConflictResolutionStrategy.random.pick(this.conflictSet);
if (!optional.isPresent()) break;
final RuleAndToken ruleAndToken = optional.get();
this.logFormatter.messageRuleFiring(this, ruleAndToken.getRule(), (Assert) ruleAndToken.getToken());
ruleAndToken.getRule().getActionList().evaluate(ruleAndToken.getToken());
this.conflictSet.remove(ruleAndToken);
++numRules;
} while (0L == maxNumRules || numRules < maxNumRules);
}
public void shutdown() {
scheduler.shutdown();
}
public void shutdownNow() {
scheduler.shutdownNow();
}
private void compileRule(final Defrule rule) {
// Preprocess CEs
RuleConditionProcessor.flatten(rule.getCondition());
// Transform TestCEs to PathFilters
new PathFilterConsolidator(this.initialFactTemplate, rule).consolidate();
}
/**
* Adds an appender to the logging framework.
*
* @param out
* output stream
* @param plain
* true for just the content, false for log-style additional infos in front of the
* content
*/
public void addAppender(final OutputStream out, final boolean plain) {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final LoggerConfig loggerConfig = config.getLoggerConfig(this.getInteractiveEventsLogger().getName());
loggerConfig.addAppender(OutstreamAppender.newInstance(out, LayoutAdapter.createLayout(config, plain), null, true), Level.ALL, (Filter) null);
// This causes all loggers to re-fetch information from their LoggerConfig
ctx.updateLoggers();
}
/**
* A default network object with a basic setup, used for testing and other quick and dirty
* networks.
*/
public final static Network DEFAULTNETWORK = new Network(org.jamocha.dn.memory.javaimpl.MemoryFactory.getMemoryFactory(), ClipsLogFormatter.getMessageFormatter(), Integer.MAX_VALUE,
// new ThreadPoolScheduler(10)
new PlainScheduler());
}
|
removed the <p>s inserted by IntelliJ
|
src/org/jamocha/dn/Network.java
|
removed the <p>s inserted by IntelliJ
|
<ide><path>rc/org/jamocha/dn/Network.java
<ide>
<ide> /**
<ide> * -- GETTER --
<del> * <p>
<add> *
<ide> * Gets the memoryFactory to generate the nodes {@link MemoryHandlerMain} and
<ide> * {@link MemoryHandlerPlusTemp}.
<ide> *
<ide>
<ide> /**
<ide> * -- GETTER --
<del> * <p>
<add> *
<ide> * Gets the capacity of the token queues in all token processing {@link Node nodes}.
<ide> *
<ide> * @return the capacity for token queues
<ide>
<ide> /**
<ide> * -- GETTER --
<del> * <p>
<add> *
<ide> * Gets the scheduler handling the dispatching of token processing to different threads.
<ide> *
<ide> * @return the networks scheduler
<ide>
<ide> /**
<ide> * -- GETTER --
<del> * <p>
<add> *
<ide> * Gets the {@link RootNode} of the network.
<ide> *
<ide> * @return the {@link RootNode} of the network
<ide>
<ide> /**
<ide> * -- GETTER --
<del> * <p>
<add> *
<ide> * Gets the {@link ConflictSet conflict set}.
<ide> *
<ide> * @return conflict set
|
|
Java
|
apache-2.0
|
34a6403d2b71cea95c19cefa93b39abf35444ae4
| 0 |
uservices-hackathon/butelkatr.io,uservices-hackathon/butelkatr.io
|
package pl.uservices.butelkatr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.google.common.base.Optional;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.nurkiewicz.asyncretry.RetryExecutor;
import com.ofg.infrastructure.discovery.ServiceAlias;
import com.ofg.infrastructure.web.resttemplate.fluent.ServiceRestClient;
/**
* Created by i304608 on 05.11.2015.
*/
@Service
public class ButelkatrService {
private Logger log = LoggerFactory.getLogger(getClass());
private ServiceRestClient serviceRestClient;
private RetryExecutor retryExecutor;
private BeerStorage beerStorage;
@Autowired
public ButelkatrService(ServiceRestClient serviceRestClient,
RetryExecutor retryExecutor, BeerStorage beerStorage) {
this.serviceRestClient = serviceRestClient;
this.retryExecutor = retryExecutor;
this.beerStorage = beerStorage;
}
@Async
public void informBeerCreated(Long quantity) {
beerStorage.addBeer(quantity);
notifyBottlesTotal();
log.info("Bottling process started.");
produceBottles();
}
@Scheduled(fixedRate = 30000)
public void produceBottles() {
createBottles();
fillBottles();
}
private void createBottles() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void fillBottles() {
Optional<Long> beerQuantity = beerStorage.getBeer();
if (beerQuantity.isPresent()) {
BottleDTO bottle = BottleUtil.produceBottle(beerQuantity.get());
log.info("Produced {0} bottles", bottle.quantity);
notifyBottlesProduced(bottle);
}
}
private BottleDTO getBottleQueue(){
return BottleUtil.produceBottle(beerStorage.getTotalBeer());
}
private void notifyBottlesTotal() {
serviceRestClient
.forService(new ServiceAlias("prezentatr"))
.retryUsing(retryExecutor)
.post()
.withCircuitBreaker(
HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory
.asKey("prezentatorBottle")))
.onUrl("/bottleQueue").body(getBottleQueue()).withHeaders()
.contentType("application/prezentator.v1+json").andExecuteFor()
.ignoringResponseAsync();
}
private void notifyBottlesProduced(BottleDTO bootles) {
serviceRestClient
.forService(new ServiceAlias("prezentatr"))
.retryUsing(retryExecutor)
.post()
.withCircuitBreaker(
HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory
.asKey("prezentatorBottle")))
.onUrl("/bottle").body(bootles).withHeaders()
.contentType("application/prezentator.v1+json").andExecuteFor()
.ignoringResponseAsync();
}
}
|
src/main/java/pl/uservices/butelkatr/ButelkatrService.java
|
package pl.uservices.butelkatr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.google.common.base.Optional;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.nurkiewicz.asyncretry.RetryExecutor;
import com.ofg.infrastructure.discovery.ServiceAlias;
import com.ofg.infrastructure.web.resttemplate.fluent.ServiceRestClient;
/**
* Created by i304608 on 05.11.2015.
*/
@Service
public class ButelkatrService {
private Logger log = LoggerFactory.getLogger(getClass());
private ServiceRestClient serviceRestClient;
private RetryExecutor retryExecutor;
private BeerStorage beerStorage;
@Autowired
public ButelkatrService(ServiceRestClient serviceRestClient,
RetryExecutor retryExecutor, BeerStorage beerStorage) {
this.serviceRestClient = serviceRestClient;
this.retryExecutor = retryExecutor;
this.beerStorage = beerStorage;
}
@Async
public void informBeerCreated(Long quantity) {
beerStorage.addBeer(quantity);
notifyBottlesTotal();
log.info("Bottling process started.");
produceBottles();
}
private void produceBottles() {
createBottles();
fillBottles();
}
private void createBottles() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void fillBottles() {
Optional<Long> beerQuantity = beerStorage.getBeer();
if (beerQuantity.isPresent()) {
BottleDTO bottle = BottleUtil.produceBottle(beerQuantity.get());
log.info("Produced {0} bottles", bottle.quantity);
notifyBottlesProduced(bottle);
}
}
private BottleDTO getBottleQueue(){
return BottleUtil.produceBottle(beerStorage.getTotalBeer());
}
private void notifyBottlesTotal() {
serviceRestClient
.forService(new ServiceAlias("prezentatr"))
.retryUsing(retryExecutor)
.post()
.withCircuitBreaker(
HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory
.asKey("prezentatorBottle")))
.onUrl("/bottleQueue").body(getBottleQueue()).withHeaders()
.contentType("application/prezentator.v1+json").andExecuteFor()
.ignoringResponseAsync();
}
private void notifyBottlesProduced(BottleDTO bootles) {
serviceRestClient
.forService(new ServiceAlias("prezentatr"))
.retryUsing(retryExecutor)
.post()
.withCircuitBreaker(
HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory
.asKey("prezentatorBottle")))
.onUrl("/bottle").body(bootles).withHeaders()
.contentType("application/prezentator.v1+json").andExecuteFor()
.ignoringResponseAsync();
}
}
|
added new async scheduled
|
src/main/java/pl/uservices/butelkatr/ButelkatrService.java
|
added new async scheduled
|
<ide><path>rc/main/java/pl/uservices/butelkatr/ButelkatrService.java
<ide> import org.slf4j.LoggerFactory;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.scheduling.annotation.Async;
<add>import org.springframework.scheduling.annotation.Scheduled;
<ide> import org.springframework.stereotype.Service;
<ide>
<ide> import com.google.common.base.Optional;
<ide> produceBottles();
<ide> }
<ide>
<del> private void produceBottles() {
<add>
<add> @Scheduled(fixedRate = 30000)
<add> public void produceBottles() {
<ide> createBottles();
<ide> fillBottles();
<ide> }
|
|
Java
|
mit
|
6c89aa65fbbf7bd81ad44c4d37e2c2edf1028adf
| 0 |
uoa-group-applications/morc,uoa-group-applications/morc
|
package nz.ac.auckland.integration.testing.specification;
import nz.ac.auckland.integration.testing.resource.HeadersTestResource;
import nz.ac.auckland.integration.testing.resource.TestResource;
import nz.ac.auckland.integration.testing.validator.HeadersValidator;
import nz.ac.auckland.integration.testing.validator.Validator;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.util.ExchangeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* A synchronous orchestrated test makes a call to a target endpoint which provides a response. During
* the request process the target may make a number of call outs to expectations which need to be satisfied.
* The response body from the target will also be validated against the expected response body.
*
* @author David MacDonald <[email protected]>
*/
public class SyncOrchestratedTestSpecification extends OrchestratedTestSpecification {
private static final Logger logger = LoggerFactory.getLogger(SyncOrchestratedTestSpecification.class);
private Queue<TestResource> inputRequestBodies;
private Queue<TestResource<Map<String, Object>>> inputRequestHeaders;
private Queue<Validator> responseBodyValidators;
private Queue<HeadersValidator> responseHeadersValidators;
private boolean expectsExceptionResponse = false;
/**
* @param template An Apache Camel template that can be used to send messages to a target endpoint
* @return true if the message is successfully sent the the response body is as expected
*/
protected boolean sendInputInternal(ProducerTemplate template) {
try {
final TestResource inputBody;
final TestResource<Map<String, Object>> inputHeaders;
final Validator responseBodyValidator;
final HeadersValidator responseHeadersValidator;
//ensure we get all required resources in lock-step
synchronized (this) {
inputBody = inputRequestBodies.poll();
inputHeaders = inputRequestHeaders.poll();
responseBodyValidator = responseBodyValidators.poll();
responseHeadersValidator = responseHeadersValidators.poll();
}
final Endpoint endpoint = template.getCamelContext().getEndpoint(getEndpointUri());
overrideEndpoint(endpoint);
Exchange response;
if (inputBody != null && inputHeaders != null)
response = template.request(endpoint, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody(inputBody.getValue());
exchange.getIn().setHeaders(inputHeaders.getValue());
logger.trace("Sending to endpoint: {} headers: {}, body: {}", new String[]{endpoint.toString(),
HeadersTestResource.formatHeaders(inputHeaders.getValue()),
exchange.getIn().getBody(String.class)});
}
});
else if (inputHeaders != null)
response = template.request(endpoint, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody("");
exchange.getIn().setHeaders(inputHeaders.getValue());
logger.trace("Sending to endpoint: {} headers: {}, body: {}", new String[]{endpoint.toString(),
HeadersTestResource.formatHeaders(inputHeaders.getValue()),
exchange.getIn().getBody(String.class)});
}
});
else if (inputBody != null)
response = template.request(endpoint, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody(inputBody.getValue());
logger.trace("Sending to endpoint: {} body: {}", new String[]{endpoint.toString(),
exchange.getIn().getBody(String.class)});
}
});
else
response = template.request(endpoint, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody("");
logger.trace("Sending to endpoint: {} body: {}", new String[]{endpoint.toString(),
exchange.getIn().getBody(String.class)});
}
});
//Put the out message into in for consistency during validation
ExchangeHelper.prepareOutToIn(response);
Exception e = response.getException();
logger.trace("Synchronous response headers: {}, body: {}",
HeadersTestResource.formatHeaders(response.getIn().getHeaders()), response.getIn().getBody(String.class));
boolean validResponse = ((responseBodyValidator == null || responseBodyValidator.validate(response))
&& (responseHeadersValidator == null || responseHeadersValidator.validate(response)));
if (!expectsExceptionResponse && e != null) {
logger.warn("An unexpected exception was encountered", e);
return false;
}
return validResponse;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static class Builder extends OrchestratedTestSpecification.AbstractBuilder<SyncOrchestratedTestSpecification, Builder> {
private Queue<TestResource> inputRequestBodies = new LinkedList<>();
private Queue<TestResource<Map<String, Object>>> inputRequestHeaders = new LinkedList<>();
private Queue<Validator> responseBodyValidators = new LinkedList<>();
private Queue<HeadersValidator> responseHeadersValidators = new LinkedList<>();
private boolean expectsExceptionResponse;
public Builder(String description, String endpointUri) {
super(description, endpointUri);
}
protected Builder self() {
return this;
}
public Builder requestBody(TestResource... resources) {
Collections.addAll(inputRequestBodies, resources);
return self();
}
public Builder requestBody(Enumeration<TestResource> resources) {
while (resources.hasMoreElements()) {
inputRequestBodies.add(resources.nextElement());
}
return self();
}
@SafeVarargs
public final Builder requestHeaders(TestResource<Map<String, Object>>... resources) {
Collections.addAll(inputRequestHeaders, resources);
return self();
}
public Builder requestHeaders(Enumeration<TestResource<Map<String, Object>>> resources) {
while (resources.hasMoreElements()) {
inputRequestHeaders.add(resources.nextElement());
}
return self();
}
public Builder expectedResponseBody(Validator... validators) {
Collections.addAll(this.responseBodyValidators, validators);
return self();
}
public Builder expectedResponseBody(Enumeration<Validator> validators) {
while (validators.hasMoreElements()) {
responseBodyValidators.add(validators.nextElement());
}
return self();
}
public Builder expectedResponseHeaders(HeadersValidator... responseHeadersValidators) {
Collections.addAll(this.responseHeadersValidators, responseHeadersValidators);
return self();
}
@SafeVarargs
public final Builder expectedResponseHeaders(TestResource<Map<String, Object>>... resources) {
for (TestResource<Map<String, Object>> resource : resources) {
this.responseHeadersValidators.add(new HeadersValidator(resource));
}
return self();
}
public Builder expectedResponseHeaders(Enumeration<HeadersValidator> resources) {
while (resources.hasMoreElements()) {
this.responseHeadersValidators.add(resources.nextElement());
}
return self();
}
public Builder expectedResponse(Validator... validators) {
return this.expectedResponseBody(validators);
}
public Builder expectedResponse(Enumeration<Validator> validators) {
return this.expectedResponseBody(validators);
}
public Builder expectsExceptionResponse() {
this.expectsExceptionResponse = true;
return self();
}
protected SyncOrchestratedTestSpecification buildInternal() {
SyncOrchestratedTestSpecification specification = new SyncOrchestratedTestSpecification(this);
logger.info("The endpoint {} will be sending {} request message bodies, {} request message headers, " +
"{} expected response body validators, and {} expected response headers validators",
new Object[]{specification.getEndpointUri(), inputRequestBodies.size(), inputRequestHeaders.size(),
responseBodyValidators.size(), responseHeadersValidators.size()});
return specification;
}
}
protected SyncOrchestratedTestSpecification(Builder builder) {
super(builder);
this.inputRequestBodies = builder.inputRequestBodies;
this.inputRequestHeaders = builder.inputRequestHeaders;
this.responseBodyValidators = builder.responseBodyValidators;
this.responseHeadersValidators = builder.responseHeadersValidators;
this.expectsExceptionResponse = builder.expectsExceptionResponse;
}
}
|
src/main/java/nz/ac/auckland/integration/testing/specification/SyncOrchestratedTestSpecification.java
|
package nz.ac.auckland.integration.testing.specification;
import nz.ac.auckland.integration.testing.resource.HeadersTestResource;
import nz.ac.auckland.integration.testing.resource.TestResource;
import nz.ac.auckland.integration.testing.validator.HeadersValidator;
import nz.ac.auckland.integration.testing.validator.Validator;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.util.ExchangeHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* A synchronous orchestrated test makes a call to a target endpoint which provides a response. During
* the request process the target may make a number of call outs to expectations which need to be satisfied.
* The response body from the target will also be validated against the expected response body.
*
* @author David MacDonald <[email protected]>
*/
public class SyncOrchestratedTestSpecification extends OrchestratedTestSpecification {
private static final Logger logger = LoggerFactory.getLogger(SyncOrchestratedTestSpecification.class);
private Queue<TestResource> inputRequestBodies;
private Queue<TestResource<Map<String, Object>>> inputRequestHeaders;
private Queue<Validator> responseBodyValidators;
private Queue<HeadersValidator> responseHeadersValidators;
private boolean expectsExceptionResponse = false;
/**
* @param template An Apache Camel template that can be used to send messages to a target endpoint
* @return true if the message is successfully sent the the response body is as expected
*/
protected boolean sendInputInternal(ProducerTemplate template) {
try {
final TestResource inputBody;
final TestResource<Map<String, Object>> inputHeaders;
final Validator responseBodyValidator;
final HeadersValidator responseHeadersValidator;
//ensure we get all required resources in lock-step
synchronized (this) {
inputBody = inputRequestBodies.poll();
inputHeaders = inputRequestHeaders.poll();
responseBodyValidator = responseBodyValidators.poll();
responseHeadersValidator = responseHeadersValidators.poll();
}
final Endpoint endpoint = template.getCamelContext().getEndpoint(getEndpointUri());
overrideEndpoint(endpoint);
Exchange response;
if (inputBody != null && inputHeaders != null)
response = template.request(endpoint, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody(inputBody.getValue());
exchange.getIn().setHeaders(inputHeaders.getValue());
logger.trace("Sending to endpoint: {} headers: {}, body: {}", new String[]{endpoint.toString(),
HeadersTestResource.formatHeaders(inputHeaders.getValue()),
exchange.getIn().getBody(String.class)});
}
});
else if (inputHeaders != null)
response = template.request(endpoint, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody("");
exchange.getIn().setHeaders(inputHeaders.getValue());
logger.trace("Sending to endpoint: {} headers: {}, body: {}", new String[]{endpoint.toString(),
HeadersTestResource.formatHeaders(inputHeaders.getValue()),
exchange.getIn().getBody(String.class)});
}
});
else if (inputBody != null)
response = template.request(endpoint, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody(inputBody.getValue());
logger.trace("Sending to endpoint: {} body: {}", new String[]{endpoint.toString(),
exchange.getIn().getBody(String.class)});
}
});
else
response = template.request(endpoint, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody("");
logger.trace("Sending to endpoint: {} body: {}", new String[]{endpoint.toString(),
exchange.getIn().getBody(String.class)});
}
});
//Put the out message into in for consistency during validation
ExchangeHelper.prepareOutToIn(response);
Exception e = response.getException();
logger.trace("Synchronous response headers: {}, body: {}",
HeadersTestResource.formatHeaders(response.getIn().getHeaders()), response.getIn().getBody(String.class));
boolean validResponse = ((responseBodyValidator == null || responseBodyValidator.validate(response))
&& (responseHeadersValidator == null || responseHeadersValidator.validate(response)));
if (!expectsExceptionResponse && e != null) {
logger.warn("An unexpected exception was encountered", e);
return false;
}
return validResponse;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static class Builder extends OrchestratedTestSpecification.AbstractBuilder<SyncOrchestratedTestSpecification, Builder> {
private Queue<TestResource> inputRequestBodies = new LinkedList<>();
private Queue<TestResource<Map<String, Object>>> inputRequestHeaders = new LinkedList<>();
private Queue<Validator> responseBodyValidators = new LinkedList<>();
private Queue<HeadersValidator> responseHeadersValidators = new LinkedList<>();
private boolean expectsExceptionResponse;
public Builder(String description, String endpointUri) {
super(description, endpointUri);
}
protected Builder self() {
return this;
}
public Builder requestBody(TestResource... resources) {
Collections.addAll(inputRequestBodies, resources);
return self();
}
public Builder requestBody(Enumeration<TestResource> resources) {
while (resources.hasMoreElements()) {
inputRequestBodies.add(resources.nextElement());
}
return self();
}
@SafeVarargs
public final Builder requestHeaders(TestResource<Map<String, Object>>... resources) {
Collections.addAll(inputRequestHeaders, resources);
return self();
}
public Builder requestHeaders(Enumeration<TestResource<Map<String, Object>>> resources) {
while (resources.hasMoreElements()) {
inputRequestHeaders.add(resources.nextElement());
}
return self();
}
public Builder expectedResponseBody(Validator... validators) {
Collections.addAll(this.responseBodyValidators, validators);
return self();
}
public Builder expectedResponseBody(Enumeration<Validator> validators) {
while (validators.hasMoreElements()) {
responseBodyValidators.add(validators.nextElement());
}
return self();
}
public Builder expectedResponseHeaders(HeadersValidator... responseHeadersValidators) {
Collections.addAll(this.responseHeadersValidators, responseHeadersValidators);
return self();
}
@SafeVarargs
public final Builder expectedResponseHeaders(TestResource<Map<String, Object>>... resources) {
for (TestResource<Map<String, Object>> resource : resources) {
this.responseHeadersValidators.add(new HeadersValidator(resource));
}
return self();
}
public Builder expectedResponseHeaders(Enumeration<HeadersValidator> resources) {
while (resources.hasMoreElements()) {
this.responseHeadersValidators.add(resources.nextElement());
}
return self();
}
public Builder expectedResponse(Validator... validators) {
return this.expectedResponseBody(validators);
}
public Builder expectedResponse(Enumeration<Validator> validators) {
return this.expectedResponseBody(validators);
}
public Builder expectsExceptionResponse() {
this.expectsExceptionResponse = true;
return self();
}
protected SyncOrchestratedTestSpecification buildInternal() {
SyncOrchestratedTestSpecification specification = new SyncOrchestratedTestSpecification(this);
logger.info("The endpoint {} will be sending {} request message bodies, {} request message headers, " +
"{} expected response body validators, and {} expected response headers validators",
new Object[]{specification.getEndpointUri(), inputRequestBodies.size(), inputRequestHeaders.size(),
responseBodyValidators.size(), responseHeadersValidators.size()});
return specification;
}
}
protected SyncOrchestratedTestSpecification(Builder builder) {
super(builder);
this.inputRequestBodies = builder.inputRequestBodies;
this.inputRequestHeaders = builder.inputRequestHeaders;
this.responseBodyValidators = builder.responseBodyValidators;
this.responseHeadersValidators = builder.responseHeadersValidators;
}
}
|
fixed bug with expecting exception response
|
src/main/java/nz/ac/auckland/integration/testing/specification/SyncOrchestratedTestSpecification.java
|
fixed bug with expecting exception response
|
<ide><path>rc/main/java/nz/ac/auckland/integration/testing/specification/SyncOrchestratedTestSpecification.java
<ide> this.inputRequestHeaders = builder.inputRequestHeaders;
<ide> this.responseBodyValidators = builder.responseBodyValidators;
<ide> this.responseHeadersValidators = builder.responseHeadersValidators;
<add> this.expectsExceptionResponse = builder.expectsExceptionResponse;
<ide> }
<ide>
<ide> }
|
|
Java
|
apache-2.0
|
532807d14345c3281b4c1bf91529bd1b8bc0e410
| 0 |
glahiru/airavata,dogless/airavata,machristie/airavata,anujbhan/airavata,apache/airavata,machristie/airavata,jjj117/airavata,anujbhan/airavata,apache/airavata,dogless/airavata,gouravshenoy/airavata,jjj117/airavata,gouravshenoy/airavata,apache/airavata,jjj117/airavata,machristie/airavata,apache/airavata,anujbhan/airavata,apache/airavata,glahiru/airavata,dogless/airavata,apache/airavata,hasinitg/airavata,hasinitg/airavata,gouravshenoy/airavata,machristie/airavata,glahiru/airavata,gouravshenoy/airavata,gouravshenoy/airavata,jjj117/airavata,apache/airavata,machristie/airavata,hasinitg/airavata,gouravshenoy/airavata,glahiru/airavata,machristie/airavata,anujbhan/airavata,hasinitg/airavata,apache/airavata,gouravshenoy/airavata,jjj117/airavata,machristie/airavata,glahiru/airavata,dogless/airavata,dogless/airavata,hasinitg/airavata,jjj117/airavata,anujbhan/airavata,dogless/airavata,anujbhan/airavata,hasinitg/airavata,anujbhan/airavata
|
/*
*
* 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.airavata.services.gfac.axis2;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.jcr.Credentials;
import javax.jcr.Repository;
import javax.jcr.RepositoryFactory;
import javax.jcr.SimpleCredentials;
import javax.security.auth.login.Configuration;
import org.apache.airavata.core.gfac.services.GenericService;
import org.apache.airavata.registry.api.Registry;
import org.apache.airavata.registry.api.impl.JCRRegistry;
import org.apache.airavata.services.gfac.axis2.handlers.AmazonSecurityHandler;
import org.apache.airavata.services.gfac.axis2.handlers.MyProxySecurityHandler;
import org.apache.airavata.services.gfac.axis2.util.WSConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.Phase;
import org.apache.axis2.engine.ServiceLifeCycle;
import org.apache.axis2.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GFacService extends Thread implements ServiceLifeCycle {
private static final Logger log = LoggerFactory.getLogger(GFacService.class);
public static final String CONFIGURATION_CONTEXT_REGISTRY = "registry";
public static final String SECURITY_CONTEXT = "security_context";
public static final String REPOSITORY_PROPERTIES = "repository.properties";
/*
* Properties for JCR
*/
public static final String JCR_CLASS = "jcr.class";
public static final String JCR_USER = "jcr.user";
public static final String JCR_PASS = "jcr.pass";
public static GenericService service;
public static final int GFAC_URL_UPDATE_INTERVAL = 1000 * 60 * 60 * 3;
public ConfigurationContext context;
public static final String GFAC_URL = "GFacURL";
public void startUp(ConfigurationContext configctx, AxisService service){
this.context = configctx;
AxisConfiguration config = null;
configctx.getAxisConfiguration().getTransportsIn().get("http").getParameter("port");
List<Phase> phases = null;
config = service.getAxisConfiguration();
phases = config.getInFlowPhases();
initializeRepository(configctx);
for (Iterator<Phase> iterator = phases.iterator(); iterator.hasNext();) {
Phase phase = (Phase) iterator.next();
if ("Security".equals(phase.getPhaseName())) {
phase.addHandler(new MyProxySecurityHandler());
phase.addHandler(new AmazonSecurityHandler());
return;
}
}
}
private void initializeRepository(ConfigurationContext context) {
Properties properties = new Properties();
try {
URL url = this.getClass().getClassLoader().getResource(REPOSITORY_PROPERTIES);
properties.load(url.openStream());
Map<String, String> map = new HashMap<String, String>((Map) properties);
Class registryRepositoryFactory = Class.forName(map.get(JCR_CLASS));
Constructor c = registryRepositoryFactory.getConstructor();
RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance();
Repository repository = repositoryFactory.getRepository(map);
Credentials credentials = new SimpleCredentials(map.get(JCR_USER), map.get(JCR_PASS).toCharArray());
Registry registry = new JCRRegistry(repository, credentials);
String localAddress = Utils.getIpAddress(context.getAxisConfiguration());
String port = (String) context.getAxisConfiguration().getTransportsIn().get("http").getParameter("port").getValue();
localAddress = "http://" + localAddress + ":" + port;
localAddress = localAddress + "/" +
context.getContextRoot() + "/" + context.getServicePath() + "/" + WSConstants.GFAC_SERVICE_NAME;
System.out.println(localAddress);
context.setProperty(CONFIGURATION_CONTEXT_REGISTRY, registry);
context.setProperty(GFAC_URL,localAddress);
this.start();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public void shutDown(ConfigurationContext configctx, AxisService service) {
Registry registry = (JCRRegistry) configctx.getProperty(CONFIGURATION_CONTEXT_REGISTRY);
String gfacURL = (String) configctx.getProperty(GFAC_URL);
registry.deleteGFacDescriptor(gfacURL);
try {
this.join();
} catch (InterruptedException e) {
log.info("GFacURL update thread is interrupted");
}
}
public void run() {
try {
while (true) {
Registry registry = (Registry) this.context.getProperty(CONFIGURATION_CONTEXT_REGISTRY);
String localAddress = (String) this.context.getProperty(GFAC_URL);
registry.saveGFacDescriptor(localAddress);
log.info("Updated the GFac URL in to Repository");
Thread.sleep(GFAC_URL_UPDATE_INTERVAL);
}
} catch (InterruptedException e) {
log.info("GFacURL update thread is interrupted");
}
}
}
|
modules/gfac-axis2/src/main/java/org/apache/airavata/services/gfac/axis2/GFacService.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.airavata.services.gfac.axis2;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.jcr.Credentials;
import javax.jcr.Repository;
import javax.jcr.RepositoryFactory;
import javax.jcr.SimpleCredentials;
import org.apache.airavata.core.gfac.services.GenericService;
import org.apache.airavata.registry.api.Registry;
import org.apache.airavata.registry.api.impl.JCRRegistry;
import org.apache.airavata.services.gfac.axis2.handlers.AmazonSecurityHandler;
import org.apache.airavata.services.gfac.axis2.handlers.MyProxySecurityHandler;
import org.apache.airavata.services.gfac.axis2.util.WSConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.Phase;
import org.apache.axis2.engine.ServiceLifeCycle;
import org.apache.axis2.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GFacService implements ServiceLifeCycle {
private static final Logger log = LoggerFactory.getLogger(GFacService.class);
public static final String CONFIGURATION_CONTEXT_REGISTRY = "registry";
public static final String SECURITY_CONTEXT = "security_context";
public static final String REPOSITORY_PROPERTIES = "repository.properties";
/*
* Properties for JCR
*/
public static final String JCR_CLASS = "jcr.class";
public static final String JCR_USER = "jcr.user";
public static final String JCR_PASS = "jcr.pass";
public static GenericService service;
public static final String GFAC_URL = "GFacURL";
public void startUp(ConfigurationContext configctx, AxisService service){
AxisConfiguration config = null;
configctx.getAxisConfiguration().getTransportsIn().get("http").getParameter("port");
List<Phase> phases = null;
config = service.getAxisConfiguration();
phases = config.getInFlowPhases();
initializeRepository(configctx);
for (Iterator<Phase> iterator = phases.iterator(); iterator.hasNext();) {
Phase phase = (Phase) iterator.next();
if ("Security".equals(phase.getPhaseName())) {
phase.addHandler(new MyProxySecurityHandler());
phase.addHandler(new AmazonSecurityHandler());
return;
}
}
}
private void initializeRepository(ConfigurationContext context) {
Properties properties = new Properties();
try {
URL url = this.getClass().getClassLoader().getResource(REPOSITORY_PROPERTIES);
properties.load(url.openStream());
Map<String, String> map = new HashMap<String, String>((Map) properties);
Class registryRepositoryFactory = Class.forName(map.get(JCR_CLASS));
Constructor c = registryRepositoryFactory.getConstructor();
RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance();
Repository repository = repositoryFactory.getRepository(map);
Credentials credentials = new SimpleCredentials(map.get(JCR_USER), map.get(JCR_PASS).toCharArray());
Registry registry = new JCRRegistry(repository, credentials);
String localAddress = Utils.getIpAddress(context.getAxisConfiguration());
String port = (String) context.getAxisConfiguration().getTransportsIn().get("http").getParameter("port").getValue();
localAddress = "http://" + localAddress + ":" + port;
localAddress = localAddress + "/" +
context.getContextRoot() + "/" + context.getServicePath() + "/" + WSConstants.GFAC_SERVICE_NAME;
System.out.println(localAddress);
registry.saveGFacDescriptor(localAddress);
context.setProperty(CONFIGURATION_CONTEXT_REGISTRY, registry);
context.setProperty(GFAC_URL,localAddress);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public void shutDown(ConfigurationContext configctx, AxisService service) {
Registry registry = (JCRRegistry) configctx.getProperty(CONFIGURATION_CONTEXT_REGISTRY);
String gfacURL = (String) configctx.getProperty(GFAC_URL);
registry.deleteGFacDescriptor(gfacURL);
}
}
|
Update the imlementation for https://issues.apache.org/jira/browse/AIRAVATA-116.
git-svn-id: 64c7115bac0e45f25b6ef7317621bf38f6d5f89e@1174286 13f79535-47bb-0310-9956-ffa450edef68
|
modules/gfac-axis2/src/main/java/org/apache/airavata/services/gfac/axis2/GFacService.java
|
Update the imlementation for https://issues.apache.org/jira/browse/AIRAVATA-116.
|
<ide><path>odules/gfac-axis2/src/main/java/org/apache/airavata/services/gfac/axis2/GFacService.java
<ide> import javax.jcr.Repository;
<ide> import javax.jcr.RepositoryFactory;
<ide> import javax.jcr.SimpleCredentials;
<add>import javax.security.auth.login.Configuration;
<ide>
<ide> import org.apache.airavata.core.gfac.services.GenericService;
<ide> import org.apache.airavata.registry.api.Registry;
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<del>public class GFacService implements ServiceLifeCycle {
<add>public class GFacService extends Thread implements ServiceLifeCycle {
<ide>
<ide> private static final Logger log = LoggerFactory.getLogger(GFacService.class);
<ide>
<ide> public static final String JCR_PASS = "jcr.pass";
<ide>
<ide> public static GenericService service;
<add> public static final int GFAC_URL_UPDATE_INTERVAL = 1000 * 60 * 60 * 3;
<add> public ConfigurationContext context;
<ide> public static final String GFAC_URL = "GFacURL";
<ide>
<ide> public void startUp(ConfigurationContext configctx, AxisService service){
<add> this.context = configctx;
<ide> AxisConfiguration config = null;
<ide> configctx.getAxisConfiguration().getTransportsIn().get("http").getParameter("port");
<ide> List<Phase> phases = null;
<ide> RepositoryFactory repositoryFactory = (RepositoryFactory) c.newInstance();
<ide> Repository repository = repositoryFactory.getRepository(map);
<ide> Credentials credentials = new SimpleCredentials(map.get(JCR_USER), map.get(JCR_PASS).toCharArray());
<add>
<ide> Registry registry = new JCRRegistry(repository, credentials);
<ide> String localAddress = Utils.getIpAddress(context.getAxisConfiguration());
<ide> String port = (String) context.getAxisConfiguration().getTransportsIn().get("http").getParameter("port").getValue();
<ide> localAddress = localAddress + "/" +
<ide> context.getContextRoot() + "/" + context.getServicePath() + "/" + WSConstants.GFAC_SERVICE_NAME;
<ide> System.out.println(localAddress);
<del> registry.saveGFacDescriptor(localAddress);
<ide> context.setProperty(CONFIGURATION_CONTEXT_REGISTRY, registry);
<ide> context.setProperty(GFAC_URL,localAddress);
<add> this.start();
<ide> } catch (Exception e) {
<ide> log.error(e.getMessage(), e);
<ide> }
<ide> Registry registry = (JCRRegistry) configctx.getProperty(CONFIGURATION_CONTEXT_REGISTRY);
<ide> String gfacURL = (String) configctx.getProperty(GFAC_URL);
<ide> registry.deleteGFacDescriptor(gfacURL);
<add> try {
<add> this.join();
<add> } catch (InterruptedException e) {
<add> log.info("GFacURL update thread is interrupted");
<add> }
<add> }
<add>
<add> public void run() {
<add> try {
<add> while (true) {
<add> Registry registry = (Registry) this.context.getProperty(CONFIGURATION_CONTEXT_REGISTRY);
<add> String localAddress = (String) this.context.getProperty(GFAC_URL);
<add> registry.saveGFacDescriptor(localAddress);
<add> log.info("Updated the GFac URL in to Repository");
<add> Thread.sleep(GFAC_URL_UPDATE_INTERVAL);
<add> }
<add> } catch (InterruptedException e) {
<add> log.info("GFacURL update thread is interrupted");
<add> }
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
1af96b5fe69e5c575938b66ca1c65a06ccc2121b
| 0 |
JetBrains/teamcity-deployer-plugin,JetBrains/teamcity-deployer-plugin
|
package jetbrains.buildServer.deployer.server.converter;
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.deployer.common.FTPRunnerConstants;
import jetbrains.buildServer.deployer.common.SSHRunnerConstants;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.serverSide.BuildServerAdapter;
import jetbrains.buildServer.serverSide.SBuildRunnerDescriptor;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.serverSide.SBuildType;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Nikita.Skvortsov
* date: 29.07.13.
*/
public class DeployerSettingsConverter extends BuildServerAdapter {
private final SBuildServer myServer;
public DeployerSettingsConverter(@NotNull SBuildServer server) {
myServer = server;
myServer.addListener(this);
}
@Override
public void buildTypeRegistered(SBuildType buildType) {
boolean persistBuildType = false;
for (SBuildRunnerDescriptor descriptor : buildType.getBuildRunners()) {
boolean runnerUpdated = false;
final String runnerType = descriptor.getType();
final Map<String, String> newRunnerParams = new HashMap<String, String>(descriptor.getParameters());
final String plainPassword = newRunnerParams.get(DeployerRunnerConstants.PARAM_PLAIN_PASSWORD);
if (plainPassword != null) {
runnerUpdated = true;
Loggers.SERVER.debug("Scrambling password for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
newRunnerParams.remove(DeployerRunnerConstants.PARAM_PLAIN_PASSWORD);
newRunnerParams.put(DeployerRunnerConstants.PARAM_PASSWORD, plainPassword);
}
if (DeployerRunnerConstants.SSH_RUN_TYPE.equals(runnerType) ||
SSHRunnerConstants.SSH_EXEC_RUN_TYPE.equals(runnerType)) {
final String sshAuthMethod = newRunnerParams.get(SSHRunnerConstants.PARAM_AUTH_METHOD);
if (StringUtil.isEmpty(sshAuthMethod)) {
runnerUpdated = true;
Loggers.SERVER.debug("Setting default (username password) ssh authentication method for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
newRunnerParams.put(SSHRunnerConstants.PARAM_AUTH_METHOD, SSHRunnerConstants.AUTH_METHOD_USERNAME_PWD);
}
if (SSHRunnerConstants.SSH_EXEC_RUN_TYPE.equals(runnerType)) {
final String oldUsername = newRunnerParams.get(SSHRunnerConstants.PARAM_USERNAME);
final String oldPassword = newRunnerParams.get(SSHRunnerConstants.PARAM_PASSWORD);
final String oldHost = newRunnerParams.get(SSHRunnerConstants.PARAM_HOST);
if (StringUtil.isNotEmpty(oldUsername)) {
runnerUpdated = true;
newRunnerParams.remove(SSHRunnerConstants.PARAM_USERNAME);
newRunnerParams.put(DeployerRunnerConstants.PARAM_USERNAME, oldUsername);
}
if (StringUtil.isNotEmpty(oldPassword)) {
runnerUpdated = true;
newRunnerParams.remove(SSHRunnerConstants.PARAM_PASSWORD);
newRunnerParams.put(DeployerRunnerConstants.PARAM_PASSWORD, oldPassword);
}
if (StringUtil.isNotEmpty(oldHost)) {
runnerUpdated = true;
newRunnerParams.remove(SSHRunnerConstants.PARAM_HOST);
newRunnerParams.put(DeployerRunnerConstants.PARAM_TARGET_URL, oldHost);
}
}
}
if (DeployerRunnerConstants.FTP_RUN_TYPE.equals(runnerType)) {
final String ftpAuthMethod = newRunnerParams.get(FTPRunnerConstants.PARAM_AUTH_METHOD);
if (StringUtil.isEmpty(ftpAuthMethod)) {
runnerUpdated = true;
Loggers.SERVER.debug("Setting ftp auth authentication method for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
final String username = newRunnerParams.get(DeployerRunnerConstants.PARAM_USERNAME);
if (StringUtil.isEmpty(username)) {
newRunnerParams.put(FTPRunnerConstants.PARAM_AUTH_METHOD, FTPRunnerConstants.AUTH_METHOD_ANONYMOUS);
} else {
newRunnerParams.put(FTPRunnerConstants.PARAM_AUTH_METHOD, FTPRunnerConstants.AUTH_METHOD_USER_PWD);
}
}
}
if (DeployerRunnerConstants.SMB_RUN_TYPE.equals(runnerType)) {
final String domain = newRunnerParams.get(DeployerRunnerConstants.PARAM_DOMAIN);
if (StringUtil.isNotEmpty(domain)) {
runnerUpdated = true;
newRunnerParams.remove(DeployerRunnerConstants.PARAM_DOMAIN);
final String username = newRunnerParams.get(DeployerRunnerConstants.PARAM_USERNAME);
newRunnerParams.put(DeployerRunnerConstants.PARAM_USERNAME, domain + "\\" + username);
}
}
if (runnerUpdated) {
persistBuildType = true;
buildType.updateBuildRunner(descriptor.getId(), descriptor.getName(), runnerType, newRunnerParams);
}
}
if (persistBuildType) {
buildType.persist();
}
}
@Override
public void serverStartup() {
myServer.removeListener(this);
Loggers.SERVER.debug("Server started up, will not convert passwords in configurations from now on.");
}
}
|
deploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/converter/DeployerSettingsConverter.java
|
package jetbrains.buildServer.deployer.server.converter;
import jetbrains.buildServer.deployer.common.DeployerRunnerConstants;
import jetbrains.buildServer.deployer.common.FTPRunnerConstants;
import jetbrains.buildServer.deployer.common.SSHRunnerConstants;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.serverSide.BuildServerAdapter;
import jetbrains.buildServer.serverSide.SBuildRunnerDescriptor;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.serverSide.SBuildType;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Nikita.Skvortsov
* date: 29.07.13.
*/
public class DeployerSettingsConverter extends BuildServerAdapter {
private final SBuildServer myServer;
public DeployerSettingsConverter(@NotNull SBuildServer server) {
myServer = server;
myServer.addListener(this);
}
@Override
public void buildTypeRegistered(SBuildType buildType) {
boolean persistBuildType = false;
for (SBuildRunnerDescriptor descriptor : buildType.getBuildRunners()) {
final String runnerType = descriptor.getType();
final Map<String, String> newRunnerParams = new HashMap<String, String>(descriptor.getParameters());
final String plainPassword = newRunnerParams.get(DeployerRunnerConstants.PARAM_PLAIN_PASSWORD);
if (plainPassword != null) {
persistBuildType = true;
Loggers.SERVER.debug("Scrambling password for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
newRunnerParams.remove(DeployerRunnerConstants.PARAM_PLAIN_PASSWORD);
newRunnerParams.put(DeployerRunnerConstants.PARAM_PASSWORD, plainPassword);
}
if (DeployerRunnerConstants.SSH_RUN_TYPE.equals(runnerType) ||
SSHRunnerConstants.SSH_EXEC_RUN_TYPE.equals(runnerType)) {
final String sshAuthMethod = newRunnerParams.get(SSHRunnerConstants.PARAM_AUTH_METHOD);
if (StringUtil.isEmpty(sshAuthMethod)) {
persistBuildType = true;
Loggers.SERVER.debug("Setting default (username password) ssh authentication method for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
newRunnerParams.put(SSHRunnerConstants.PARAM_AUTH_METHOD, SSHRunnerConstants.AUTH_METHOD_USERNAME_PWD);
}
if (SSHRunnerConstants.SSH_EXEC_RUN_TYPE.equals(runnerType)) {
final String oldUsername = newRunnerParams.get(SSHRunnerConstants.PARAM_USERNAME);
final String oldPassword = newRunnerParams.get(SSHRunnerConstants.PARAM_PASSWORD);
final String oldHost = newRunnerParams.get(SSHRunnerConstants.PARAM_HOST);
if (StringUtil.isNotEmpty(oldUsername)) {
persistBuildType = true;
newRunnerParams.remove(SSHRunnerConstants.PARAM_USERNAME);
newRunnerParams.put(DeployerRunnerConstants.PARAM_USERNAME, oldUsername);
}
if (StringUtil.isNotEmpty(oldPassword)) {
persistBuildType = true;
newRunnerParams.remove(SSHRunnerConstants.PARAM_PASSWORD);
newRunnerParams.put(DeployerRunnerConstants.PARAM_PASSWORD, oldPassword);
}
if (StringUtil.isNotEmpty(oldHost)) {
persistBuildType = true;
newRunnerParams.remove(SSHRunnerConstants.PARAM_HOST);
newRunnerParams.put(DeployerRunnerConstants.PARAM_TARGET_URL, oldHost);
}
}
}
if (DeployerRunnerConstants.FTP_RUN_TYPE.equals(runnerType)) {
final String ftpAuthMethod = newRunnerParams.get(FTPRunnerConstants.PARAM_AUTH_METHOD);
if (StringUtil.isEmpty(ftpAuthMethod)) {
persistBuildType = true;
Loggers.SERVER.debug("Setting ftp auth authentication method for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
final String username = newRunnerParams.get(DeployerRunnerConstants.PARAM_USERNAME);
if (StringUtil.isEmpty(username)) {
newRunnerParams.put(FTPRunnerConstants.PARAM_AUTH_METHOD, FTPRunnerConstants.AUTH_METHOD_ANONYMOUS);
} else {
newRunnerParams.put(FTPRunnerConstants.PARAM_AUTH_METHOD, FTPRunnerConstants.AUTH_METHOD_USER_PWD);
}
}
}
if (DeployerRunnerConstants.SMB_RUN_TYPE.equals(runnerType)) {
final String domain = newRunnerParams.get(DeployerRunnerConstants.PARAM_DOMAIN);
if (StringUtil.isNotEmpty(domain)) {
persistBuildType = true;
newRunnerParams.remove(DeployerRunnerConstants.PARAM_DOMAIN);
final String username = newRunnerParams.get(DeployerRunnerConstants.PARAM_USERNAME);
newRunnerParams.put(DeployerRunnerConstants.PARAM_USERNAME, domain + "\\" + username);
}
}
buildType.updateBuildRunner(descriptor.getId(), descriptor.getName(), runnerType, newRunnerParams);
}
if (persistBuildType) {
buildType.persist();
}
}
@Override
public void serverStartup() {
myServer.removeListener(this);
Loggers.SERVER.debug("Server started up, will not convert passwords in configurations from now on.");
}
}
|
Always persist updated buildType
In TC 10.0.3 update of a build runner marks buildType/template as
edited. TeamCity settings changes from VCS are not applied unless edited
entity is persisted, in order to not revert changes made in UI.
|
deploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/converter/DeployerSettingsConverter.java
|
Always persist updated buildType
|
<ide><path>eploy-runner-server/src/main/java/jetbrains/buildServer/deployer/server/converter/DeployerSettingsConverter.java
<ide> public void buildTypeRegistered(SBuildType buildType) {
<ide> boolean persistBuildType = false;
<ide> for (SBuildRunnerDescriptor descriptor : buildType.getBuildRunners()) {
<add> boolean runnerUpdated = false;
<ide> final String runnerType = descriptor.getType();
<ide> final Map<String, String> newRunnerParams = new HashMap<String, String>(descriptor.getParameters());
<ide>
<ide> final String plainPassword = newRunnerParams.get(DeployerRunnerConstants.PARAM_PLAIN_PASSWORD);
<ide> if (plainPassword != null) {
<del> persistBuildType = true;
<add> runnerUpdated = true;
<ide> Loggers.SERVER.debug("Scrambling password for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
<ide> newRunnerParams.remove(DeployerRunnerConstants.PARAM_PLAIN_PASSWORD);
<ide> newRunnerParams.put(DeployerRunnerConstants.PARAM_PASSWORD, plainPassword);
<ide> SSHRunnerConstants.SSH_EXEC_RUN_TYPE.equals(runnerType)) {
<ide> final String sshAuthMethod = newRunnerParams.get(SSHRunnerConstants.PARAM_AUTH_METHOD);
<ide> if (StringUtil.isEmpty(sshAuthMethod)) {
<del> persistBuildType = true;
<add> runnerUpdated = true;
<ide> Loggers.SERVER.debug("Setting default (username password) ssh authentication method for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
<ide> newRunnerParams.put(SSHRunnerConstants.PARAM_AUTH_METHOD, SSHRunnerConstants.AUTH_METHOD_USERNAME_PWD);
<ide> }
<ide> final String oldPassword = newRunnerParams.get(SSHRunnerConstants.PARAM_PASSWORD);
<ide> final String oldHost = newRunnerParams.get(SSHRunnerConstants.PARAM_HOST);
<ide> if (StringUtil.isNotEmpty(oldUsername)) {
<del> persistBuildType = true;
<add> runnerUpdated = true;
<ide> newRunnerParams.remove(SSHRunnerConstants.PARAM_USERNAME);
<ide> newRunnerParams.put(DeployerRunnerConstants.PARAM_USERNAME, oldUsername);
<ide> }
<ide> if (StringUtil.isNotEmpty(oldPassword)) {
<del> persistBuildType = true;
<add> runnerUpdated = true;
<ide> newRunnerParams.remove(SSHRunnerConstants.PARAM_PASSWORD);
<ide> newRunnerParams.put(DeployerRunnerConstants.PARAM_PASSWORD, oldPassword);
<ide> }
<ide> if (StringUtil.isNotEmpty(oldHost)) {
<del> persistBuildType = true;
<add> runnerUpdated = true;
<ide> newRunnerParams.remove(SSHRunnerConstants.PARAM_HOST);
<ide> newRunnerParams.put(DeployerRunnerConstants.PARAM_TARGET_URL, oldHost);
<ide> }
<ide> if (DeployerRunnerConstants.FTP_RUN_TYPE.equals(runnerType)) {
<ide> final String ftpAuthMethod = newRunnerParams.get(FTPRunnerConstants.PARAM_AUTH_METHOD);
<ide> if (StringUtil.isEmpty(ftpAuthMethod)) {
<del> persistBuildType = true;
<add> runnerUpdated = true;
<ide> Loggers.SERVER.debug("Setting ftp auth authentication method for runner [" + runnerType + "-" + descriptor.getName() + "] in [" + buildType.getName() + "]");
<ide> final String username = newRunnerParams.get(DeployerRunnerConstants.PARAM_USERNAME);
<ide> if (StringUtil.isEmpty(username)) {
<ide> if (DeployerRunnerConstants.SMB_RUN_TYPE.equals(runnerType)) {
<ide> final String domain = newRunnerParams.get(DeployerRunnerConstants.PARAM_DOMAIN);
<ide> if (StringUtil.isNotEmpty(domain)) {
<del> persistBuildType = true;
<add> runnerUpdated = true;
<ide> newRunnerParams.remove(DeployerRunnerConstants.PARAM_DOMAIN);
<ide> final String username = newRunnerParams.get(DeployerRunnerConstants.PARAM_USERNAME);
<ide> newRunnerParams.put(DeployerRunnerConstants.PARAM_USERNAME, domain + "\\" + username);
<ide> }
<ide> }
<ide>
<del> buildType.updateBuildRunner(descriptor.getId(), descriptor.getName(), runnerType, newRunnerParams);
<add> if (runnerUpdated) {
<add> persistBuildType = true;
<add> buildType.updateBuildRunner(descriptor.getId(), descriptor.getName(), runnerType, newRunnerParams);
<add> }
<ide> }
<ide> if (persistBuildType) {
<ide> buildType.persist();
|
|
Java
|
apache-2.0
|
7547a97916589607c0474b1297b38e87807122e7
| 0 |
matrix-org/matrix-android-sdk,matrix-org/matrix-android-sdk,matrix-org/matrix-android-sdk
|
/*
* Copyright 2014 OpenMarket Ltd
* Copyright 2017 Vector Creations Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.data;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.HandlerThread;
import android.os.Looper;
import android.text.TextUtils;
import android.os.Handler;
import android.util.Pair;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.matrix.androidsdk.MXDataHandler;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.adapters.MessageRow;
import org.matrix.androidsdk.call.MXCallsManager;
import org.matrix.androidsdk.crypto.MXCryptoError;
import org.matrix.androidsdk.crypto.MXEncryptedAttachments;
import org.matrix.androidsdk.crypto.data.MXEncryptEventContentResult;
import org.matrix.androidsdk.data.store.IMXStore;
import org.matrix.androidsdk.db.MXMediasCache;
import org.matrix.androidsdk.listeners.IMXEventListener;
import org.matrix.androidsdk.listeners.MXEventListener;
import org.matrix.androidsdk.listeners.MXMediaUploadListener;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.callback.SimpleApiCallback;
import org.matrix.androidsdk.rest.client.RoomsRestClient;
import org.matrix.androidsdk.rest.client.UrlPostTask;
import org.matrix.androidsdk.rest.model.BannedUser;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.EventContext;
import org.matrix.androidsdk.rest.model.FileInfo;
import org.matrix.androidsdk.rest.model.FileMessage;
import org.matrix.androidsdk.rest.model.ImageInfo;
import org.matrix.androidsdk.rest.model.ImageMessage;
import org.matrix.androidsdk.rest.model.LocationMessage;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.Message;
import org.matrix.androidsdk.rest.model.PowerLevels;
import org.matrix.androidsdk.rest.model.ReceiptData;
import org.matrix.androidsdk.rest.model.RoomMember;
import org.matrix.androidsdk.rest.model.RoomResponse;
import org.matrix.androidsdk.rest.model.Sync.InvitedRoomSync;
import org.matrix.androidsdk.rest.model.Sync.RoomSync;
import org.matrix.androidsdk.rest.model.ThumbnailInfo;
import org.matrix.androidsdk.rest.model.TokensChunkResponse;
import org.matrix.androidsdk.rest.model.User;
import org.matrix.androidsdk.rest.model.VideoInfo;
import org.matrix.androidsdk.rest.model.VideoMessage;
import org.matrix.androidsdk.util.ImageUtils;
import org.matrix.androidsdk.util.JsonUtils;
import org.matrix.androidsdk.util.Log;
import org.matrix.androidsdk.util.MXOsHandler;
import org.matrix.androidsdk.util.ResourceUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Class representing a room and the interactions we have with it.
*/
public class Room {
private static final String LOG_TAG = "Room";
// Account data
private RoomAccountData mAccountData = new RoomAccountData();
// handler
private MXDataHandler mDataHandler;
// store
private IMXStore mStore;
private String mMyUserId = null;
// Map to keep track of the listeners the client adds vs. the ones we actually register to the global data handler.
// This is needed to find the right one when removing the listener.
private final Map<IMXEventListener, IMXEventListener> mEventListeners = new HashMap<>();
// the user is leaving the room
private boolean mIsLeaving = false;
// the room is syncing
private boolean mIsSyncing;
// the unread messages count must be refreshed when the current sync is done.
private boolean mRefreshUnreadAfterSync = false;
// the time line
private EventTimeline mLiveTimeline;
// initial sync callback.
private ApiCallback<Void> mOnInitialSyncCallback;
// gson parser
private final Gson gson = new GsonBuilder().create();
// This is used to block live events and history requests until the state is fully processed and ready
private boolean mIsReady = false;
// call conference user id
private String mCallConferenceUserId;
// true when the current room is a left one
private boolean mIsLeft;
/**
* Default room creator
*/
public Room() {
mLiveTimeline = new EventTimeline(this, true);
}
/**
* Init the room fields.
*
* @param store the store.
* @param roomId the room id
* @param dataHandler the data handler
*/
public void init(IMXStore store, String roomId, MXDataHandler dataHandler) {
mLiveTimeline.setRoomId(roomId);
mDataHandler = dataHandler;
mStore = store;
if (null != mDataHandler) {
mMyUserId = mDataHandler.getUserId();
mLiveTimeline.setDataHandler(mStore, dataHandler);
}
}
/**
* @return the used datahandler
*/
public MXDataHandler getDataHandler() {
return mDataHandler;
}
/**
* @return the store in which the room is stored
*/
public IMXStore getStore() {
return mStore;
}
/**
* Tells if the room is a call conference one
* i.e. this room has been created to manage the call conference
*
* @return true if it is a call conference room.
*/
public boolean isConferenceUserRoom() {
return getLiveState().isConferenceUserRoom();
}
/**
* Set this room as a conference user room
*
* @param isConferenceUserRoom true when it is an user conference room.
*/
public void setIsConferenceUserRoom(boolean isConferenceUserRoom) {
getLiveState().setIsConferenceUserRoom(isConferenceUserRoom);
}
/**
* Test if there is an ongoing conference call.
*
* @return true if there is one.
*/
public boolean isOngoingConferenceCall() {
RoomMember conferenceUser = getLiveState().getMember(MXCallsManager.getConferenceUserId(getRoomId()));
return (null != conferenceUser) && TextUtils.equals(conferenceUser.membership, RoomMember.MEMBERSHIP_JOIN);
}
/**
* Defines that the current room is a left one
*
* @param isLeft true when the current room is a left one
*/
public void setIsLeft(boolean isLeft) {
mIsLeft = isLeft;
mLiveTimeline.setIsHistorical(isLeft);
}
/**
* @return true if the current room is an left one
*/
public boolean isLeft() {
return mIsLeft;
}
//================================================================================
// Sync events
//================================================================================
/**
* Manage list of ephemeral events
*
* @param events the ephemeral events
*/
private void handleEphemeralEvents(List<Event> events) {
for (Event event : events) {
// ensure that the room Id is defined
event.roomId = getRoomId();
try {
if (Event.EVENT_TYPE_RECEIPT.equals(event.getType())) {
if (event.roomId != null) {
List<String> senders = handleReceiptEvent(event);
if ((null != senders) && (senders.size() > 0)) {
mDataHandler.onReceiptEvent(event.roomId, senders);
}
}
} else if (Event.EVENT_TYPE_TYPING.equals(event.getType())) {
mDataHandler.onLiveEvent(event, getState());
}
} catch (Exception e) {
Log.e(LOG_TAG, "ephemeral event failed " + e.getMessage());
}
}
}
/**
* Handle the events of a joined room.
*
* @param roomSync the sync events list.
* @param isGlobalInitialSync true if the room is initialized by a global initial sync.
*/
public void handleJoinedRoomSync(RoomSync roomSync, boolean isGlobalInitialSync) {
if (null != mOnInitialSyncCallback) {
Log.d(LOG_TAG, "initial sync handleJoinedRoomSync " + getRoomId());
} else {
Log.d(LOG_TAG, "handleJoinedRoomSync " + getRoomId());
}
mIsSyncing = true;
synchronized (this) {
mLiveTimeline.handleJoinedRoomSync(roomSync, isGlobalInitialSync);
// ephemeral events
if ((null != roomSync.ephemeral) && (null != roomSync.ephemeral.events)) {
handleEphemeralEvents(roomSync.ephemeral.events);
}
// Handle account data events (if any)
if ((null != roomSync.accountData) && (null != roomSync.accountData.events) && (roomSync.accountData.events.size() > 0)) {
if (isGlobalInitialSync) {
Log.d(LOG_TAG, "## handleJoinedRoomSync : received " + roomSync.accountData.events.size() + " account data events");
}
handleAccountDataEvents(roomSync.accountData.events);
}
}
// the user joined the room
// With V2 sync, the server sends the events to init the room.
if (null != mOnInitialSyncCallback) {
Log.d(LOG_TAG, "handleJoinedRoomSync " + getRoomId() + " : the initial sync is done");
final ApiCallback<Void> fOnInitialSyncCallback = mOnInitialSyncCallback;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
try {
fOnInitialSyncCallback.onSuccess(null);
} catch (Exception e) {
Log.e(LOG_TAG, "handleJoinedRoomSync : onSuccess failed" + e.getMessage());
}
}
});
mOnInitialSyncCallback = null;
}
mIsSyncing = false;
if (mRefreshUnreadAfterSync) {
if (!isGlobalInitialSync) {
refreshUnreadCounter();
} // else -> it will be done at the end of the sync
mRefreshUnreadAfterSync = false;
}
}
/**
* Handle the invitation room events
*
* @param invitedRoomSync the invitation room events.
*/
public void handleInvitedRoomSync(InvitedRoomSync invitedRoomSync) {
mLiveTimeline.handleInvitedRoomSync(invitedRoomSync);
}
/**
* Store an outgoing event.
*
* @param event the event.
*/
public void storeOutgoingEvent(Event event) {
mLiveTimeline.storeOutgoingEvent(event);
}
/**
* Request events to the server. The local cache is not used.
* The events will not be saved in the local storage.
*
* @param token the token to go back from.
* @param paginationCount the number of events to retrieve.
* @param callback the onComplete callback
*/
public void requestServerRoomHistory(final String token, final int paginationCount, final ApiCallback<TokensChunkResponse<Event>> callback) {
mDataHandler.getDataRetriever().requestServerRoomHistory(getRoomId(), token, paginationCount, new SimpleApiCallback<TokensChunkResponse<Event>>(callback) {
@Override
public void onSuccess(TokensChunkResponse<Event> info) {
callback.onSuccess(info);
}
});
}
/**
* cancel any remote request
*/
public void cancelRemoteHistoryRequest() {
mDataHandler.getDataRetriever().cancelRemoteHistoryRequest(getRoomId());
}
//================================================================================
// Getters / setters
//================================================================================
public String getRoomId() {
return mLiveTimeline.getState().roomId;
}
public void setAccountData(RoomAccountData accountData) {
this.mAccountData = accountData;
}
public RoomAccountData getAccountData() {
return this.mAccountData;
}
public RoomState getState() {
return mLiveTimeline.getState();
}
public RoomState getLiveState() {
return getState();
}
public boolean isLeaving() {
return mIsLeaving;
}
public Collection<RoomMember> getMembers() {
return getState().getMembers();
}
public EventTimeline getLiveTimeLine() {
return mLiveTimeline;
}
public void setLiveTimeline(EventTimeline eventTimeline) {
mLiveTimeline = eventTimeline;
}
public void setReadyState(boolean isReady) {
mIsReady = isReady;
}
public boolean isReady() {
return mIsReady;
}
/**
* @return the list of active members in a room ie joined or invited ones.
*/
public Collection<RoomMember> getActiveMembers() {
Collection<RoomMember> members = getState().getMembers();
List<RoomMember> activeMembers = new ArrayList<>();
String conferenceUserId = MXCallsManager.getConferenceUserId(getRoomId());
for (RoomMember member : members) {
if (!TextUtils.equals(member.getUserId(), conferenceUserId)) {
if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_JOIN) || TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_INVITE)) {
activeMembers.add(member);
}
}
}
return activeMembers;
}
/**
* Get the list of the members who have joined the room.
*
* @return the list the joined members of the room.
*/
public Collection<RoomMember> getJoinedMembers() {
Collection<RoomMember> membersList = getState().getMembers();
List<RoomMember> joinedMembersList = new ArrayList<>();
for (RoomMember member : membersList) {
if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_JOIN)) {
joinedMembersList.add(member);
}
}
return joinedMembersList;
}
public RoomMember getMember(String userId) {
return getState().getMember(userId);
}
// member event caches
private final Map<String, Event> mMemberEventByEventId = new HashMap<>();
public void getMemberEvent(final String userId, final ApiCallback<Event> callback) {
final Event event;
final RoomMember member = getMember(userId);
if ((null != member) && (null != member.getOriginalEventId())) {
event = mMemberEventByEventId.get(member.getOriginalEventId());
if (null == event) {
mDataHandler.getDataRetriever().getRoomsRestClient().getContextOfEvent(getRoomId(), member.getOriginalEventId(), 1, new ApiCallback<EventContext>() {
@Override
public void onSuccess(EventContext eventContext) {
if (null != eventContext.event) {
mMemberEventByEventId.put(eventContext.event.eventId, eventContext.event);
}
callback.onSuccess(eventContext.event);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
return;
}
} else {
event = null;
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
callback.onSuccess(event);
}
});
}
public String getTopic() {
return this.getState().topic;
}
public String getName(String selfUserId) {
return getState().getDisplayName(selfUserId);
}
public String getVisibility() {
return getState().visibility;
}
/**
* @return true if the user is invited to the room
*/
public boolean isInvited() {
// Is it an initial sync for this room ?
RoomState state = getState();
String membership = null;
RoomMember selfMember = state.getMember(mMyUserId);
if (null != selfMember) {
membership = selfMember.membership;
}
return TextUtils.equals(membership, RoomMember.MEMBERSHIP_INVITE);
}
/**
* @return true if the user is invited in a direct chat room
*/
public boolean isDirectChatInvitation() {
if (isInvited()) {
// Is it an initial sync for this room ?
RoomState state = getState();
RoomMember selfMember = state.getMember(mMyUserId);
if ((null != selfMember) && (null != selfMember.is_direct)) {
return selfMember.is_direct;
}
}
return false;
}
//================================================================================
// Join
//================================================================================
/**
* Defines the initial sync callback
*
* @param callback the new callback.
*/
public void setOnInitialSyncCallback(ApiCallback<Void> callback) {
mOnInitialSyncCallback = callback;
}
/**
* Join a room with an url to post before joined the room.
*
* @param alias the room alias
* @param thirdPartySignedUrl the thirdPartySigned url
* @param callback the callback
*/
public void joinWithThirdPartySigned(final String alias, final String thirdPartySignedUrl, final ApiCallback<Void> callback) {
if (null == thirdPartySignedUrl) {
join(alias, callback);
} else {
String url = thirdPartySignedUrl + "&mxid=" + mMyUserId;
UrlPostTask task = new UrlPostTask();
task.setListener(new UrlPostTask.IPostTaskListener() {
@Override
public void onSucceed(JsonObject object) {
HashMap<String, Object> map = null;
try {
map = new Gson().fromJson(object, new TypeToken<HashMap<String, Object>>() {
}.getType());
} catch (Exception e) {
Log.e(LOG_TAG, "joinWithThirdPartySigned : Gson().fromJson failed" + e.getMessage());
}
if (null != map) {
HashMap<String, Object> joinMap = new HashMap<>();
joinMap.put("third_party_signed", map);
join(alias, joinMap, callback);
} else {
join(callback);
}
}
@Override
public void onError(String errorMessage) {
Log.d(LOG_TAG, "joinWithThirdPartySigned failed " + errorMessage);
// cannot validate the url
// try without validating the url
join(callback);
}
});
// avoid crash if there are too many running task
try {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
} catch (final Exception e) {
task.cancel(true);
Log.e(LOG_TAG, "joinWithThirdPartySigned : task.executeOnExecutor failed" + e.getMessage());
(new android.os.Handler(Looper.getMainLooper())).post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
}
/**
* Join the room. If successful, the room's current state will be loaded before calling back onComplete.
*
* @param callback the callback for when done
*/
public void join(final ApiCallback<Void> callback) {
join(null, null, callback);
}
/**
* Join the room. If successful, the room's current state will be loaded before calling back onComplete.
*
* @param roomAlias the room alias
* @param callback the callback for when done
*/
private void join(String roomAlias, ApiCallback<Void> callback) {
join(roomAlias, null, callback);
}
/**
* Join the room. If successful, the room's current state will be loaded before calling back onComplete.
*
* @param roomAlias the room alias
* @param extraParams the join extra params
* @param callback the callback for when done
*/
private void join(final String roomAlias, final HashMap<String, Object> extraParams, final ApiCallback<Void> callback) {
Log.d(LOG_TAG, "Join the room " + getRoomId() + " with alias " + roomAlias);
mDataHandler.getDataRetriever().getRoomsRestClient().joinRoom((null != roomAlias) ? roomAlias : getRoomId(), extraParams, new SimpleApiCallback<RoomResponse>(callback) {
@Override
public void onSuccess(final RoomResponse aResponse) {
try {
boolean isRoomMember;
synchronized (this) {
isRoomMember = (getState().getMember(mMyUserId) != null);
}
// the join request did not get the room initial history
if (!isRoomMember) {
Log.d(LOG_TAG, "the room " + getRoomId() + " is joined but wait after initial sync");
// wait the server sends the events chunk before calling the callback
setOnInitialSyncCallback(callback);
} else {
Log.d(LOG_TAG, "the room " + getRoomId() + " is joined : the initial sync has been done");
// already got the initial sync
callback.onSuccess(null);
}
} catch (Exception e) {
Log.e(LOG_TAG, "join exception " + e.getMessage());
}
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "join onNetworkError " + e.getMessage());
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "join onMatrixError " + e.getMessage());
if (MatrixError.UNKNOWN.equals(e.errcode) && TextUtils.equals("No known servers", e.error)) {
// minging kludge until https://matrix.org/jira/browse/SYN-678 is fixed
// 'Error when trying to join an empty room should be more explicit
e.error = mStore.getContext().getString(org.matrix.androidsdk.R.string.room_error_join_failed_empty_room);
}
// if the alias is not found
// try with the room id
if ((e.mStatus == 404) && !TextUtils.isEmpty(roomAlias)) {
Log.e(LOG_TAG, "Retry without the room alias");
join(null, extraParams, callback);
return;
}
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "join onUnexpectedError " + e.getMessage());
callback.onUnexpectedError(e);
}
});
}
/**
* @return true if the user joined the room
*/
private boolean selfJoined() {
RoomMember roomMember = getMember(mMyUserId);
// send the event only if the user has joined the room.
return ((null != roomMember) && RoomMember.MEMBERSHIP_JOIN.equals(roomMember.membership));
}
//================================================================================
// Room info (liveState) update
//================================================================================
/**
* This class dispatches the error to the dedicated callbacks.
* If the operation succeeds, the room state is saved because calling the callback.
*/
private class RoomInfoUpdateCallback<T> implements ApiCallback<T> {
private final ApiCallback<T> mCallback;
/**
* Constructor
*/
public RoomInfoUpdateCallback(ApiCallback<T> callback) {
mCallback = callback;
}
@Override
public void onSuccess(T info) {
mStore.storeLiveStateForRoom(getRoomId());
if (null != mCallback) {
mCallback.onSuccess(info);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != mCallback) {
mCallback.onNetworkError(e);
}
}
@Override
public void onMatrixError(final MatrixError e) {
if (null != mCallback) {
mCallback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(final Exception e) {
if (null != mCallback) {
mCallback.onUnexpectedError(e);
}
}
}
/**
* Update the power level of the user userId
*
* @param userId the user id
* @param powerLevel the new power level
* @param callback the callback with the created event
*/
public void updateUserPowerLevels(String userId, int powerLevel, ApiCallback<Void> callback) {
PowerLevels powerLevels = getState().getPowerLevels().deepCopy();
powerLevels.setUserPowerLevel(userId, powerLevel);
mDataHandler.getDataRetriever().getRoomsRestClient().updatePowerLevels(getRoomId(), powerLevels, callback);
}
/**
* Update the room's name.
*
* @param aRoomName the new name
* @param callback the async callback
*/
public void updateName(String aRoomName, final ApiCallback<Void> callback) {
final String fRoomName = TextUtils.isEmpty(aRoomName) ? null : aRoomName;
mDataHandler.getDataRetriever().getRoomsRestClient().updateRoomName(getRoomId(), fRoomName, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().name = fRoomName;
super.onSuccess(info);
}
});
}
/**
* Update the room's topic.
*
* @param aTopic the new topic
* @param callback the async callback
*/
public void updateTopic(final String aTopic, final ApiCallback<Void> callback) {
final String fTopic = TextUtils.isEmpty(aTopic) ? null : aTopic;
mDataHandler.getDataRetriever().getRoomsRestClient().updateTopic(getRoomId(), fTopic, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().topic = fTopic;
super.onSuccess(info);
}
});
}
/**
* Update the room's main alias.
*
* @param aCanonicalAlias the canonical alias
* @param callback the async callback
*/
public void updateCanonicalAlias(final String aCanonicalAlias, final ApiCallback<Void> callback) {
final String fCanonicalAlias = TextUtils.isEmpty(aCanonicalAlias) ? null : aCanonicalAlias;
mDataHandler.getDataRetriever().getRoomsRestClient().updateCanonicalAlias(getRoomId(), fCanonicalAlias, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().roomAliasName = fCanonicalAlias;
super.onSuccess(info);
}
});
}
/**
* Provides the room aliases list.
* The result is never null.
*
* @return the room aliases list.
*/
public List<String> getAliases() {
return getLiveState().getAliases();
}
/**
* Remove a room alias.
*
* @param alias the alias to remove
* @param callback the async callback
*/
public void removeAlias(final String alias, final ApiCallback<Void> callback) {
final List<String> updatedAliasesList = new ArrayList<>(getAliases());
// nothing to do
if (TextUtils.isEmpty(alias) || (updatedAliasesList.indexOf(alias) < 0)) {
if (null != callback) {
callback.onSuccess(null);
}
return;
}
mDataHandler.getDataRetriever().getRoomsRestClient().removeRoomAlias(alias, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().removeAlias(alias);
super.onSuccess(info);
}
});
}
/**
* Try to add an alias to the aliases list.
*
* @param alias the alias to add.
* @param callback the the async callback
*/
public void addAlias(final String alias, final ApiCallback<Void> callback) {
final List<String> updatedAliasesList = new ArrayList<>(getAliases());
// nothing to do
if (TextUtils.isEmpty(alias) || (updatedAliasesList.indexOf(alias) >= 0)) {
if (null != callback) {
callback.onSuccess(null);
}
return;
}
mDataHandler.getDataRetriever().getRoomsRestClient().setRoomIdByAlias(getRoomId(), alias, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().addAlias(alias);
super.onSuccess(info);
}
});
}
/**
* @return the room avatar URL. If there is no defined one, use the members one (1:1 chat only).
*/
public String getAvatarUrl() {
String res = getState().getAvatarUrl();
// detect if it is a room with no more than 2 members (i.e. an alone or a 1:1 chat)
if (null == res) {
List<RoomMember> members = new ArrayList<>(getState().getMembers());
if (members.size() == 1) {
res = members.get(0).getAvatarUrl();
} else if (members.size() == 2) {
RoomMember m1 = members.get(0);
RoomMember m2 = members.get(1);
res = TextUtils.equals(m1.getUserId(), mMyUserId) ? m2.getAvatarUrl() : m1.getAvatarUrl();
}
}
return res;
}
/**
* The call avatar is the same as the room avatar except there are only 2 JOINED members.
* In this case, it returns the avtar of the other joined member.
*
* @return the call avatar URL.
*/
public String getCallAvatarUrl() {
String avatarURL;
List<RoomMember> joinedMembers = new ArrayList<>(getJoinedMembers());
// 2 joined members case
if (2 == joinedMembers.size()) {
// use other member avatar.
if (TextUtils.equals(mMyUserId, joinedMembers.get(0).getUserId())) {
avatarURL = joinedMembers.get(1).getAvatarUrl();
} else {
avatarURL = joinedMembers.get(0).getAvatarUrl();
}
} else {
//
avatarURL = getAvatarUrl();
}
return avatarURL;
}
/**
* Update the room avatar URL.
*
* @param avatarUrl the new avatar URL
* @param callback the async callback
*/
public void updateAvatarUrl(final String avatarUrl, final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateAvatarUrl(getRoomId(), avatarUrl, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().url = avatarUrl;
super.onSuccess(info);
}
});
}
/**
* Update the room's history visibility
*
* @param historyVisibility the visibility (should be one of RoomState.HISTORY_VISIBILITY_XX values)
* @param callback the async callback
*/
public void updateHistoryVisibility(final String historyVisibility, final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateHistoryVisibility(getRoomId(), historyVisibility, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().history_visibility = historyVisibility;
super.onSuccess(info);
}
});
}
/**
* Update the directory's visibility
*
* @param visibility the visibility (should be one of RoomState.HISTORY_VISIBILITY_XX values)
* @param callback the async callback
*/
public void updateDirectoryVisibility(final String visibility, final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateDirectoryVisibility(getRoomId(), visibility, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().visibility = visibility;
super.onSuccess(info);
}
});
}
/**
* Get the directory visibility of the room (see {@link #updateDirectoryVisibility(String, ApiCallback)}).
* The directory visibility indicates if the room is listed among the directory list.
*
* @param roomId the user Id.
* @param callback the callback returning the visibility response value.
*/
public void getDirectoryVisibility(final String roomId, final ApiCallback<String> callback) {
RoomsRestClient roomRestApi = mDataHandler.getDataRetriever().getRoomsRestClient();
if (null != roomRestApi) {
roomRestApi.getDirectoryVisibility(roomId, new ApiCallback<RoomState>() {
@Override
public void onSuccess(RoomState roomState) {
RoomState currentRoomState = getState();
if (null != currentRoomState) {
currentRoomState.visibility = roomState.visibility;
}
if (null != callback) {
callback.onSuccess(roomState.visibility);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
/**
* Update the join rule of the room.
*
* @param aRule the join rule: {@link RoomState#JOIN_RULE_PUBLIC} or {@link RoomState#JOIN_RULE_INVITE}
* @param aCallBackResp the async callback
*/
public void updateJoinRules(final String aRule, final ApiCallback<Void> aCallBackResp) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateJoinRules(getRoomId(), aRule, new RoomInfoUpdateCallback<Void>(aCallBackResp) {
@Override
public void onSuccess(Void info) {
getState().join_rule = aRule;
super.onSuccess(info);
}
});
}
/**
* Update the guest access rule of the room.
* To deny guest access to the room, aGuestAccessRule must be set to {@link RoomState#GUEST_ACCESS_FORBIDDEN}.
*
* @param aGuestAccessRule the guest access rule: {@link RoomState#GUEST_ACCESS_CAN_JOIN} or {@link RoomState#GUEST_ACCESS_FORBIDDEN}
* @param callback the async callback
*/
public void updateGuestAccess(final String aGuestAccessRule, final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateGuestAccess(getRoomId(), aGuestAccessRule, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().guest_access = aGuestAccessRule;
super.onSuccess(info);
}
});
}
//================================================================================
// Read receipts events
//================================================================================
/**
* @return the call conference user id
*/
private String getCallConferenceUserId() {
if (null == mCallConferenceUserId) {
mCallConferenceUserId = MXCallsManager.getConferenceUserId(getRoomId());
}
return mCallConferenceUserId;
}
/**
* Handle a receiptData.
*
* @param receiptData the receiptData.
* @return true if there a store update.
*/
public boolean handleReceiptData(ReceiptData receiptData) {
if (!TextUtils.equals(receiptData.userId, getCallConferenceUserId())) {
boolean isUpdated = mStore.storeReceipt(receiptData, getRoomId());
// check oneself receipts
// if there is an update, it means that the messages have been read from another client
// it requires to update the summary to display valid information.
if (isUpdated && TextUtils.equals(mMyUserId, receiptData.userId)) {
RoomSummary summary = mStore.getSummary(getRoomId());
if (null != summary) {
summary.setReadReceiptEventId(receiptData.eventId);
mStore.flushSummary(summary);
}
refreshUnreadCounter();
}
return isUpdated;
} else {
return false;
}
}
/**
* Handle receipt event.
*
* @param event the event receipts.
* @return the sender user IDs list.
*/
private List<String> handleReceiptEvent(Event event) {
List<String> senderIDs = new ArrayList<>();
try {
// the receipts dictionnaries
// key : $EventId
// value : dict key $UserId
// value dict key ts
// dict value ts value
Type type = new TypeToken<HashMap<String, HashMap<String, HashMap<String, HashMap<String, Object>>>>>() {
}.getType();
HashMap<String, HashMap<String, HashMap<String, HashMap<String, Object>>>> receiptsDict = gson.fromJson(event.getContent(), type);
for (String eventId : receiptsDict.keySet()) {
HashMap<String, HashMap<String, HashMap<String, Object>>> receiptDict = receiptsDict.get(eventId);
for (String receiptType : receiptDict.keySet()) {
// only the read receipts are managed
if (TextUtils.equals(receiptType, "m.read")) {
HashMap<String, HashMap<String, Object>> userIdsDict = receiptDict.get(receiptType);
for (String userID : userIdsDict.keySet()) {
HashMap<String, Object> paramsDict = userIdsDict.get(userID);
for (String paramName : paramsDict.keySet()) {
if (TextUtils.equals("ts", paramName)) {
Double value = (Double) paramsDict.get(paramName);
long ts = value.longValue();
if (handleReceiptData(new ReceiptData(userID, eventId, ts))) {
senderIDs.add(userID);
}
}
}
}
}
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "handleReceiptEvent : failed" + e.getMessage());
}
return senderIDs;
}
/**
* Clear the unread message counters
*
* @param summary the room summary
*/
private void clearUnreadCounters(RoomSummary summary) {
Log.d(LOG_TAG, "## clearUnreadCounters " + getRoomId());
// reset the notification count
getLiveState().setHighlightCount(0);
getLiveState().setNotificationCount(0);
mStore.storeLiveStateForRoom(getRoomId());
// flush the summary
if (null != summary) {
summary.setUnreadEventsCount(0);
summary.setHighlightCount(0);
summary.setNotificationCount(0);
mStore.flushSummary(summary);
}
mStore.commit();
}
/**
* @return the read marker event id
*/
public String getReadMarkerEventId() {
RoomSummary summary = mStore.getSummary(getRoomId());
if (null != summary) {
return (null != summary.getReadMarkerEventId()) ? summary.getReadMarkerEventId() : summary.getReadReceiptEventId();
} else {
return null;
}
}
/**
* Mark all the messages as read.
* It also move the read marker to the latest known messages
*
* @param aRespCallback the asynchronous callback
*/
public boolean markAllAsRead(final ApiCallback<Void> aRespCallback) {
return markAllAsRead(true, aRespCallback);
}
/**
* Mark all the messages as read.
* It also move the read marker to the latest known messages if updateReadMarker is set to true
*
* @param updateReadMarker true to move the read marker to the latest known event
* @param aRespCallback the asynchronous callback
*/
private boolean markAllAsRead(boolean updateReadMarker, final ApiCallback<Void> aRespCallback) {
final Event lastEvent = mStore.getLatestEvent(getRoomId());
boolean res = sendReadMarkers(updateReadMarker ? ((null != lastEvent) ? lastEvent.eventId : null) : getReadMarkerEventId(), null, aRespCallback);
if (!res) {
RoomSummary summary = mDataHandler.getStore().getSummary(getRoomId());
if (null != summary) {
if ((0 != summary.getUnreadEventsCount()) ||
(0 != summary.getHighlightCount()) ||
(0 != summary.getNotificationCount())) {
Log.e(LOG_TAG, "## markAllAsRead() : the summary events counters should be cleared for " + getRoomId() + " should have been cleared");
Event latestEvent = mDataHandler.getStore().getLatestEvent(getRoomId());
summary.setLatestReceivedEvent(latestEvent);
if (null != latestEvent) {
summary.setReadReceiptEventId(latestEvent.eventId);
} else {
summary.setReadReceiptEventId(null);
}
summary.setUnreadEventsCount(0);
summary.setHighlightCount(0);
summary.setNotificationCount(0);
mDataHandler.getStore().flushSummary(summary);
}
} else {
Log.e(LOG_TAG, "## sendReadReceipt() : no summary for " + getRoomId());
}
if ((0 != getLiveState().getNotificationCount()) || (0 != getLiveState().getHighlightCount())) {
Log.e(LOG_TAG, "## markAllAsRead() : the notification messages count for " + getRoomId() + " should have been cleared");
getLiveState().setNotificationCount(0);
getLiveState().setHighlightCount(0);
mDataHandler.getStore().storeLiveStateForRoom(getRoomId());
}
}
return res;
}
/**
* Update the read marker event Id
*
* @param readMarkerEventId the read marker even id
*/
public void setReadMakerEventId(final String readMarkerEventId) {
RoomSummary summary = mStore.getSummary(getRoomId());
if (summary != null && !readMarkerEventId.equals(summary.getReadMarkerEventId())) {
sendReadMarkers(readMarkerEventId, summary.getReadReceiptEventId(), null);
}
}
/**
* Send a read receipt to the latest known event
*/
public void sendReadReceipt() {
markAllAsRead(false, null);
}
/**
* Send the read receipt to the latest room message id.
*
* @param event send a read receipt to a provided event
* @param aRespCallback asynchronous response callback
* @return true if the read receipt has been sent, false otherwise
*/
public boolean sendReadReceipt(Event event, final ApiCallback<Void> aRespCallback) {
String eventId = (null != event) ? event.eventId : null;
Log.d(LOG_TAG, "## sendReadReceipt() : eventId " + eventId + " in room " + getRoomId());
return sendReadMarkers(null, eventId, aRespCallback);
}
/**
* Forget the current read marker
* This will update the read marker to match the read receipt
*
* @param callback the asynchronous callback
*/
public void forgetReadMarker(final ApiCallback<Void> callback) {
final RoomSummary summary = mStore.getSummary(getRoomId());
final String currentReadReceipt = summary.getReadReceiptEventId();
Log.d(LOG_TAG, "## forgetReadMarker() : update the read marker to " + currentReadReceipt + " in room " + getRoomId());
summary.setReadMarkerEventId(currentReadReceipt);
mStore.flushSummary(summary);
setReadMarkers(currentReadReceipt, currentReadReceipt, callback);
}
/**
* Send the read markers
*
* @param aReadMarkerEventId the new read marker event id (if null use the latest known event id)
* @param aReadReceiptEventId the new read receipt event id (if null use the latest known event id)
* @param aRespCallback asynchronous response callback
* @return true if the request is sent, false otherwise
*/
public boolean sendReadMarkers(final String aReadMarkerEventId, final String aReadReceiptEventId, final ApiCallback<Void> aRespCallback) {
final Event lastEvent = mStore.getLatestEvent(getRoomId());
// reported by GA
if (null == lastEvent) {
Log.e(LOG_TAG, "## sendReadMarkers(): no last event");
return false;
}
Log.d(LOG_TAG, "## sendReadMarkers(): readMarkerEventId " + aReadMarkerEventId + " readReceiptEventId " + aReadReceiptEventId + " in room " + getRoomId());
boolean hasUpdate = false;
String readMarkerEventId = aReadMarkerEventId;
if (!TextUtils.isEmpty(aReadMarkerEventId)) {
if (!MXSession.isMessageId(aReadMarkerEventId)) {
Log.e(LOG_TAG, "## sendReadMarkers() : invalid event id " + readMarkerEventId);
// Read marker is invalid, ignore it
readMarkerEventId = null;
} else {
// Check if the read marker is updated
RoomSummary summary = mStore.getSummary(getRoomId());
if ((null != summary) && !TextUtils.equals(readMarkerEventId, summary.getReadMarkerEventId())) {
// Make sure the new read marker event is newer than the current one
final Event newReadMarkerEvent = mStore.getEvent(readMarkerEventId, getRoomId());
final Event currentReadMarkerEvent = mStore.getEvent(summary.getReadMarkerEventId(), getRoomId());
if (newReadMarkerEvent == null || currentReadMarkerEvent == null
|| newReadMarkerEvent.getOriginServerTs() > currentReadMarkerEvent.getOriginServerTs()) {
// Event is not in store (assume it is in the past), or is older than current one
Log.d(LOG_TAG, "## sendReadMarkers(): set new read marker event id " + readMarkerEventId + " in room " + getRoomId());
summary.setReadMarkerEventId(readMarkerEventId);
mStore.flushSummary(summary);
hasUpdate = true;
}
}
}
}
final String readReceiptEventId = (null == aReadReceiptEventId) ? lastEvent.eventId : aReadReceiptEventId;
// check if the read receipt event id is already read
if (!getDataHandler().getStore().isEventRead(getRoomId(), getDataHandler().getUserId(), readReceiptEventId)) {
// check if the event id update is allowed
if (handleReceiptData(new ReceiptData(mMyUserId, readReceiptEventId, System.currentTimeMillis()))) {
// Clear the unread counters if the latest message is displayed
// We don't try to compute the unread counters for oldest messages :
// ---> it would require too much time.
// The counters are cleared to avoid displaying invalid values
// when the device is offline.
// The read receipts will be sent later
// (asap there is a valid network connection)
if (TextUtils.equals(lastEvent.eventId, readReceiptEventId)) {
clearUnreadCounters(mStore.getSummary(getRoomId()));
}
hasUpdate = true;
}
}
if (hasUpdate) {
setReadMarkers(readMarkerEventId, readReceiptEventId, aRespCallback);
}
return hasUpdate;
}
/**
* Send the request to update the read marker and read receipt.
*
* @param aReadMarkerEventId the read marker event id
* @param aReadReceiptEventId the read receipt event id
* @param callback the asynchronous callback
*/
private void setReadMarkers(final String aReadMarkerEventId, final String aReadReceiptEventId, final ApiCallback<Void> callback) {
Log.d(LOG_TAG, "## setReadMarkers(): readMarkerEventId " + aReadMarkerEventId + " readReceiptEventId " + aReadMarkerEventId);
// check if the message ids are valid
final String readMarkerEventId = MXSession.isMessageId(aReadMarkerEventId) ? aReadMarkerEventId : null;
final String readReceiptEventId = MXSession.isMessageId(aReadReceiptEventId) ? aReadReceiptEventId : null;
// if there is nothing to do
if (TextUtils.isEmpty(readMarkerEventId) && TextUtils.isEmpty(readReceiptEventId)) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onSuccess(null);
}
}
});
} else {
mDataHandler.getDataRetriever().getRoomsRestClient().sendReadMarker(getRoomId(), readMarkerEventId, readReceiptEventId, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (null != callback) {
callback.onSuccess(info);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
/**
* Check if an event has been read.
*
* @param eventId the event id
* @return true if the message has been read
*/
public boolean isEventRead(String eventId) {
return mStore.isEventRead(getRoomId(), mMyUserId, eventId);
}
//================================================================================
// Unread event count management
//================================================================================
/**
* @return the number of unread messages that match the push notification rules.
*/
public int getNotificationCount() {
return getState().getNotificationCount();
}
/**
* @return the number of highlighted events.
*/
public int getHighlightCount() {
return getState().getHighlightCount();
}
/**
* refresh the unread events counts.
*/
public void refreshUnreadCounter() {
// avoid refreshing the unread counter while processing a bunch of messages.
if (!mIsSyncing) {
RoomSummary summary = mStore.getSummary(getRoomId());
if (null != summary) {
int prevValue = summary.getUnreadEventsCount();
int newValue = mStore.eventsCountAfter(getRoomId(), summary.getReadReceiptEventId());
if (prevValue != newValue) {
summary.setUnreadEventsCount(newValue);
mStore.flushSummary(summary);
}
}
} else {
// wait the sync end before computing is again
mRefreshUnreadAfterSync = true;
}
}
//================================================================================
// typing events
//================================================================================
// userIds list
private List<String> mTypingUsers = new ArrayList<>();
/**
* Get typing users
*
* @return the userIds list
*/
public List<String> getTypingUsers() {
List<String> typingUsers;
synchronized (Room.this) {
typingUsers = (null == mTypingUsers) ? new ArrayList<String>() : new ArrayList<>(mTypingUsers);
}
return typingUsers;
}
/**
* Send a typing notification
*
* @param isTyping typing status
* @param timeout the typing timeout
*/
public void sendTypingNotification(boolean isTyping, int timeout, ApiCallback<Void> callback) {
// send the event only if the user has joined the room.
if (selfJoined()) {
mDataHandler.getDataRetriever().getRoomsRestClient().sendTypingNotification(getRoomId(), mMyUserId, isTyping, timeout, callback);
}
}
//================================================================================
// Medias events
//================================================================================
/**
* Fill the locationInfo
*
* @param context the context
* @param locationMessage the location message
* @param thumbnailUri the thumbnail uri
* @param thumbMimeType the thumbnail mime type
*/
public static void fillLocationInfo(Context context, LocationMessage locationMessage, Uri thumbnailUri, String thumbMimeType) {
if (null != thumbnailUri) {
try {
locationMessage.thumbnail_url = thumbnailUri.toString();
ThumbnailInfo thumbInfo = new ThumbnailInfo();
File thumbnailFile = new File(thumbnailUri.getPath());
ExifInterface exifMedia = new ExifInterface(thumbnailUri.getPath());
String sWidth = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
String sHeight = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
if (null != sWidth) {
thumbInfo.w = Integer.parseInt(sWidth);
}
if (null != sHeight) {
thumbInfo.h = Integer.parseInt(sHeight);
}
thumbInfo.size = Long.valueOf(thumbnailFile.length());
thumbInfo.mimetype = thumbMimeType;
locationMessage.thumbnail_info = thumbInfo;
} catch (Exception e) {
Log.e(LOG_TAG, "fillLocationInfo : failed" + e.getMessage());
}
}
}
/**
* Fills the VideoMessage info.
*
* @param context Application context for the content resolver.
* @param videoMessage The VideoMessage to fill.
* @param fileUri The file uri.
* @param videoMimeType The mimeType
* @param thumbnailUri the thumbnail uri
* @param thumbMimeType the thumbnail mime type
*/
public static void fillVideoInfo(Context context, VideoMessage videoMessage, Uri fileUri, String videoMimeType, Uri thumbnailUri, String thumbMimeType) {
try {
VideoInfo videoInfo = new VideoInfo();
File file = new File(fileUri.getPath());
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(file.getAbsolutePath());
Bitmap bmp = retriever.getFrameAtTime();
videoInfo.h = bmp.getHeight();
videoInfo.w = bmp.getWidth();
videoInfo.mimetype = videoMimeType;
try {
MediaPlayer mp = MediaPlayer.create(context, fileUri);
if (null != mp) {
videoInfo.duration = Long.valueOf(mp.getDuration());
mp.release();
}
} catch (Exception e) {
Log.e(LOG_TAG, "fillVideoInfo : MediaPlayer.create failed" + e.getMessage());
}
videoInfo.size = file.length();
// thumbnail
if (null != thumbnailUri) {
videoInfo.thumbnail_url = thumbnailUri.toString();
ThumbnailInfo thumbInfo = new ThumbnailInfo();
File thumbnailFile = new File(thumbnailUri.getPath());
ExifInterface exifMedia = new ExifInterface(thumbnailUri.getPath());
String sWidth = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
String sHeight = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
if (null != sWidth) {
thumbInfo.w = Integer.parseInt(sWidth);
}
if (null != sHeight) {
thumbInfo.h = Integer.parseInt(sHeight);
}
thumbInfo.size = Long.valueOf(thumbnailFile.length());
thumbInfo.mimetype = thumbMimeType;
videoInfo.thumbnail_info = thumbInfo;
}
videoMessage.info = videoInfo;
} catch (Exception e) {
Log.e(LOG_TAG, "fillVideoInfo : failed" + e.getMessage());
}
}
/**
* Fills the fileMessage fileInfo.
*
* @param context Application context for the content resolver.
* @param fileMessage The fileMessage to fill.
* @param fileUri The file uri.
* @param mimeType The mimeType
*/
public static void fillFileInfo(Context context, FileMessage fileMessage, Uri fileUri, String mimeType) {
try {
FileInfo fileInfo = new FileInfo();
String filename = fileUri.getPath();
File file = new File(filename);
fileInfo.mimetype = mimeType;
fileInfo.size = file.length();
fileMessage.info = fileInfo;
} catch (Exception e) {
Log.e(LOG_TAG, "fillFileInfo : failed" + e.getMessage());
}
}
/**
* Define ImageInfo for an image uri
*
* @param context Application context for the content resolver.
* @param imageUri The full size image uri.
* @param mimeType The image mimeType
*/
public static ImageInfo getImageInfo(Context context, ImageInfo anImageInfo, Uri imageUri, String mimeType) {
ImageInfo imageInfo = (null == anImageInfo) ? new ImageInfo() : anImageInfo;
try {
String filename = imageUri.getPath();
File file = new File(filename);
ExifInterface exifMedia = new ExifInterface(filename);
String sWidth = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
String sHeight = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
// the image rotation is replaced by orientation
// imageInfo.rotation = ImageUtils.getRotationAngleForBitmap(context, imageUri);
imageInfo.orientation = ImageUtils.getOrientationForBitmap(context, imageUri);
int width = 0;
int height = 0;
// extract the Exif info
if ((null != sWidth) && (null != sHeight)) {
if ((imageInfo.orientation == ExifInterface.ORIENTATION_TRANSPOSE) ||
(imageInfo.orientation == ExifInterface.ORIENTATION_ROTATE_90) ||
(imageInfo.orientation == ExifInterface.ORIENTATION_TRANSVERSE) ||
(imageInfo.orientation == ExifInterface.ORIENTATION_ROTATE_270)) {
height = Integer.parseInt(sWidth);
width = Integer.parseInt(sHeight);
} else {
width = Integer.parseInt(sWidth);
height = Integer.parseInt(sHeight);
}
}
// there is no exif info or the size is invalid
if ((0 == width) || (0 == height)) {
try {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageUri.getPath(), opts);
// don't need to load the bitmap in memory
if ((opts.outHeight > 0) && (opts.outWidth > 0)) {
width = opts.outWidth;
height = opts.outHeight;
}
} catch (Exception e) {
Log.e(LOG_TAG, "fillImageInfo : failed" + e.getMessage());
} catch (OutOfMemoryError oom) {
Log.e(LOG_TAG, "fillImageInfo : oom");
}
}
// valid image size ?
if ((0 != width) || (0 != height)) {
imageInfo.w = width;
imageInfo.h = height;
}
imageInfo.mimetype = mimeType;
imageInfo.size = file.length();
} catch (Exception e) {
Log.e(LOG_TAG, "fillImageInfo : failed" + e.getMessage());
imageInfo = null;
}
return imageInfo;
}
/**
* Fills the imageMessage imageInfo.
*
* @param context Application context for the content resolver.
* @param imageMessage The imageMessage to fill.
* @param imageUri The full size image uri.
* @param mimeType The image mimeType
*/
public static void fillImageInfo(Context context, ImageMessage imageMessage, Uri imageUri, String mimeType) {
imageMessage.info = getImageInfo(context, imageMessage.info, imageUri, mimeType);
}
/**
* Fills the imageMessage imageInfo.
*
* @param context Application context for the content resolver.
* @param imageMessage The imageMessage to fill.
* @param thumbUri The thumbnail uri
* @param mimeType The image mimeType
*/
public static void fillThumbnailInfo(Context context, ImageMessage imageMessage, Uri thumbUri, String mimeType) {
ImageInfo imageInfo = getImageInfo(context, null, thumbUri, mimeType);
if (null != imageInfo) {
if (null == imageMessage.info) {
imageMessage.info = new ImageInfo();
}
imageMessage.info.thumbnailInfo = new ThumbnailInfo();
imageMessage.info.thumbnailInfo.w = imageInfo.w;
imageMessage.info.thumbnailInfo.h = imageInfo.h;
imageMessage.info.thumbnailInfo.size = imageInfo.size;
imageMessage.info.thumbnailInfo.mimetype = imageInfo.mimetype;
}
}
//================================================================================
// Call
//================================================================================
/**
* Test if a call can be performed in this room.
*
* @return true if a call can be performed.
*/
public boolean canPerformCall() {
return getActiveMembers().size() > 1;
}
/**
* @return a list of callable members.
*/
public List<RoomMember> callees() {
List<RoomMember> res = new ArrayList<>();
Collection<RoomMember> members = getMembers();
for (RoomMember m : members) {
if (RoomMember.MEMBERSHIP_JOIN.equals(m.membership) && !mMyUserId.equals(m.getUserId())) {
res.add(m);
}
}
return res;
}
//================================================================================
// Account data management
//================================================================================
/**
* Handle private user data events.
*
* @param accountDataEvents the account events.
*/
private void handleAccountDataEvents(List<Event> accountDataEvents) {
if ((null != accountDataEvents) && (accountDataEvents.size() > 0)) {
// manage the account events
for (Event accountDataEvent : accountDataEvents) {
String eventType = accountDataEvent.getType();
if (eventType.equals(Event.EVENT_TYPE_READ_MARKER)) {
RoomSummary summary = mStore.getSummary(getRoomId());
if (null != summary) {
Event event = JsonUtils.toEvent(accountDataEvent.getContent());
if (null != event && !TextUtils.equals(event.eventId, summary.getReadMarkerEventId())) {
Log.d(LOG_TAG, "## handleAccountDataEvents() : update the read marker to " + event.eventId + " in room " + getRoomId());
if (TextUtils.isEmpty(event.eventId)) {
Log.e(LOG_TAG, "## handleAccountDataEvents() : null event id " + accountDataEvent.getContent());
}
summary.setReadMarkerEventId(event.eventId);
mStore.flushSummary(summary);
mDataHandler.onReadMarkerEvent(getRoomId());
}
}
} else {
try {
mAccountData.handleTagEvent(accountDataEvent);
if (accountDataEvent.getType().equals(Event.EVENT_TYPE_TAGS)) {
mDataHandler.onRoomTagEvent(getRoomId());
}
} catch (Exception e) {
Log.e(LOG_TAG, "## handleAccountDataEvents() : room " + getRoomId() + " failed " + e.getMessage());
}
}
}
mStore.storeAccountData(getRoomId(), mAccountData);
}
}
/**
* Add a tag to a room.
* Use this method to update the order of an existing tag.
*
* @param tag the new tag to add to the room.
* @param order the order.
* @param callback the operation callback
*/
private void addTag(String tag, Double order, final ApiCallback<Void> callback) {
// sanity check
if ((null != tag) && (null != order)) {
mDataHandler.getDataRetriever().getRoomsRestClient().addTag(getRoomId(), tag, order, callback);
} else {
if (null != callback) {
callback.onSuccess(null);
}
}
}
/**
* Remove a tag to a room.
*
* @param tag the new tag to add to the room.
* @param callback the operation callback.
*/
private void removeTag(String tag, final ApiCallback<Void> callback) {
// sanity check
if (null != tag) {
mDataHandler.getDataRetriever().getRoomsRestClient().removeTag(getRoomId(), tag, callback);
} else {
if (null != callback) {
callback.onSuccess(null);
}
}
}
/**
* Remove a tag and add another one.
*
* @param oldTag the tag to remove.
* @param newTag the new tag to add. Nil can be used. Then, no new tag will be added.
* @param newTagOrder the order of the new tag.
* @param callback the operation callback.
*/
public void replaceTag(final String oldTag, final String newTag, final Double newTagOrder, final ApiCallback<Void> callback) {
// remove tag
if ((null != oldTag) && (null == newTag)) {
removeTag(oldTag, callback);
}
// define a tag or define a new order
else if (((null == oldTag) && (null != newTag)) || TextUtils.equals(oldTag, newTag)) {
addTag(newTag, newTagOrder, callback);
} else {
removeTag(oldTag, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
addTag(newTag, newTagOrder, callback);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
}
}
//==============================================================================================================
// Room events dispatcher
//==============================================================================================================
/**
* Add an event listener to this room. Only events relative to the room will come down.
*
* @param eventListener the event listener to add
*/
public void addEventListener(final IMXEventListener eventListener) {
// sanity check
if (null == eventListener) {
Log.e(LOG_TAG, "addEventListener : eventListener is null");
return;
}
// GA crash : should never happen but got it.
if (null == mDataHandler) {
Log.e(LOG_TAG, "addEventListener : mDataHandler is null");
return;
}
// Create a global listener that we'll add to the data handler
IMXEventListener globalListener = new MXEventListener() {
@Override
public void onPresenceUpdate(Event event, User user) {
// Only pass event through if the user is a member of the room
if (getMember(user.user_id) != null) {
try {
eventListener.onPresenceUpdate(event, user);
} catch (Exception e) {
Log.e(LOG_TAG, "onPresenceUpdate exception " + e.getMessage());
}
}
}
@Override
public void onLiveEvent(Event event, RoomState roomState) {
// Filter out events for other rooms and events while we are joining (before the room is ready)
if (TextUtils.equals(getRoomId(), event.roomId) && mIsReady) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_TYPING)) {
// Typing notifications events are not room messages nor room state events
// They are just volatile information
JsonObject eventContent = event.getContentAsJsonObject();
if (eventContent.has("user_ids")) {
synchronized (Room.this) {
mTypingUsers = null;
try {
mTypingUsers = (new Gson()).fromJson(eventContent.get("user_ids"), new TypeToken<List<String>>() {
}.getType());
} catch (Exception e) {
Log.e(LOG_TAG, "onLiveEvent exception " + e.getMessage());
}
// avoid null list
if (null == mTypingUsers) {
mTypingUsers = new ArrayList<>();
}
}
}
}
try {
eventListener.onLiveEvent(event, roomState);
} catch (Exception e) {
Log.e(LOG_TAG, "onLiveEvent exception " + e.getMessage());
}
}
}
@Override
public void onLiveEventsChunkProcessed(String fromToken, String toToken) {
try {
eventListener.onLiveEventsChunkProcessed(fromToken, toToken);
} catch (Exception e) {
Log.e(LOG_TAG, "onLiveEventsChunkProcessed exception " + e.getMessage());
}
}
@Override
public void onEventEncrypted(Event event) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), event.roomId)) {
try {
eventListener.onEventEncrypted(event);
} catch (Exception e) {
Log.e(LOG_TAG, "onEventEncrypted exception " + e.getMessage());
}
}
}
@Override
public void onEventDecrypted(Event event) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), event.roomId)) {
try {
eventListener.onEventDecrypted(event);
} catch (Exception e) {
Log.e(LOG_TAG, "onDecryptedEvent exception " + e.getMessage());
}
}
}
@Override
public void onEventSent(final Event event, final String prevEventId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), event.roomId)) {
try {
eventListener.onEventSent(event, prevEventId);
} catch (Exception e) {
Log.e(LOG_TAG, "onEventSent exception " + e.getMessage());
}
}
}
@Override
public void onFailedSendingEvent(Event event) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), event.roomId)) {
try {
eventListener.onFailedSendingEvent(event);
} catch (Exception e) {
Log.e(LOG_TAG, "onFailedSendingEvent exception " + e.getMessage());
}
}
}
@Override
public void onRoomInitialSyncComplete(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onRoomInitialSyncComplete(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomInitialSyncComplete exception " + e.getMessage());
}
}
}
@Override
public void onRoomInternalUpdate(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onRoomInternalUpdate(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomInternalUpdate exception " + e.getMessage());
}
}
}
@Override
public void onNewRoom(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onNewRoom(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onNewRoom exception " + e.getMessage());
}
}
}
@Override
public void onJoinRoom(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onJoinRoom(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onJoinRoom exception " + e.getMessage());
}
}
}
@Override
public void onReceiptEvent(String roomId, List<String> senderIds) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onReceiptEvent(roomId, senderIds);
} catch (Exception e) {
Log.e(LOG_TAG, "onReceiptEvent exception " + e.getMessage());
}
}
}
@Override
public void onRoomTagEvent(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onRoomTagEvent(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomTagEvent exception " + e.getMessage());
}
}
}
@Override
public void onReadMarkerEvent(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onReadMarkerEvent(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onReadMarkerEvent exception " + e.getMessage());
}
}
}
@Override
public void onRoomFlush(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onRoomFlush(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomFlush exception " + e.getMessage());
}
}
}
@Override
public void onLeaveRoom(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onLeaveRoom(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onLeaveRoom exception " + e.getMessage());
}
}
}
};
mEventListeners.put(eventListener, globalListener);
// GA crash
if (null != mDataHandler) {
mDataHandler.addListener(globalListener);
}
}
/**
* Remove an event listener.
*
* @param eventListener the event listener to remove
*/
public void removeEventListener(IMXEventListener eventListener) {
// sanity check
if ((null != eventListener) && (null != mDataHandler)) {
mDataHandler.removeListener(mEventListeners.get(eventListener));
mEventListeners.remove(eventListener);
}
}
//==============================================================================================================
// Send methods
//==============================================================================================================
/**
* Send an event content to the room.
* The event is updated with the data provided by the server
* The provided event contains the error description.
*
* @param event the message
* @param callback the callback with the created event
*/
public void sendEvent(final Event event, final ApiCallback<Void> callback) {
// wait that the room is synced before sending messages
if (!mIsReady || !selfJoined()) {
event.mSentState = Event.SentState.WAITING_RETRY;
try {
callback.onNetworkError(null);
} catch (Exception e) {
Log.e(LOG_TAG, "sendEvent exception " + e.getMessage());
}
return;
}
final String prevEventId = event.eventId;
final ApiCallback<Event> localCB = new ApiCallback<Event>() {
@Override
public void onSuccess(final Event serverResponseEvent) {
// remove the tmp event
mStore.deleteEvent(event);
// replace the tmp event id by the final one
boolean isReadMarkerUpdated = TextUtils.equals(getReadMarkerEventId(), event.eventId);
// update the event with the server response
event.mSentState = Event.SentState.SENT;
event.eventId = serverResponseEvent.eventId;
event.originServerTs = System.currentTimeMillis();
// the message echo is not yet echoed
if (!mStore.doesEventExist(serverResponseEvent.eventId, getRoomId())) {
mStore.storeLiveRoomEvent(event);
}
// send the dedicated read receipt asap
markAllAsRead(isReadMarkerUpdated, null);
mStore.commit();
mDataHandler.onEventSent(event, prevEventId);
try {
callback.onSuccess(null);
} catch (Exception e) {
Log.e(LOG_TAG, "sendEvent exception " + e.getMessage());
}
}
@Override
public void onNetworkError(Exception e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentException = e;
try {
callback.onNetworkError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "sendEvent exception " + anException.getMessage());
}
}
@Override
public void onMatrixError(MatrixError e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentMatrixError = e;
if (TextUtils.equals(MatrixError.UNKNOWN_TOKEN, e.errcode)) {
mDataHandler.onInvalidToken();
} else {
try {
callback.onMatrixError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "sendEvent exception " + anException.getMessage());
}
}
}
@Override
public void onUnexpectedError(Exception e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentException = e;
try {
callback.onUnexpectedError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "sendEvent exception " + anException.getMessage());
}
}
};
if (isEncrypted() && (null != mDataHandler.getCrypto())) {
event.mSentState = Event.SentState.ENCRYPTING;
// Encrypt the content before sending
mDataHandler.getCrypto().encryptEventContent(event.getContent().getAsJsonObject(), event.getType(), this, new ApiCallback<MXEncryptEventContentResult>() {
@Override
public void onSuccess(MXEncryptEventContentResult encryptEventContentResult) {
// update the event content with the encrypted data
event.type = encryptEventContentResult.mEventType;
event.updateContent(encryptEventContentResult.mEventContent.getAsJsonObject());
mDataHandler.getCrypto().decryptEvent(event, null);
// warn the upper layer
mDataHandler.onEventEncrypted(event);
// sending in progress
event.mSentState = Event.SentState.SENDING;
mDataHandler.getDataRetriever().getRoomsRestClient().sendEventToRoom(event.originServerTs + "", getRoomId(), encryptEventContentResult.mEventType, encryptEventContentResult.mEventContent.getAsJsonObject(), localCB);
}
@Override
public void onNetworkError(Exception e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentException = e;
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
// update the sent state if the message encryption failed because there are unknown devices.
if ((e instanceof MXCryptoError) && TextUtils.equals(((MXCryptoError) e).errcode, MXCryptoError.UNKNOWN_DEVICES_CODE)) {
event.mSentState = Event.SentState.FAILED_UNKNOWN_DEVICES;
} else {
event.mSentState = Event.SentState.UNDELIVERABLE;
}
event.unsentMatrixError = e;
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentException = e;
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
} else {
event.mSentState = Event.SentState.SENDING;
if (Event.EVENT_TYPE_MESSAGE.equals(event.getType())) {
mDataHandler.getDataRetriever().getRoomsRestClient().sendMessage(event.originServerTs + "", getRoomId(), JsonUtils.toMessage(event.getContent()), localCB);
} else {
mDataHandler.getDataRetriever().getRoomsRestClient().sendEventToRoom(event.originServerTs + "", getRoomId(), event.getType(), event.getContent().getAsJsonObject(), localCB);
}
}
}
/**
* Cancel the event sending.
* Any media upload will be cancelled too.
* The event becomes undeliverable.
*
* @param event the message
*/
public void cancelEventSending(final Event event) {
if (null != event) {
if ((Event.SentState.UNSENT == event.mSentState) ||
(Event.SentState.SENDING == event.mSentState) ||
(Event.SentState.WAITING_RETRY == event.mSentState) ||
(Event.SentState.ENCRYPTING == event.mSentState)) {
// the message cannot be sent anymore
event.mSentState = Event.SentState.UNDELIVERABLE;
}
List<String> urls = event.getMediaUrls();
MXMediasCache cache = mDataHandler.getMediasCache();
for (String url : urls) {
cache.cancelUpload(url);
cache.cancelDownload(cache.downloadIdFromUrl(url));
}
}
}
/**
* Redact an event from the room.
*
* @param eventId the event's id
* @param callback the callback with the redacted event
*/
public void redact(final String eventId, final ApiCallback<Event> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().redactEvent(getRoomId(), eventId, new ApiCallback<Event>() {
@Override
public void onSuccess(Event event) {
Event redactedEvent = mStore.getEvent(eventId, getRoomId());
// test if the redacted event has been echoed
// it it was not echoed, the event must be pruned to remove useless data
// the room summary will be updated when the server will echo the redacted event
if ((null != redactedEvent) && ((null == redactedEvent.unsigned) || (null == redactedEvent.unsigned.redacted_because))) {
redactedEvent.prune(null);
mStore.storeLiveRoomEvent(redactedEvent);
mStore.commit();
}
if (null != callback) {
callback.onSuccess(redactedEvent);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
/**
* Redact an event from the room.
*
* @param eventId the event's id
* @param callback the callback with the created event
*/
public void report(String eventId, int score, String reason, ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().reportEvent(getRoomId(), eventId, score, reason, callback);
}
//================================================================================
// Member actions
//================================================================================
/**
* Invite an user to this room.
*
* @param userId the user id
* @param callback the callback for when done
*/
public void invite(String userId, ApiCallback<Void> callback) {
if (null != userId) {
invite(Collections.singletonList(userId), callback);
}
}
/**
* Invite an user to a room based on their email address to this room.
*
* @param email the email address
* @param callback the callback for when done
*/
public void inviteByEmail(String email, ApiCallback<Void> callback) {
if (null != email) {
invite(Collections.singletonList(email), callback);
}
}
/**
* Invite users to this room.
* The identifiers are either ini Id or email address.
*
* @param identifiers the identifiers list
* @param callback the callback for when done
*/
public void invite(List<String> identifiers, ApiCallback<Void> callback) {
if (null != identifiers) {
invite(identifiers.iterator(), callback);
}
}
/**
* Invite some users to this room.
*
* @param identifiers the identifiers iterator
* @param callback the callback for when done
*/
private void invite(final Iterator<String> identifiers, final ApiCallback<Void> callback) {
if (!identifiers.hasNext()) {
callback.onSuccess(null);
return;
}
final ApiCallback<Void> localCallback = new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
invite(identifiers, callback);
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "## invite failed " + e.getMessage());
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "## invite failed " + e.getMessage());
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "## invite failed " + e.getMessage());
if (null != callback) {
callback.onUnexpectedError(e);
}
}
};
String identifier = identifiers.next();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(identifier).matches()) {
mDataHandler.getDataRetriever().getRoomsRestClient().inviteByEmailToRoom(getRoomId(), identifier, localCallback);
} else {
mDataHandler.getDataRetriever().getRoomsRestClient().inviteUserToRoom(getRoomId(), identifier, localCallback);
}
}
/**
* Leave the room.
*
* @param callback the callback for when done
*/
public void leave(final ApiCallback<Void> callback) {
this.mIsLeaving = true;
mDataHandler.onRoomInternalUpdate(getRoomId());
mDataHandler.getDataRetriever().getRoomsRestClient().leaveRoom(getRoomId(), new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (mDataHandler.isAlive()) {
Room.this.mIsLeaving = false;
// delete references to the room
mDataHandler.deleteRoom(getRoomId());
Log.d(LOG_TAG, "leave : commit");
mStore.commit();
try {
callback.onSuccess(info);
} catch (Exception e) {
Log.e(LOG_TAG, "leave exception " + e.getMessage());
}
mDataHandler.onLeaveRoom(getRoomId());
}
}
@Override
public void onNetworkError(Exception e) {
Room.this.mIsLeaving = false;
try {
callback.onNetworkError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "leave exception " + anException.getMessage());
}
mDataHandler.onRoomInternalUpdate(getRoomId());
}
@Override
public void onMatrixError(MatrixError e) {
// the room was not anymore defined server side
// race condition ?
if (e.mStatus == 404) {
onSuccess(null);
} else {
Room.this.mIsLeaving = false;
try {
callback.onMatrixError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "leave exception " + anException.getMessage());
}
mDataHandler.onRoomInternalUpdate(getRoomId());
}
}
@Override
public void onUnexpectedError(Exception e) {
Room.this.mIsLeaving = false;
try {
callback.onUnexpectedError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "leave exception " + anException.getMessage());
}
mDataHandler.onRoomInternalUpdate(getRoomId());
}
});
}
/**
* Forget the room.
*
* @param callback the callback for when done
*/
public void forget(final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().forgetRoom(getRoomId(), new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (mDataHandler.isAlive()) {
// don't call onSuccess.deleteRoom because it moves an existing room to historical store
IMXStore store = mDataHandler.getStore(getRoomId());
if (null != store) {
store.deleteRoom(getRoomId());
mStore.commit();
}
try {
callback.onSuccess(info);
} catch (Exception e) {
Log.e(LOG_TAG, "forget exception " + e.getMessage());
}
}
}
@Override
public void onNetworkError(Exception e) {
try {
callback.onNetworkError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "forget exception " + anException.getMessage());
}
}
@Override
public void onMatrixError(MatrixError e) {
try {
callback.onMatrixError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "forget exception " + anException.getMessage());
}
}
@Override
public void onUnexpectedError(Exception e) {
try {
callback.onUnexpectedError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "forget exception " + anException.getMessage());
}
}
});
}
/**
* Kick a user from the room.
*
* @param userId the user id
* @param callback the async callback
*/
public void kick(String userId, ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().kickFromRoom(getRoomId(), userId, callback);
}
/**
* Ban a user from the room.
*
* @param userId the user id
* @param reason ban reason
* @param callback the async callback
*/
public void ban(String userId, String reason, ApiCallback<Void> callback) {
BannedUser user = new BannedUser();
user.userId = userId;
if (!TextUtils.isEmpty(reason)) {
user.reason = reason;
}
mDataHandler.getDataRetriever().getRoomsRestClient().banFromRoom(getRoomId(), user, callback);
}
/**
* Unban a user.
*
* @param userId the user id
* @param callback the async callback
*/
public void unban(String userId, ApiCallback<Void> callback) {
BannedUser user = new BannedUser();
user.userId = userId;
mDataHandler.getDataRetriever().getRoomsRestClient().unbanFromRoom(getRoomId(), user, callback);
}
//================================================================================
// Encryption
//================================================================================
private ApiCallback<Void> mRoomEncryptionCallback;
private final MXEventListener mEncryptionListener = new MXEventListener() {
@Override
public void onLiveEvent(Event event, RoomState roomState) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE_ENCRYPTION)) {
if (null != mRoomEncryptionCallback) {
mRoomEncryptionCallback.onSuccess(null);
mRoomEncryptionCallback = null;
}
}
}
};
/**
* @return if the room content is encrypted
*/
public boolean isEncrypted() {
return !TextUtils.isEmpty(getLiveState().algorithm);
}
/**
* Enable the encryption.
*
* @param algorithm the used algorithm
* @param callback the asynchronous callback
*/
public void enableEncryptionWithAlgorithm(final String algorithm, final ApiCallback<Void> callback) {
// ensure that the crypto has been update
if (null != mDataHandler.getCrypto() && !TextUtils.isEmpty(algorithm)) {
HashMap<String, Object> params = new HashMap<>();
params.put("algorithm", algorithm);
if (null != callback) {
mRoomEncryptionCallback = callback;
addEventListener(mEncryptionListener);
}
mDataHandler.getDataRetriever().getRoomsRestClient().sendStateEvent(getRoomId(), Event.EVENT_TYPE_MESSAGE_ENCRYPTION, null, params, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// Wait for the event coming back from the hs
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
removeEventListener(mEncryptionListener);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
removeEventListener(mEncryptionListener);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
removeEventListener(mEncryptionListener);
}
}
});
} else if (null != callback) {
if (null == mDataHandler.getCrypto()) {
callback.onMatrixError(new MXCryptoError(MXCryptoError.ENCRYPTING_NOT_ENABLED_ERROR_CODE, MXCryptoError.ENCRYPTING_NOT_ENABLED_REASON, MXCryptoError.ENCRYPTING_NOT_ENABLED_REASON));
} else {
callback.onMatrixError(new MXCryptoError(MXCryptoError.MISSING_FIELDS_ERROR_CODE, MXCryptoError.UNABLE_TO_ENCRYPT, MXCryptoError.MISSING_FIELDS_REASON));
}
}
}
//==============================================================================================================
// Room events helper
//==============================================================================================================
private RoomMediaMessagesSender mRoomMediaMessagesSender;
/**
* Init the mRoomDataItemsSender instance
*/
private void initRoomDataItemsSender() {
if (null == mRoomMediaMessagesSender) {
mRoomMediaMessagesSender = new RoomMediaMessagesSender(mDataHandler.getStore().getContext(), mDataHandler, this);
}
}
/**
* Send a text message asynchronously.
*
* @param text the unformatted text
* @param HTMLFormattedText the HTML formatted text
* @param format the formatted text format
* @param listener the event creation listener
*/
public void sendTextMessage(String text, String HTMLFormattedText, String format, RoomMediaMessage.EventCreationListener listener) {
sendTextMessage(text, HTMLFormattedText, format, Message.MSGTYPE_TEXT, listener);
}
/**
* Send an emote message asynchronously.
*
* @param text the unformatted text
* @param HTMLFormattedText the HTML formatted text
* @param format the formatted text format
* @param listener the event creation listener
*/
public void sendEmoteMessage(String text, String HTMLFormattedText, String format, final RoomMediaMessage.EventCreationListener listener) {
sendTextMessage(text, HTMLFormattedText, format, Message.MSGTYPE_EMOTE, listener);
}
/**
* Send a text message asynchronously.
*
* @param text the unformatted text
* @param HTMLFormattedText the HTML formatted text
* @param format the formatted text format
* @param msgType the message type
* @param listener the event creation listener
*/
private void sendTextMessage(String text, String HTMLFormattedText, String format, String msgType, final RoomMediaMessage.EventCreationListener listener) {
initRoomDataItemsSender();
RoomMediaMessage roomMediaMessage = new RoomMediaMessage(text, HTMLFormattedText, format);
roomMediaMessage.setMessageType(msgType);
roomMediaMessage.setEventCreationListener(listener);
mRoomMediaMessagesSender.send(roomMediaMessage);
}
/**
* Send an media message asynchronously
*
* @param roomMediaMessage the media message
*/
public void sendMediaMessage(final RoomMediaMessage roomMediaMessage, final int maxThumbnailWidth, final int maxThumbnailHeight, final RoomMediaMessage.EventCreationListener listener) {
initRoomDataItemsSender();
roomMediaMessage.setThumnailSize(new Pair<>(maxThumbnailWidth, maxThumbnailHeight));
roomMediaMessage.setEventCreationListener(listener);
mRoomMediaMessagesSender.send(roomMediaMessage);
}
//==============================================================================================================
// Unsent events managemenet
//==============================================================================================================
/**
* Provides the unsent messages list.
*
* @return the unsent events list
*/
public List<Event> getUnsentEvents() {
List<Event> unsent = new ArrayList<>();
List<Event> undeliverableEvents = mDataHandler.getStore().getUndeliverableEvents(getRoomId());
List<Event> unknownDeviceEvents = mDataHandler.getStore().getUnknownDeviceEvents(getRoomId());
if (null != undeliverableEvents) {
unsent.addAll(undeliverableEvents);
}
if (null != unknownDeviceEvents) {
unsent.addAll(unknownDeviceEvents);
}
return unsent;
}
/**
* Delete an events list.
*
* @param events the events list
*/
public void deleteEvents(List<Event> events) {
if ((null != events) && events.size() > 0) {
IMXStore store = mDataHandler.getStore();
// reset the timestamp
for (Event event : events) {
store.deleteEvent(event);
}
// update the summary
Event latestEvent = store.getLatestEvent(getRoomId());
// if there is an oldest event, use it to set a summary
if (latestEvent != null) {
if (RoomSummary.isSupportedEvent(latestEvent)) {
RoomSummary summary = store.getSummary(getRoomId());
if (null != summary) {
summary.setLatestReceivedEvent(latestEvent, getState());
} else {
summary = new RoomSummary(null, latestEvent, getState(), mDataHandler.getUserId());
}
store.storeSummary(summary);
}
}
store.commit();
}
}
}
|
matrix-sdk/src/main/java/org/matrix/androidsdk/data/Room.java
|
/*
* Copyright 2014 OpenMarket Ltd
* Copyright 2017 Vector Creations Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.data;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.HandlerThread;
import android.os.Looper;
import android.text.TextUtils;
import android.os.Handler;
import android.util.Pair;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.matrix.androidsdk.MXDataHandler;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.adapters.MessageRow;
import org.matrix.androidsdk.call.MXCallsManager;
import org.matrix.androidsdk.crypto.MXCryptoError;
import org.matrix.androidsdk.crypto.MXEncryptedAttachments;
import org.matrix.androidsdk.crypto.data.MXEncryptEventContentResult;
import org.matrix.androidsdk.data.store.IMXStore;
import org.matrix.androidsdk.db.MXMediasCache;
import org.matrix.androidsdk.listeners.IMXEventListener;
import org.matrix.androidsdk.listeners.MXEventListener;
import org.matrix.androidsdk.listeners.MXMediaUploadListener;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.callback.SimpleApiCallback;
import org.matrix.androidsdk.rest.client.RoomsRestClient;
import org.matrix.androidsdk.rest.client.UrlPostTask;
import org.matrix.androidsdk.rest.model.BannedUser;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.EventContext;
import org.matrix.androidsdk.rest.model.FileInfo;
import org.matrix.androidsdk.rest.model.FileMessage;
import org.matrix.androidsdk.rest.model.ImageInfo;
import org.matrix.androidsdk.rest.model.ImageMessage;
import org.matrix.androidsdk.rest.model.LocationMessage;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.Message;
import org.matrix.androidsdk.rest.model.PowerLevels;
import org.matrix.androidsdk.rest.model.ReceiptData;
import org.matrix.androidsdk.rest.model.RoomMember;
import org.matrix.androidsdk.rest.model.RoomResponse;
import org.matrix.androidsdk.rest.model.Sync.InvitedRoomSync;
import org.matrix.androidsdk.rest.model.Sync.RoomSync;
import org.matrix.androidsdk.rest.model.ThumbnailInfo;
import org.matrix.androidsdk.rest.model.TokensChunkResponse;
import org.matrix.androidsdk.rest.model.User;
import org.matrix.androidsdk.rest.model.VideoInfo;
import org.matrix.androidsdk.rest.model.VideoMessage;
import org.matrix.androidsdk.util.ImageUtils;
import org.matrix.androidsdk.util.JsonUtils;
import org.matrix.androidsdk.util.Log;
import org.matrix.androidsdk.util.MXOsHandler;
import org.matrix.androidsdk.util.ResourceUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Class representing a room and the interactions we have with it.
*/
public class Room {
private static final String LOG_TAG = "Room";
// Account data
private RoomAccountData mAccountData = new RoomAccountData();
// handler
private MXDataHandler mDataHandler;
// store
private IMXStore mStore;
private String mMyUserId = null;
// Map to keep track of the listeners the client adds vs. the ones we actually register to the global data handler.
// This is needed to find the right one when removing the listener.
private final Map<IMXEventListener, IMXEventListener> mEventListeners = new HashMap<>();
// the user is leaving the room
private boolean mIsLeaving = false;
// the room is syncing
private boolean mIsSyncing;
// the unread messages count must be refreshed when the current sync is done.
private boolean mRefreshUnreadAfterSync = false;
// the time line
private EventTimeline mLiveTimeline;
// initial sync callback.
private ApiCallback<Void> mOnInitialSyncCallback;
// gson parser
private final Gson gson = new GsonBuilder().create();
// This is used to block live events and history requests until the state is fully processed and ready
private boolean mIsReady = false;
// call conference user id
private String mCallConferenceUserId;
// true when the current room is a left one
private boolean mIsLeft;
/**
* Default room creator
*/
public Room() {
mLiveTimeline = new EventTimeline(this, true);
}
/**
* Init the room fields.
*
* @param store the store.
* @param roomId the room id
* @param dataHandler the data handler
*/
public void init(IMXStore store, String roomId, MXDataHandler dataHandler) {
mLiveTimeline.setRoomId(roomId);
mDataHandler = dataHandler;
mStore = store;
if (null != mDataHandler) {
mMyUserId = mDataHandler.getUserId();
mLiveTimeline.setDataHandler(mStore, dataHandler);
}
}
/**
* @return the used datahandler
*/
public MXDataHandler getDataHandler() {
return mDataHandler;
}
/**
* @return the store in which the room is stored
*/
public IMXStore getStore() {
return mStore;
}
/**
* Tells if the room is a call conference one
* i.e. this room has been created to manage the call conference
*
* @return true if it is a call conference room.
*/
public boolean isConferenceUserRoom() {
return getLiveState().isConferenceUserRoom();
}
/**
* Set this room as a conference user room
*
* @param isConferenceUserRoom true when it is an user conference room.
*/
public void setIsConferenceUserRoom(boolean isConferenceUserRoom) {
getLiveState().setIsConferenceUserRoom(isConferenceUserRoom);
}
/**
* Test if there is an ongoing conference call.
*
* @return true if there is one.
*/
public boolean isOngoingConferenceCall() {
RoomMember conferenceUser = getLiveState().getMember(MXCallsManager.getConferenceUserId(getRoomId()));
return (null != conferenceUser) && TextUtils.equals(conferenceUser.membership, RoomMember.MEMBERSHIP_JOIN);
}
/**
* Defines that the current room is a left one
*
* @param isLeft true when the current room is a left one
*/
public void setIsLeft(boolean isLeft) {
mIsLeft = isLeft;
mLiveTimeline.setIsHistorical(isLeft);
}
/**
* @return true if the current room is an left one
*/
public boolean isLeft() {
return mIsLeft;
}
//================================================================================
// Sync events
//================================================================================
/**
* Manage list of ephemeral events
*
* @param events the ephemeral events
*/
private void handleEphemeralEvents(List<Event> events) {
for (Event event : events) {
// ensure that the room Id is defined
event.roomId = getRoomId();
try {
if (Event.EVENT_TYPE_RECEIPT.equals(event.getType())) {
if (event.roomId != null) {
List<String> senders = handleReceiptEvent(event);
if ((null != senders) && (senders.size() > 0)) {
mDataHandler.onReceiptEvent(event.roomId, senders);
}
}
} else if (Event.EVENT_TYPE_TYPING.equals(event.getType())) {
mDataHandler.onLiveEvent(event, getState());
}
} catch (Exception e) {
Log.e(LOG_TAG, "ephemeral event failed " + e.getMessage());
}
}
}
/**
* Handle the events of a joined room.
*
* @param roomSync the sync events list.
* @param isGlobalInitialSync true if the room is initialized by a global initial sync.
*/
public void handleJoinedRoomSync(RoomSync roomSync, boolean isGlobalInitialSync) {
if (null != mOnInitialSyncCallback) {
Log.d(LOG_TAG, "initial sync handleJoinedRoomSync " + getRoomId());
} else {
Log.d(LOG_TAG, "handleJoinedRoomSync " + getRoomId());
}
mIsSyncing = true;
synchronized (this) {
mLiveTimeline.handleJoinedRoomSync(roomSync, isGlobalInitialSync);
// ephemeral events
if ((null != roomSync.ephemeral) && (null != roomSync.ephemeral.events)) {
handleEphemeralEvents(roomSync.ephemeral.events);
}
// Handle account data events (if any)
if ((null != roomSync.accountData) && (null != roomSync.accountData.events) && (roomSync.accountData.events.size() > 0)) {
if (isGlobalInitialSync) {
Log.d(LOG_TAG, "## handleJoinedRoomSync : received " + roomSync.accountData.events.size() + " account data events");
}
handleAccountDataEvents(roomSync.accountData.events);
}
}
// the user joined the room
// With V2 sync, the server sends the events to init the room.
if (null != mOnInitialSyncCallback) {
Log.d(LOG_TAG, "handleJoinedRoomSync " + getRoomId() + " : the initial sync is done");
final ApiCallback<Void> fOnInitialSyncCallback = mOnInitialSyncCallback;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
try {
fOnInitialSyncCallback.onSuccess(null);
} catch (Exception e) {
Log.e(LOG_TAG, "handleJoinedRoomSync : onSuccess failed" + e.getMessage());
}
}
});
mOnInitialSyncCallback = null;
}
mIsSyncing = false;
if (mRefreshUnreadAfterSync) {
if (!isGlobalInitialSync) {
refreshUnreadCounter();
} // else -> it will be done at the end of the sync
mRefreshUnreadAfterSync = false;
}
}
/**
* Handle the invitation room events
*
* @param invitedRoomSync the invitation room events.
*/
public void handleInvitedRoomSync(InvitedRoomSync invitedRoomSync) {
mLiveTimeline.handleInvitedRoomSync(invitedRoomSync);
}
/**
* Store an outgoing event.
*
* @param event the event.
*/
public void storeOutgoingEvent(Event event) {
mLiveTimeline.storeOutgoingEvent(event);
}
/**
* Request events to the server. The local cache is not used.
* The events will not be saved in the local storage.
*
* @param token the token to go back from.
* @param paginationCount the number of events to retrieve.
* @param callback the onComplete callback
*/
public void requestServerRoomHistory(final String token, final int paginationCount, final ApiCallback<TokensChunkResponse<Event>> callback) {
mDataHandler.getDataRetriever().requestServerRoomHistory(getRoomId(), token, paginationCount, new SimpleApiCallback<TokensChunkResponse<Event>>(callback) {
@Override
public void onSuccess(TokensChunkResponse<Event> info) {
callback.onSuccess(info);
}
});
}
/**
* cancel any remote request
*/
public void cancelRemoteHistoryRequest() {
mDataHandler.getDataRetriever().cancelRemoteHistoryRequest(getRoomId());
}
//================================================================================
// Getters / setters
//================================================================================
public String getRoomId() {
return mLiveTimeline.getState().roomId;
}
public void setAccountData(RoomAccountData accountData) {
this.mAccountData = accountData;
}
public RoomAccountData getAccountData() {
return this.mAccountData;
}
public RoomState getState() {
return mLiveTimeline.getState();
}
public RoomState getLiveState() {
return getState();
}
public boolean isLeaving() {
return mIsLeaving;
}
public Collection<RoomMember> getMembers() {
return getState().getMembers();
}
public EventTimeline getLiveTimeLine() {
return mLiveTimeline;
}
public void setLiveTimeline(EventTimeline eventTimeline) {
mLiveTimeline = eventTimeline;
}
public void setReadyState(boolean isReady) {
mIsReady = isReady;
}
public boolean isReady() {
return mIsReady;
}
/**
* @return the list of active members in a room ie joined or invited ones.
*/
public Collection<RoomMember> getActiveMembers() {
Collection<RoomMember> members = getState().getMembers();
List<RoomMember> activeMembers = new ArrayList<>();
String conferenceUserId = MXCallsManager.getConferenceUserId(getRoomId());
for (RoomMember member : members) {
if (!TextUtils.equals(member.getUserId(), conferenceUserId)) {
if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_JOIN) || TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_INVITE)) {
activeMembers.add(member);
}
}
}
return activeMembers;
}
/**
* Get the list of the members who have joined the room.
*
* @return the list the joined members of the room.
*/
public Collection<RoomMember> getJoinedMembers() {
Collection<RoomMember> membersList = getState().getMembers();
List<RoomMember> joinedMembersList = new ArrayList<>();
for (RoomMember member : membersList) {
if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_JOIN)) {
joinedMembersList.add(member);
}
}
return joinedMembersList;
}
public RoomMember getMember(String userId) {
return getState().getMember(userId);
}
// member event caches
private final Map<String, Event> mMemberEventByEventId = new HashMap<>();
public void getMemberEvent(final String userId, final ApiCallback<Event> callback) {
final Event event;
final RoomMember member = getMember(userId);
if ((null != member) && (null != member.getOriginalEventId())) {
event = mMemberEventByEventId.get(member.getOriginalEventId());
if (null == event) {
mDataHandler.getDataRetriever().getRoomsRestClient().getContextOfEvent(getRoomId(), member.getOriginalEventId(), 1, new ApiCallback<EventContext>() {
@Override
public void onSuccess(EventContext eventContext) {
if (null != eventContext.event) {
mMemberEventByEventId.put(eventContext.event.eventId, eventContext.event);
}
callback.onSuccess(eventContext.event);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
return;
}
} else {
event = null;
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
callback.onSuccess(event);
}
});
}
public String getTopic() {
return this.getState().topic;
}
public String getName(String selfUserId) {
return getState().getDisplayName(selfUserId);
}
public String getVisibility() {
return getState().visibility;
}
/**
* @return true if the user is invited to the room
*/
public boolean isInvited() {
// Is it an initial sync for this room ?
RoomState state = getState();
String membership = null;
RoomMember selfMember = state.getMember(mMyUserId);
if (null != selfMember) {
membership = selfMember.membership;
}
return TextUtils.equals(membership, RoomMember.MEMBERSHIP_INVITE);
}
/**
* @return true if the user is invited in a direct chat room
*/
public boolean isDirectChatInvitation() {
if (isInvited()) {
// Is it an initial sync for this room ?
RoomState state = getState();
RoomMember selfMember = state.getMember(mMyUserId);
if ((null != selfMember) && (null != selfMember.is_direct)) {
return selfMember.is_direct;
}
}
return false;
}
//================================================================================
// Join
//================================================================================
/**
* Defines the initial sync callback
*
* @param callback the new callback.
*/
public void setOnInitialSyncCallback(ApiCallback<Void> callback) {
mOnInitialSyncCallback = callback;
}
/**
* Join a room with an url to post before joined the room.
*
* @param alias the room alias
* @param thirdPartySignedUrl the thirdPartySigned url
* @param callback the callback
*/
public void joinWithThirdPartySigned(final String alias, final String thirdPartySignedUrl, final ApiCallback<Void> callback) {
if (null == thirdPartySignedUrl) {
join(alias, callback);
} else {
String url = thirdPartySignedUrl + "&mxid=" + mMyUserId;
UrlPostTask task = new UrlPostTask();
task.setListener(new UrlPostTask.IPostTaskListener() {
@Override
public void onSucceed(JsonObject object) {
HashMap<String, Object> map = null;
try {
map = new Gson().fromJson(object, new TypeToken<HashMap<String, Object>>() {
}.getType());
} catch (Exception e) {
Log.e(LOG_TAG, "joinWithThirdPartySigned : Gson().fromJson failed" + e.getMessage());
}
if (null != map) {
HashMap<String, Object> joinMap = new HashMap<>();
joinMap.put("third_party_signed", map);
join(alias, joinMap, callback);
} else {
join(callback);
}
}
@Override
public void onError(String errorMessage) {
Log.d(LOG_TAG, "joinWithThirdPartySigned failed " + errorMessage);
// cannot validate the url
// try without validating the url
join(callback);
}
});
// avoid crash if there are too many running task
try {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
} catch (final Exception e) {
task.cancel(true);
Log.e(LOG_TAG, "joinWithThirdPartySigned : task.executeOnExecutor failed" + e.getMessage());
(new android.os.Handler(Looper.getMainLooper())).post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
}
/**
* Join the room. If successful, the room's current state will be loaded before calling back onComplete.
*
* @param callback the callback for when done
*/
public void join(final ApiCallback<Void> callback) {
join(null, null, callback);
}
/**
* Join the room. If successful, the room's current state will be loaded before calling back onComplete.
*
* @param roomAlias the room alias
* @param callback the callback for when done
*/
private void join(String roomAlias, ApiCallback<Void> callback) {
join(roomAlias, null, callback);
}
/**
* Join the room. If successful, the room's current state will be loaded before calling back onComplete.
*
* @param roomAlias the room alias
* @param extraParams the join extra params
* @param callback the callback for when done
*/
private void join(String roomAlias, HashMap<String, Object> extraParams, final ApiCallback<Void> callback) {
Log.d(LOG_TAG, "Join the room " + getRoomId() + " with alias " + roomAlias);
mDataHandler.getDataRetriever().getRoomsRestClient().joinRoom((null != roomAlias) ? roomAlias : getRoomId(), extraParams, new SimpleApiCallback<RoomResponse>(callback) {
@Override
public void onSuccess(final RoomResponse aResponse) {
try {
boolean isRoomMember;
synchronized (this) {
isRoomMember = (getState().getMember(mMyUserId) != null);
}
// the join request did not get the room initial history
if (!isRoomMember) {
Log.d(LOG_TAG, "the room " + getRoomId() + " is joined but wait after initial sync");
// wait the server sends the events chunk before calling the callback
setOnInitialSyncCallback(callback);
} else {
Log.d(LOG_TAG, "the room " + getRoomId() + " is joined : the initial sync has been done");
// already got the initial sync
callback.onSuccess(null);
}
} catch (Exception e) {
Log.e(LOG_TAG, "join exception " + e.getMessage());
}
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "join onNetworkError " + e.getMessage());
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "join onMatrixError " + e.getMessage());
if (MatrixError.UNKNOWN.equals(e.errcode) && TextUtils.equals("No known servers", e.error)) {
// minging kludge until https://matrix.org/jira/browse/SYN-678 is fixed
// 'Error when trying to join an empty room should be more explicit
e.error = mStore.getContext().getString(org.matrix.androidsdk.R.string.room_error_join_failed_empty_room);
}
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "join onUnexpectedError " + e.getMessage());
callback.onUnexpectedError(e);
}
});
}
/**
* @return true if the user joined the room
*/
private boolean selfJoined() {
RoomMember roomMember = getMember(mMyUserId);
// send the event only if the user has joined the room.
return ((null != roomMember) && RoomMember.MEMBERSHIP_JOIN.equals(roomMember.membership));
}
//================================================================================
// Room info (liveState) update
//================================================================================
/**
* This class dispatches the error to the dedicated callbacks.
* If the operation succeeds, the room state is saved because calling the callback.
*/
private class RoomInfoUpdateCallback<T> implements ApiCallback<T> {
private final ApiCallback<T> mCallback;
/**
* Constructor
*/
public RoomInfoUpdateCallback(ApiCallback<T> callback) {
mCallback = callback;
}
@Override
public void onSuccess(T info) {
mStore.storeLiveStateForRoom(getRoomId());
if (null != mCallback) {
mCallback.onSuccess(info);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != mCallback) {
mCallback.onNetworkError(e);
}
}
@Override
public void onMatrixError(final MatrixError e) {
if (null != mCallback) {
mCallback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(final Exception e) {
if (null != mCallback) {
mCallback.onUnexpectedError(e);
}
}
}
/**
* Update the power level of the user userId
*
* @param userId the user id
* @param powerLevel the new power level
* @param callback the callback with the created event
*/
public void updateUserPowerLevels(String userId, int powerLevel, ApiCallback<Void> callback) {
PowerLevels powerLevels = getState().getPowerLevels().deepCopy();
powerLevels.setUserPowerLevel(userId, powerLevel);
mDataHandler.getDataRetriever().getRoomsRestClient().updatePowerLevels(getRoomId(), powerLevels, callback);
}
/**
* Update the room's name.
*
* @param aRoomName the new name
* @param callback the async callback
*/
public void updateName(String aRoomName, final ApiCallback<Void> callback) {
final String fRoomName = TextUtils.isEmpty(aRoomName) ? null : aRoomName;
mDataHandler.getDataRetriever().getRoomsRestClient().updateRoomName(getRoomId(), fRoomName, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().name = fRoomName;
super.onSuccess(info);
}
});
}
/**
* Update the room's topic.
*
* @param aTopic the new topic
* @param callback the async callback
*/
public void updateTopic(final String aTopic, final ApiCallback<Void> callback) {
final String fTopic = TextUtils.isEmpty(aTopic) ? null : aTopic;
mDataHandler.getDataRetriever().getRoomsRestClient().updateTopic(getRoomId(), fTopic, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().topic = fTopic;
super.onSuccess(info);
}
});
}
/**
* Update the room's main alias.
*
* @param aCanonicalAlias the canonical alias
* @param callback the async callback
*/
public void updateCanonicalAlias(final String aCanonicalAlias, final ApiCallback<Void> callback) {
final String fCanonicalAlias = TextUtils.isEmpty(aCanonicalAlias) ? null : aCanonicalAlias;
mDataHandler.getDataRetriever().getRoomsRestClient().updateCanonicalAlias(getRoomId(), fCanonicalAlias, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().roomAliasName = fCanonicalAlias;
super.onSuccess(info);
}
});
}
/**
* Provides the room aliases list.
* The result is never null.
*
* @return the room aliases list.
*/
public List<String> getAliases() {
return getLiveState().getAliases();
}
/**
* Remove a room alias.
*
* @param alias the alias to remove
* @param callback the async callback
*/
public void removeAlias(final String alias, final ApiCallback<Void> callback) {
final List<String> updatedAliasesList = new ArrayList<>(getAliases());
// nothing to do
if (TextUtils.isEmpty(alias) || (updatedAliasesList.indexOf(alias) < 0)) {
if (null != callback) {
callback.onSuccess(null);
}
return;
}
mDataHandler.getDataRetriever().getRoomsRestClient().removeRoomAlias(alias, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().removeAlias(alias);
super.onSuccess(info);
}
});
}
/**
* Try to add an alias to the aliases list.
*
* @param alias the alias to add.
* @param callback the the async callback
*/
public void addAlias(final String alias, final ApiCallback<Void> callback) {
final List<String> updatedAliasesList = new ArrayList<>(getAliases());
// nothing to do
if (TextUtils.isEmpty(alias) || (updatedAliasesList.indexOf(alias) >= 0)) {
if (null != callback) {
callback.onSuccess(null);
}
return;
}
mDataHandler.getDataRetriever().getRoomsRestClient().setRoomIdByAlias(getRoomId(), alias, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().addAlias(alias);
super.onSuccess(info);
}
});
}
/**
* @return the room avatar URL. If there is no defined one, use the members one (1:1 chat only).
*/
public String getAvatarUrl() {
String res = getState().getAvatarUrl();
// detect if it is a room with no more than 2 members (i.e. an alone or a 1:1 chat)
if (null == res) {
List<RoomMember> members = new ArrayList<>(getState().getMembers());
if (members.size() == 1) {
res = members.get(0).getAvatarUrl();
} else if (members.size() == 2) {
RoomMember m1 = members.get(0);
RoomMember m2 = members.get(1);
res = TextUtils.equals(m1.getUserId(), mMyUserId) ? m2.getAvatarUrl() : m1.getAvatarUrl();
}
}
return res;
}
/**
* The call avatar is the same as the room avatar except there are only 2 JOINED members.
* In this case, it returns the avtar of the other joined member.
*
* @return the call avatar URL.
*/
public String getCallAvatarUrl() {
String avatarURL;
List<RoomMember> joinedMembers = new ArrayList<>(getJoinedMembers());
// 2 joined members case
if (2 == joinedMembers.size()) {
// use other member avatar.
if (TextUtils.equals(mMyUserId, joinedMembers.get(0).getUserId())) {
avatarURL = joinedMembers.get(1).getAvatarUrl();
} else {
avatarURL = joinedMembers.get(0).getAvatarUrl();
}
} else {
//
avatarURL = getAvatarUrl();
}
return avatarURL;
}
/**
* Update the room avatar URL.
*
* @param avatarUrl the new avatar URL
* @param callback the async callback
*/
public void updateAvatarUrl(final String avatarUrl, final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateAvatarUrl(getRoomId(), avatarUrl, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().url = avatarUrl;
super.onSuccess(info);
}
});
}
/**
* Update the room's history visibility
*
* @param historyVisibility the visibility (should be one of RoomState.HISTORY_VISIBILITY_XX values)
* @param callback the async callback
*/
public void updateHistoryVisibility(final String historyVisibility, final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateHistoryVisibility(getRoomId(), historyVisibility, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().history_visibility = historyVisibility;
super.onSuccess(info);
}
});
}
/**
* Update the directory's visibility
*
* @param visibility the visibility (should be one of RoomState.HISTORY_VISIBILITY_XX values)
* @param callback the async callback
*/
public void updateDirectoryVisibility(final String visibility, final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateDirectoryVisibility(getRoomId(), visibility, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().visibility = visibility;
super.onSuccess(info);
}
});
}
/**
* Get the directory visibility of the room (see {@link #updateDirectoryVisibility(String, ApiCallback)}).
* The directory visibility indicates if the room is listed among the directory list.
*
* @param roomId the user Id.
* @param callback the callback returning the visibility response value.
*/
public void getDirectoryVisibility(final String roomId, final ApiCallback<String> callback) {
RoomsRestClient roomRestApi = mDataHandler.getDataRetriever().getRoomsRestClient();
if (null != roomRestApi) {
roomRestApi.getDirectoryVisibility(roomId, new ApiCallback<RoomState>() {
@Override
public void onSuccess(RoomState roomState) {
RoomState currentRoomState = getState();
if (null != currentRoomState) {
currentRoomState.visibility = roomState.visibility;
}
if (null != callback) {
callback.onSuccess(roomState.visibility);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
/**
* Update the join rule of the room.
*
* @param aRule the join rule: {@link RoomState#JOIN_RULE_PUBLIC} or {@link RoomState#JOIN_RULE_INVITE}
* @param aCallBackResp the async callback
*/
public void updateJoinRules(final String aRule, final ApiCallback<Void> aCallBackResp) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateJoinRules(getRoomId(), aRule, new RoomInfoUpdateCallback<Void>(aCallBackResp) {
@Override
public void onSuccess(Void info) {
getState().join_rule = aRule;
super.onSuccess(info);
}
});
}
/**
* Update the guest access rule of the room.
* To deny guest access to the room, aGuestAccessRule must be set to {@link RoomState#GUEST_ACCESS_FORBIDDEN}.
*
* @param aGuestAccessRule the guest access rule: {@link RoomState#GUEST_ACCESS_CAN_JOIN} or {@link RoomState#GUEST_ACCESS_FORBIDDEN}
* @param callback the async callback
*/
public void updateGuestAccess(final String aGuestAccessRule, final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().updateGuestAccess(getRoomId(), aGuestAccessRule, new RoomInfoUpdateCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
getState().guest_access = aGuestAccessRule;
super.onSuccess(info);
}
});
}
//================================================================================
// Read receipts events
//================================================================================
/**
* @return the call conference user id
*/
private String getCallConferenceUserId() {
if (null == mCallConferenceUserId) {
mCallConferenceUserId = MXCallsManager.getConferenceUserId(getRoomId());
}
return mCallConferenceUserId;
}
/**
* Handle a receiptData.
*
* @param receiptData the receiptData.
* @return true if there a store update.
*/
public boolean handleReceiptData(ReceiptData receiptData) {
if (!TextUtils.equals(receiptData.userId, getCallConferenceUserId())) {
boolean isUpdated = mStore.storeReceipt(receiptData, getRoomId());
// check oneself receipts
// if there is an update, it means that the messages have been read from another client
// it requires to update the summary to display valid information.
if (isUpdated && TextUtils.equals(mMyUserId, receiptData.userId)) {
RoomSummary summary = mStore.getSummary(getRoomId());
if (null != summary) {
summary.setReadReceiptEventId(receiptData.eventId);
mStore.flushSummary(summary);
}
refreshUnreadCounter();
}
return isUpdated;
} else {
return false;
}
}
/**
* Handle receipt event.
*
* @param event the event receipts.
* @return the sender user IDs list.
*/
private List<String> handleReceiptEvent(Event event) {
List<String> senderIDs = new ArrayList<>();
try {
// the receipts dictionnaries
// key : $EventId
// value : dict key $UserId
// value dict key ts
// dict value ts value
Type type = new TypeToken<HashMap<String, HashMap<String, HashMap<String, HashMap<String, Object>>>>>() {
}.getType();
HashMap<String, HashMap<String, HashMap<String, HashMap<String, Object>>>> receiptsDict = gson.fromJson(event.getContent(), type);
for (String eventId : receiptsDict.keySet()) {
HashMap<String, HashMap<String, HashMap<String, Object>>> receiptDict = receiptsDict.get(eventId);
for (String receiptType : receiptDict.keySet()) {
// only the read receipts are managed
if (TextUtils.equals(receiptType, "m.read")) {
HashMap<String, HashMap<String, Object>> userIdsDict = receiptDict.get(receiptType);
for (String userID : userIdsDict.keySet()) {
HashMap<String, Object> paramsDict = userIdsDict.get(userID);
for (String paramName : paramsDict.keySet()) {
if (TextUtils.equals("ts", paramName)) {
Double value = (Double) paramsDict.get(paramName);
long ts = value.longValue();
if (handleReceiptData(new ReceiptData(userID, eventId, ts))) {
senderIDs.add(userID);
}
}
}
}
}
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "handleReceiptEvent : failed" + e.getMessage());
}
return senderIDs;
}
/**
* Clear the unread message counters
*
* @param summary the room summary
*/
private void clearUnreadCounters(RoomSummary summary) {
Log.d(LOG_TAG, "## clearUnreadCounters " + getRoomId());
// reset the notification count
getLiveState().setHighlightCount(0);
getLiveState().setNotificationCount(0);
mStore.storeLiveStateForRoom(getRoomId());
// flush the summary
if (null != summary) {
summary.setUnreadEventsCount(0);
summary.setHighlightCount(0);
summary.setNotificationCount(0);
mStore.flushSummary(summary);
}
mStore.commit();
}
/**
* @return the read marker event id
*/
public String getReadMarkerEventId() {
RoomSummary summary = mStore.getSummary(getRoomId());
if (null != summary) {
return (null != summary.getReadMarkerEventId()) ? summary.getReadMarkerEventId() : summary.getReadReceiptEventId();
} else {
return null;
}
}
/**
* Mark all the messages as read.
* It also move the read marker to the latest known messages
*
* @param aRespCallback the asynchronous callback
*/
public boolean markAllAsRead(final ApiCallback<Void> aRespCallback) {
return markAllAsRead(true, aRespCallback);
}
/**
* Mark all the messages as read.
* It also move the read marker to the latest known messages if updateReadMarker is set to true
*
* @param updateReadMarker true to move the read marker to the latest known event
* @param aRespCallback the asynchronous callback
*/
private boolean markAllAsRead(boolean updateReadMarker, final ApiCallback<Void> aRespCallback) {
final Event lastEvent = mStore.getLatestEvent(getRoomId());
boolean res = sendReadMarkers(updateReadMarker ? ((null != lastEvent) ? lastEvent.eventId : null) : getReadMarkerEventId(), null, aRespCallback);
if (!res) {
RoomSummary summary = mDataHandler.getStore().getSummary(getRoomId());
if (null != summary) {
if ((0 != summary.getUnreadEventsCount()) ||
(0 != summary.getHighlightCount()) ||
(0 != summary.getNotificationCount())) {
Log.e(LOG_TAG, "## markAllAsRead() : the summary events counters should be cleared for " + getRoomId() + " should have been cleared");
Event latestEvent = mDataHandler.getStore().getLatestEvent(getRoomId());
summary.setLatestReceivedEvent(latestEvent);
if (null != latestEvent) {
summary.setReadReceiptEventId(latestEvent.eventId);
} else {
summary.setReadReceiptEventId(null);
}
summary.setUnreadEventsCount(0);
summary.setHighlightCount(0);
summary.setNotificationCount(0);
mDataHandler.getStore().flushSummary(summary);
}
} else {
Log.e(LOG_TAG, "## sendReadReceipt() : no summary for " + getRoomId());
}
if ((0 != getLiveState().getNotificationCount()) || (0 != getLiveState().getHighlightCount())) {
Log.e(LOG_TAG, "## markAllAsRead() : the notification messages count for " + getRoomId() + " should have been cleared");
getLiveState().setNotificationCount(0);
getLiveState().setHighlightCount(0);
mDataHandler.getStore().storeLiveStateForRoom(getRoomId());
}
}
return res;
}
/**
* Update the read marker event Id
*
* @param readMarkerEventId the read marker even id
*/
public void setReadMakerEventId(final String readMarkerEventId) {
RoomSummary summary = mStore.getSummary(getRoomId());
if (summary != null && !readMarkerEventId.equals(summary.getReadMarkerEventId())) {
sendReadMarkers(readMarkerEventId, summary.getReadReceiptEventId(), null);
}
}
/**
* Send a read receipt to the latest known event
*/
public void sendReadReceipt() {
markAllAsRead(false, null);
}
/**
* Send the read receipt to the latest room message id.
*
* @param event send a read receipt to a provided event
* @param aRespCallback asynchronous response callback
* @return true if the read receipt has been sent, false otherwise
*/
public boolean sendReadReceipt(Event event, final ApiCallback<Void> aRespCallback) {
String eventId = (null != event) ? event.eventId : null;
Log.d(LOG_TAG, "## sendReadReceipt() : eventId " + eventId + " in room " + getRoomId());
return sendReadMarkers(null, eventId, aRespCallback);
}
/**
* Forget the current read marker
* This will update the read marker to match the read receipt
*
* @param callback the asynchronous callback
*/
public void forgetReadMarker(final ApiCallback<Void> callback) {
final RoomSummary summary = mStore.getSummary(getRoomId());
final String currentReadReceipt = summary.getReadReceiptEventId();
Log.d(LOG_TAG, "## forgetReadMarker() : update the read marker to " + currentReadReceipt + " in room " + getRoomId());
summary.setReadMarkerEventId(currentReadReceipt);
mStore.flushSummary(summary);
setReadMarkers(currentReadReceipt, currentReadReceipt, callback);
}
/**
* Send the read markers
*
* @param aReadMarkerEventId the new read marker event id (if null use the latest known event id)
* @param aReadReceiptEventId the new read receipt event id (if null use the latest known event id)
* @param aRespCallback asynchronous response callback
* @return true if the request is sent, false otherwise
*/
public boolean sendReadMarkers(final String aReadMarkerEventId, final String aReadReceiptEventId, final ApiCallback<Void> aRespCallback) {
final Event lastEvent = mStore.getLatestEvent(getRoomId());
// reported by GA
if (null == lastEvent) {
Log.e(LOG_TAG, "## sendReadMarkers(): no last event");
return false;
}
Log.d(LOG_TAG, "## sendReadMarkers(): readMarkerEventId " + aReadMarkerEventId + " readReceiptEventId " + aReadReceiptEventId + " in room " + getRoomId());
boolean hasUpdate = false;
String readMarkerEventId = aReadMarkerEventId;
if (!TextUtils.isEmpty(aReadMarkerEventId)) {
if (!MXSession.isMessageId(aReadMarkerEventId)) {
Log.e(LOG_TAG, "## sendReadMarkers() : invalid event id " + readMarkerEventId);
// Read marker is invalid, ignore it
readMarkerEventId = null;
} else {
// Check if the read marker is updated
RoomSummary summary = mStore.getSummary(getRoomId());
if ((null != summary) && !TextUtils.equals(readMarkerEventId, summary.getReadMarkerEventId())) {
// Make sure the new read marker event is newer than the current one
final Event newReadMarkerEvent = mStore.getEvent(readMarkerEventId, getRoomId());
final Event currentReadMarkerEvent = mStore.getEvent(summary.getReadMarkerEventId(), getRoomId());
if (newReadMarkerEvent == null || currentReadMarkerEvent == null
|| newReadMarkerEvent.getOriginServerTs() > currentReadMarkerEvent.getOriginServerTs()) {
// Event is not in store (assume it is in the past), or is older than current one
Log.d(LOG_TAG, "## sendReadMarkers(): set new read marker event id " + readMarkerEventId + " in room " + getRoomId());
summary.setReadMarkerEventId(readMarkerEventId);
mStore.flushSummary(summary);
hasUpdate = true;
}
}
}
}
final String readReceiptEventId = (null == aReadReceiptEventId) ? lastEvent.eventId : aReadReceiptEventId;
// check if the read receipt event id is already read
if (!getDataHandler().getStore().isEventRead(getRoomId(), getDataHandler().getUserId(), readReceiptEventId)) {
// check if the event id update is allowed
if (handleReceiptData(new ReceiptData(mMyUserId, readReceiptEventId, System.currentTimeMillis()))) {
// Clear the unread counters if the latest message is displayed
// We don't try to compute the unread counters for oldest messages :
// ---> it would require too much time.
// The counters are cleared to avoid displaying invalid values
// when the device is offline.
// The read receipts will be sent later
// (asap there is a valid network connection)
if (TextUtils.equals(lastEvent.eventId, readReceiptEventId)) {
clearUnreadCounters(mStore.getSummary(getRoomId()));
}
hasUpdate = true;
}
}
if (hasUpdate) {
setReadMarkers(readMarkerEventId, readReceiptEventId, aRespCallback);
}
return hasUpdate;
}
/**
* Send the request to update the read marker and read receipt.
*
* @param aReadMarkerEventId the read marker event id
* @param aReadReceiptEventId the read receipt event id
* @param callback the asynchronous callback
*/
private void setReadMarkers(final String aReadMarkerEventId, final String aReadReceiptEventId, final ApiCallback<Void> callback) {
Log.d(LOG_TAG, "## setReadMarkers(): readMarkerEventId " + aReadMarkerEventId + " readReceiptEventId " + aReadMarkerEventId);
// check if the message ids are valid
final String readMarkerEventId = MXSession.isMessageId(aReadMarkerEventId) ? aReadMarkerEventId : null;
final String readReceiptEventId = MXSession.isMessageId(aReadReceiptEventId) ? aReadReceiptEventId : null;
// if there is nothing to do
if (TextUtils.isEmpty(readMarkerEventId) && TextUtils.isEmpty(readReceiptEventId)) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onSuccess(null);
}
}
});
} else {
mDataHandler.getDataRetriever().getRoomsRestClient().sendReadMarker(getRoomId(), readMarkerEventId, readReceiptEventId, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (null != callback) {
callback.onSuccess(info);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
/**
* Check if an event has been read.
*
* @param eventId the event id
* @return true if the message has been read
*/
public boolean isEventRead(String eventId) {
return mStore.isEventRead(getRoomId(), mMyUserId, eventId);
}
//================================================================================
// Unread event count management
//================================================================================
/**
* @return the number of unread messages that match the push notification rules.
*/
public int getNotificationCount() {
return getState().getNotificationCount();
}
/**
* @return the number of highlighted events.
*/
public int getHighlightCount() {
return getState().getHighlightCount();
}
/**
* refresh the unread events counts.
*/
public void refreshUnreadCounter() {
// avoid refreshing the unread counter while processing a bunch of messages.
if (!mIsSyncing) {
RoomSummary summary = mStore.getSummary(getRoomId());
if (null != summary) {
int prevValue = summary.getUnreadEventsCount();
int newValue = mStore.eventsCountAfter(getRoomId(), summary.getReadReceiptEventId());
if (prevValue != newValue) {
summary.setUnreadEventsCount(newValue);
mStore.flushSummary(summary);
}
}
} else {
// wait the sync end before computing is again
mRefreshUnreadAfterSync = true;
}
}
//================================================================================
// typing events
//================================================================================
// userIds list
private List<String> mTypingUsers = new ArrayList<>();
/**
* Get typing users
*
* @return the userIds list
*/
public List<String> getTypingUsers() {
List<String> typingUsers;
synchronized (Room.this) {
typingUsers = (null == mTypingUsers) ? new ArrayList<String>() : new ArrayList<>(mTypingUsers);
}
return typingUsers;
}
/**
* Send a typing notification
*
* @param isTyping typing status
* @param timeout the typing timeout
*/
public void sendTypingNotification(boolean isTyping, int timeout, ApiCallback<Void> callback) {
// send the event only if the user has joined the room.
if (selfJoined()) {
mDataHandler.getDataRetriever().getRoomsRestClient().sendTypingNotification(getRoomId(), mMyUserId, isTyping, timeout, callback);
}
}
//================================================================================
// Medias events
//================================================================================
/**
* Fill the locationInfo
*
* @param context the context
* @param locationMessage the location message
* @param thumbnailUri the thumbnail uri
* @param thumbMimeType the thumbnail mime type
*/
public static void fillLocationInfo(Context context, LocationMessage locationMessage, Uri thumbnailUri, String thumbMimeType) {
if (null != thumbnailUri) {
try {
locationMessage.thumbnail_url = thumbnailUri.toString();
ThumbnailInfo thumbInfo = new ThumbnailInfo();
File thumbnailFile = new File(thumbnailUri.getPath());
ExifInterface exifMedia = new ExifInterface(thumbnailUri.getPath());
String sWidth = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
String sHeight = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
if (null != sWidth) {
thumbInfo.w = Integer.parseInt(sWidth);
}
if (null != sHeight) {
thumbInfo.h = Integer.parseInt(sHeight);
}
thumbInfo.size = Long.valueOf(thumbnailFile.length());
thumbInfo.mimetype = thumbMimeType;
locationMessage.thumbnail_info = thumbInfo;
} catch (Exception e) {
Log.e(LOG_TAG, "fillLocationInfo : failed" + e.getMessage());
}
}
}
/**
* Fills the VideoMessage info.
*
* @param context Application context for the content resolver.
* @param videoMessage The VideoMessage to fill.
* @param fileUri The file uri.
* @param videoMimeType The mimeType
* @param thumbnailUri the thumbnail uri
* @param thumbMimeType the thumbnail mime type
*/
public static void fillVideoInfo(Context context, VideoMessage videoMessage, Uri fileUri, String videoMimeType, Uri thumbnailUri, String thumbMimeType) {
try {
VideoInfo videoInfo = new VideoInfo();
File file = new File(fileUri.getPath());
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(file.getAbsolutePath());
Bitmap bmp = retriever.getFrameAtTime();
videoInfo.h = bmp.getHeight();
videoInfo.w = bmp.getWidth();
videoInfo.mimetype = videoMimeType;
try {
MediaPlayer mp = MediaPlayer.create(context, fileUri);
if (null != mp) {
videoInfo.duration = Long.valueOf(mp.getDuration());
mp.release();
}
} catch (Exception e) {
Log.e(LOG_TAG, "fillVideoInfo : MediaPlayer.create failed" + e.getMessage());
}
videoInfo.size = file.length();
// thumbnail
if (null != thumbnailUri) {
videoInfo.thumbnail_url = thumbnailUri.toString();
ThumbnailInfo thumbInfo = new ThumbnailInfo();
File thumbnailFile = new File(thumbnailUri.getPath());
ExifInterface exifMedia = new ExifInterface(thumbnailUri.getPath());
String sWidth = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
String sHeight = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
if (null != sWidth) {
thumbInfo.w = Integer.parseInt(sWidth);
}
if (null != sHeight) {
thumbInfo.h = Integer.parseInt(sHeight);
}
thumbInfo.size = Long.valueOf(thumbnailFile.length());
thumbInfo.mimetype = thumbMimeType;
videoInfo.thumbnail_info = thumbInfo;
}
videoMessage.info = videoInfo;
} catch (Exception e) {
Log.e(LOG_TAG, "fillVideoInfo : failed" + e.getMessage());
}
}
/**
* Fills the fileMessage fileInfo.
*
* @param context Application context for the content resolver.
* @param fileMessage The fileMessage to fill.
* @param fileUri The file uri.
* @param mimeType The mimeType
*/
public static void fillFileInfo(Context context, FileMessage fileMessage, Uri fileUri, String mimeType) {
try {
FileInfo fileInfo = new FileInfo();
String filename = fileUri.getPath();
File file = new File(filename);
fileInfo.mimetype = mimeType;
fileInfo.size = file.length();
fileMessage.info = fileInfo;
} catch (Exception e) {
Log.e(LOG_TAG, "fillFileInfo : failed" + e.getMessage());
}
}
/**
* Define ImageInfo for an image uri
*
* @param context Application context for the content resolver.
* @param imageUri The full size image uri.
* @param mimeType The image mimeType
*/
public static ImageInfo getImageInfo(Context context, ImageInfo anImageInfo, Uri imageUri, String mimeType) {
ImageInfo imageInfo = (null == anImageInfo) ? new ImageInfo() : anImageInfo;
try {
String filename = imageUri.getPath();
File file = new File(filename);
ExifInterface exifMedia = new ExifInterface(filename);
String sWidth = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
String sHeight = exifMedia.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
// the image rotation is replaced by orientation
// imageInfo.rotation = ImageUtils.getRotationAngleForBitmap(context, imageUri);
imageInfo.orientation = ImageUtils.getOrientationForBitmap(context, imageUri);
int width = 0;
int height = 0;
// extract the Exif info
if ((null != sWidth) && (null != sHeight)) {
if ((imageInfo.orientation == ExifInterface.ORIENTATION_TRANSPOSE) ||
(imageInfo.orientation == ExifInterface.ORIENTATION_ROTATE_90) ||
(imageInfo.orientation == ExifInterface.ORIENTATION_TRANSVERSE) ||
(imageInfo.orientation == ExifInterface.ORIENTATION_ROTATE_270)) {
height = Integer.parseInt(sWidth);
width = Integer.parseInt(sHeight);
} else {
width = Integer.parseInt(sWidth);
height = Integer.parseInt(sHeight);
}
}
// there is no exif info or the size is invalid
if ((0 == width) || (0 == height)) {
try {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageUri.getPath(), opts);
// don't need to load the bitmap in memory
if ((opts.outHeight > 0) && (opts.outWidth > 0)) {
width = opts.outWidth;
height = opts.outHeight;
}
} catch (Exception e) {
Log.e(LOG_TAG, "fillImageInfo : failed" + e.getMessage());
} catch (OutOfMemoryError oom) {
Log.e(LOG_TAG, "fillImageInfo : oom");
}
}
// valid image size ?
if ((0 != width) || (0 != height)) {
imageInfo.w = width;
imageInfo.h = height;
}
imageInfo.mimetype = mimeType;
imageInfo.size = file.length();
} catch (Exception e) {
Log.e(LOG_TAG, "fillImageInfo : failed" + e.getMessage());
imageInfo = null;
}
return imageInfo;
}
/**
* Fills the imageMessage imageInfo.
*
* @param context Application context for the content resolver.
* @param imageMessage The imageMessage to fill.
* @param imageUri The full size image uri.
* @param mimeType The image mimeType
*/
public static void fillImageInfo(Context context, ImageMessage imageMessage, Uri imageUri, String mimeType) {
imageMessage.info = getImageInfo(context, imageMessage.info, imageUri, mimeType);
}
/**
* Fills the imageMessage imageInfo.
*
* @param context Application context for the content resolver.
* @param imageMessage The imageMessage to fill.
* @param thumbUri The thumbnail uri
* @param mimeType The image mimeType
*/
public static void fillThumbnailInfo(Context context, ImageMessage imageMessage, Uri thumbUri, String mimeType) {
ImageInfo imageInfo = getImageInfo(context, null, thumbUri, mimeType);
if (null != imageInfo) {
if (null == imageMessage.info) {
imageMessage.info = new ImageInfo();
}
imageMessage.info.thumbnailInfo = new ThumbnailInfo();
imageMessage.info.thumbnailInfo.w = imageInfo.w;
imageMessage.info.thumbnailInfo.h = imageInfo.h;
imageMessage.info.thumbnailInfo.size = imageInfo.size;
imageMessage.info.thumbnailInfo.mimetype = imageInfo.mimetype;
}
}
//================================================================================
// Call
//================================================================================
/**
* Test if a call can be performed in this room.
*
* @return true if a call can be performed.
*/
public boolean canPerformCall() {
return getActiveMembers().size() > 1;
}
/**
* @return a list of callable members.
*/
public List<RoomMember> callees() {
List<RoomMember> res = new ArrayList<>();
Collection<RoomMember> members = getMembers();
for (RoomMember m : members) {
if (RoomMember.MEMBERSHIP_JOIN.equals(m.membership) && !mMyUserId.equals(m.getUserId())) {
res.add(m);
}
}
return res;
}
//================================================================================
// Account data management
//================================================================================
/**
* Handle private user data events.
*
* @param accountDataEvents the account events.
*/
private void handleAccountDataEvents(List<Event> accountDataEvents) {
if ((null != accountDataEvents) && (accountDataEvents.size() > 0)) {
// manage the account events
for (Event accountDataEvent : accountDataEvents) {
String eventType = accountDataEvent.getType();
if (eventType.equals(Event.EVENT_TYPE_READ_MARKER)) {
RoomSummary summary = mStore.getSummary(getRoomId());
if (null != summary) {
Event event = JsonUtils.toEvent(accountDataEvent.getContent());
if (null != event && !TextUtils.equals(event.eventId, summary.getReadMarkerEventId())) {
Log.d(LOG_TAG, "## handleAccountDataEvents() : update the read marker to " + event.eventId + " in room " + getRoomId());
if (TextUtils.isEmpty(event.eventId)) {
Log.e(LOG_TAG, "## handleAccountDataEvents() : null event id " + accountDataEvent.getContent());
}
summary.setReadMarkerEventId(event.eventId);
mStore.flushSummary(summary);
mDataHandler.onReadMarkerEvent(getRoomId());
}
}
} else {
try {
mAccountData.handleTagEvent(accountDataEvent);
if (accountDataEvent.getType().equals(Event.EVENT_TYPE_TAGS)) {
mDataHandler.onRoomTagEvent(getRoomId());
}
} catch (Exception e) {
Log.e(LOG_TAG, "## handleAccountDataEvents() : room " + getRoomId() + " failed " + e.getMessage());
}
}
}
mStore.storeAccountData(getRoomId(), mAccountData);
}
}
/**
* Add a tag to a room.
* Use this method to update the order of an existing tag.
*
* @param tag the new tag to add to the room.
* @param order the order.
* @param callback the operation callback
*/
private void addTag(String tag, Double order, final ApiCallback<Void> callback) {
// sanity check
if ((null != tag) && (null != order)) {
mDataHandler.getDataRetriever().getRoomsRestClient().addTag(getRoomId(), tag, order, callback);
} else {
if (null != callback) {
callback.onSuccess(null);
}
}
}
/**
* Remove a tag to a room.
*
* @param tag the new tag to add to the room.
* @param callback the operation callback.
*/
private void removeTag(String tag, final ApiCallback<Void> callback) {
// sanity check
if (null != tag) {
mDataHandler.getDataRetriever().getRoomsRestClient().removeTag(getRoomId(), tag, callback);
} else {
if (null != callback) {
callback.onSuccess(null);
}
}
}
/**
* Remove a tag and add another one.
*
* @param oldTag the tag to remove.
* @param newTag the new tag to add. Nil can be used. Then, no new tag will be added.
* @param newTagOrder the order of the new tag.
* @param callback the operation callback.
*/
public void replaceTag(final String oldTag, final String newTag, final Double newTagOrder, final ApiCallback<Void> callback) {
// remove tag
if ((null != oldTag) && (null == newTag)) {
removeTag(oldTag, callback);
}
// define a tag or define a new order
else if (((null == oldTag) && (null != newTag)) || TextUtils.equals(oldTag, newTag)) {
addTag(newTag, newTagOrder, callback);
} else {
removeTag(oldTag, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
addTag(newTag, newTagOrder, callback);
}
@Override
public void onNetworkError(Exception e) {
callback.onNetworkError(e);
}
@Override
public void onMatrixError(MatrixError e) {
callback.onMatrixError(e);
}
@Override
public void onUnexpectedError(Exception e) {
callback.onUnexpectedError(e);
}
});
}
}
//==============================================================================================================
// Room events dispatcher
//==============================================================================================================
/**
* Add an event listener to this room. Only events relative to the room will come down.
*
* @param eventListener the event listener to add
*/
public void addEventListener(final IMXEventListener eventListener) {
// sanity check
if (null == eventListener) {
Log.e(LOG_TAG, "addEventListener : eventListener is null");
return;
}
// GA crash : should never happen but got it.
if (null == mDataHandler) {
Log.e(LOG_TAG, "addEventListener : mDataHandler is null");
return;
}
// Create a global listener that we'll add to the data handler
IMXEventListener globalListener = new MXEventListener() {
@Override
public void onPresenceUpdate(Event event, User user) {
// Only pass event through if the user is a member of the room
if (getMember(user.user_id) != null) {
try {
eventListener.onPresenceUpdate(event, user);
} catch (Exception e) {
Log.e(LOG_TAG, "onPresenceUpdate exception " + e.getMessage());
}
}
}
@Override
public void onLiveEvent(Event event, RoomState roomState) {
// Filter out events for other rooms and events while we are joining (before the room is ready)
if (TextUtils.equals(getRoomId(), event.roomId) && mIsReady) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_TYPING)) {
// Typing notifications events are not room messages nor room state events
// They are just volatile information
JsonObject eventContent = event.getContentAsJsonObject();
if (eventContent.has("user_ids")) {
synchronized (Room.this) {
mTypingUsers = null;
try {
mTypingUsers = (new Gson()).fromJson(eventContent.get("user_ids"), new TypeToken<List<String>>() {
}.getType());
} catch (Exception e) {
Log.e(LOG_TAG, "onLiveEvent exception " + e.getMessage());
}
// avoid null list
if (null == mTypingUsers) {
mTypingUsers = new ArrayList<>();
}
}
}
}
try {
eventListener.onLiveEvent(event, roomState);
} catch (Exception e) {
Log.e(LOG_TAG, "onLiveEvent exception " + e.getMessage());
}
}
}
@Override
public void onLiveEventsChunkProcessed(String fromToken, String toToken) {
try {
eventListener.onLiveEventsChunkProcessed(fromToken, toToken);
} catch (Exception e) {
Log.e(LOG_TAG, "onLiveEventsChunkProcessed exception " + e.getMessage());
}
}
@Override
public void onEventEncrypted(Event event) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), event.roomId)) {
try {
eventListener.onEventEncrypted(event);
} catch (Exception e) {
Log.e(LOG_TAG, "onEventEncrypted exception " + e.getMessage());
}
}
}
@Override
public void onEventDecrypted(Event event) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), event.roomId)) {
try {
eventListener.onEventDecrypted(event);
} catch (Exception e) {
Log.e(LOG_TAG, "onDecryptedEvent exception " + e.getMessage());
}
}
}
@Override
public void onEventSent(final Event event, final String prevEventId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), event.roomId)) {
try {
eventListener.onEventSent(event, prevEventId);
} catch (Exception e) {
Log.e(LOG_TAG, "onEventSent exception " + e.getMessage());
}
}
}
@Override
public void onFailedSendingEvent(Event event) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), event.roomId)) {
try {
eventListener.onFailedSendingEvent(event);
} catch (Exception e) {
Log.e(LOG_TAG, "onFailedSendingEvent exception " + e.getMessage());
}
}
}
@Override
public void onRoomInitialSyncComplete(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onRoomInitialSyncComplete(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomInitialSyncComplete exception " + e.getMessage());
}
}
}
@Override
public void onRoomInternalUpdate(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onRoomInternalUpdate(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomInternalUpdate exception " + e.getMessage());
}
}
}
@Override
public void onNewRoom(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onNewRoom(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onNewRoom exception " + e.getMessage());
}
}
}
@Override
public void onJoinRoom(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onJoinRoom(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onJoinRoom exception " + e.getMessage());
}
}
}
@Override
public void onReceiptEvent(String roomId, List<String> senderIds) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onReceiptEvent(roomId, senderIds);
} catch (Exception e) {
Log.e(LOG_TAG, "onReceiptEvent exception " + e.getMessage());
}
}
}
@Override
public void onRoomTagEvent(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onRoomTagEvent(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomTagEvent exception " + e.getMessage());
}
}
}
@Override
public void onReadMarkerEvent(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onReadMarkerEvent(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onReadMarkerEvent exception " + e.getMessage());
}
}
}
@Override
public void onRoomFlush(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onRoomFlush(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomFlush exception " + e.getMessage());
}
}
}
@Override
public void onLeaveRoom(String roomId) {
// Filter out events for other rooms
if (TextUtils.equals(getRoomId(), roomId)) {
try {
eventListener.onLeaveRoom(roomId);
} catch (Exception e) {
Log.e(LOG_TAG, "onLeaveRoom exception " + e.getMessage());
}
}
}
};
mEventListeners.put(eventListener, globalListener);
// GA crash
if (null != mDataHandler) {
mDataHandler.addListener(globalListener);
}
}
/**
* Remove an event listener.
*
* @param eventListener the event listener to remove
*/
public void removeEventListener(IMXEventListener eventListener) {
// sanity check
if ((null != eventListener) && (null != mDataHandler)) {
mDataHandler.removeListener(mEventListeners.get(eventListener));
mEventListeners.remove(eventListener);
}
}
//==============================================================================================================
// Send methods
//==============================================================================================================
/**
* Send an event content to the room.
* The event is updated with the data provided by the server
* The provided event contains the error description.
*
* @param event the message
* @param callback the callback with the created event
*/
public void sendEvent(final Event event, final ApiCallback<Void> callback) {
// wait that the room is synced before sending messages
if (!mIsReady || !selfJoined()) {
event.mSentState = Event.SentState.WAITING_RETRY;
try {
callback.onNetworkError(null);
} catch (Exception e) {
Log.e(LOG_TAG, "sendEvent exception " + e.getMessage());
}
return;
}
final String prevEventId = event.eventId;
final ApiCallback<Event> localCB = new ApiCallback<Event>() {
@Override
public void onSuccess(final Event serverResponseEvent) {
// remove the tmp event
mStore.deleteEvent(event);
// replace the tmp event id by the final one
boolean isReadMarkerUpdated = TextUtils.equals(getReadMarkerEventId(), event.eventId);
// update the event with the server response
event.mSentState = Event.SentState.SENT;
event.eventId = serverResponseEvent.eventId;
event.originServerTs = System.currentTimeMillis();
// the message echo is not yet echoed
if (!mStore.doesEventExist(serverResponseEvent.eventId, getRoomId())) {
mStore.storeLiveRoomEvent(event);
}
// send the dedicated read receipt asap
markAllAsRead(isReadMarkerUpdated, null);
mStore.commit();
mDataHandler.onEventSent(event, prevEventId);
try {
callback.onSuccess(null);
} catch (Exception e) {
Log.e(LOG_TAG, "sendEvent exception " + e.getMessage());
}
}
@Override
public void onNetworkError(Exception e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentException = e;
try {
callback.onNetworkError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "sendEvent exception " + anException.getMessage());
}
}
@Override
public void onMatrixError(MatrixError e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentMatrixError = e;
if (TextUtils.equals(MatrixError.UNKNOWN_TOKEN, e.errcode)) {
mDataHandler.onInvalidToken();
} else {
try {
callback.onMatrixError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "sendEvent exception " + anException.getMessage());
}
}
}
@Override
public void onUnexpectedError(Exception e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentException = e;
try {
callback.onUnexpectedError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "sendEvent exception " + anException.getMessage());
}
}
};
if (isEncrypted() && (null != mDataHandler.getCrypto())) {
event.mSentState = Event.SentState.ENCRYPTING;
// Encrypt the content before sending
mDataHandler.getCrypto().encryptEventContent(event.getContent().getAsJsonObject(), event.getType(), this, new ApiCallback<MXEncryptEventContentResult>() {
@Override
public void onSuccess(MXEncryptEventContentResult encryptEventContentResult) {
// update the event content with the encrypted data
event.type = encryptEventContentResult.mEventType;
event.updateContent(encryptEventContentResult.mEventContent.getAsJsonObject());
mDataHandler.getCrypto().decryptEvent(event, null);
// warn the upper layer
mDataHandler.onEventEncrypted(event);
// sending in progress
event.mSentState = Event.SentState.SENDING;
mDataHandler.getDataRetriever().getRoomsRestClient().sendEventToRoom(event.originServerTs + "", getRoomId(), encryptEventContentResult.mEventType, encryptEventContentResult.mEventContent.getAsJsonObject(), localCB);
}
@Override
public void onNetworkError(Exception e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentException = e;
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
// update the sent state if the message encryption failed because there are unknown devices.
if ((e instanceof MXCryptoError) && TextUtils.equals(((MXCryptoError) e).errcode, MXCryptoError.UNKNOWN_DEVICES_CODE)) {
event.mSentState = Event.SentState.FAILED_UNKNOWN_DEVICES;
} else {
event.mSentState = Event.SentState.UNDELIVERABLE;
}
event.unsentMatrixError = e;
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
event.mSentState = Event.SentState.UNDELIVERABLE;
event.unsentException = e;
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
} else {
event.mSentState = Event.SentState.SENDING;
if (Event.EVENT_TYPE_MESSAGE.equals(event.getType())) {
mDataHandler.getDataRetriever().getRoomsRestClient().sendMessage(event.originServerTs + "", getRoomId(), JsonUtils.toMessage(event.getContent()), localCB);
} else {
mDataHandler.getDataRetriever().getRoomsRestClient().sendEventToRoom(event.originServerTs + "", getRoomId(), event.getType(), event.getContent().getAsJsonObject(), localCB);
}
}
}
/**
* Cancel the event sending.
* Any media upload will be cancelled too.
* The event becomes undeliverable.
*
* @param event the message
*/
public void cancelEventSending(final Event event) {
if (null != event) {
if ((Event.SentState.UNSENT == event.mSentState) ||
(Event.SentState.SENDING == event.mSentState) ||
(Event.SentState.WAITING_RETRY == event.mSentState) ||
(Event.SentState.ENCRYPTING == event.mSentState)) {
// the message cannot be sent anymore
event.mSentState = Event.SentState.UNDELIVERABLE;
}
List<String> urls = event.getMediaUrls();
MXMediasCache cache = mDataHandler.getMediasCache();
for (String url : urls) {
cache.cancelUpload(url);
cache.cancelDownload(cache.downloadIdFromUrl(url));
}
}
}
/**
* Redact an event from the room.
*
* @param eventId the event's id
* @param callback the callback with the redacted event
*/
public void redact(final String eventId, final ApiCallback<Event> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().redactEvent(getRoomId(), eventId, new ApiCallback<Event>() {
@Override
public void onSuccess(Event event) {
Event redactedEvent = mStore.getEvent(eventId, getRoomId());
// test if the redacted event has been echoed
// it it was not echoed, the event must be pruned to remove useless data
// the room summary will be updated when the server will echo the redacted event
if ((null != redactedEvent) && ((null == redactedEvent.unsigned) || (null == redactedEvent.unsigned.redacted_because))) {
redactedEvent.prune(null);
mStore.storeLiveRoomEvent(redactedEvent);
mStore.commit();
}
if (null != callback) {
callback.onSuccess(redactedEvent);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
/**
* Redact an event from the room.
*
* @param eventId the event's id
* @param callback the callback with the created event
*/
public void report(String eventId, int score, String reason, ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().reportEvent(getRoomId(), eventId, score, reason, callback);
}
//================================================================================
// Member actions
//================================================================================
/**
* Invite an user to this room.
*
* @param userId the user id
* @param callback the callback for when done
*/
public void invite(String userId, ApiCallback<Void> callback) {
if (null != userId) {
invite(Collections.singletonList(userId), callback);
}
}
/**
* Invite an user to a room based on their email address to this room.
*
* @param email the email address
* @param callback the callback for when done
*/
public void inviteByEmail(String email, ApiCallback<Void> callback) {
if (null != email) {
invite(Collections.singletonList(email), callback);
}
}
/**
* Invite users to this room.
* The identifiers are either ini Id or email address.
*
* @param identifiers the identifiers list
* @param callback the callback for when done
*/
public void invite(List<String> identifiers, ApiCallback<Void> callback) {
if (null != identifiers) {
invite(identifiers.iterator(), callback);
}
}
/**
* Invite some users to this room.
*
* @param identifiers the identifiers iterator
* @param callback the callback for when done
*/
private void invite(final Iterator<String> identifiers, final ApiCallback<Void> callback) {
if (!identifiers.hasNext()) {
callback.onSuccess(null);
return;
}
final ApiCallback<Void> localCallback = new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
invite(identifiers, callback);
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "## invite failed " + e.getMessage());
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "## invite failed " + e.getMessage());
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "## invite failed " + e.getMessage());
if (null != callback) {
callback.onUnexpectedError(e);
}
}
};
String identifier = identifiers.next();
if (android.util.Patterns.EMAIL_ADDRESS.matcher(identifier).matches()) {
mDataHandler.getDataRetriever().getRoomsRestClient().inviteByEmailToRoom(getRoomId(), identifier, localCallback);
} else {
mDataHandler.getDataRetriever().getRoomsRestClient().inviteUserToRoom(getRoomId(), identifier, localCallback);
}
}
/**
* Leave the room.
*
* @param callback the callback for when done
*/
public void leave(final ApiCallback<Void> callback) {
this.mIsLeaving = true;
mDataHandler.onRoomInternalUpdate(getRoomId());
mDataHandler.getDataRetriever().getRoomsRestClient().leaveRoom(getRoomId(), new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (mDataHandler.isAlive()) {
Room.this.mIsLeaving = false;
// delete references to the room
mDataHandler.deleteRoom(getRoomId());
Log.d(LOG_TAG, "leave : commit");
mStore.commit();
try {
callback.onSuccess(info);
} catch (Exception e) {
Log.e(LOG_TAG, "leave exception " + e.getMessage());
}
mDataHandler.onLeaveRoom(getRoomId());
}
}
@Override
public void onNetworkError(Exception e) {
Room.this.mIsLeaving = false;
try {
callback.onNetworkError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "leave exception " + anException.getMessage());
}
mDataHandler.onRoomInternalUpdate(getRoomId());
}
@Override
public void onMatrixError(MatrixError e) {
// the room was not anymore defined server side
// race condition ?
if (e.mStatus == 404) {
onSuccess(null);
} else {
Room.this.mIsLeaving = false;
try {
callback.onMatrixError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "leave exception " + anException.getMessage());
}
mDataHandler.onRoomInternalUpdate(getRoomId());
}
}
@Override
public void onUnexpectedError(Exception e) {
Room.this.mIsLeaving = false;
try {
callback.onUnexpectedError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "leave exception " + anException.getMessage());
}
mDataHandler.onRoomInternalUpdate(getRoomId());
}
});
}
/**
* Forget the room.
*
* @param callback the callback for when done
*/
public void forget(final ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().forgetRoom(getRoomId(), new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (mDataHandler.isAlive()) {
// don't call onSuccess.deleteRoom because it moves an existing room to historical store
IMXStore store = mDataHandler.getStore(getRoomId());
if (null != store) {
store.deleteRoom(getRoomId());
mStore.commit();
}
try {
callback.onSuccess(info);
} catch (Exception e) {
Log.e(LOG_TAG, "forget exception " + e.getMessage());
}
}
}
@Override
public void onNetworkError(Exception e) {
try {
callback.onNetworkError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "forget exception " + anException.getMessage());
}
}
@Override
public void onMatrixError(MatrixError e) {
try {
callback.onMatrixError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "forget exception " + anException.getMessage());
}
}
@Override
public void onUnexpectedError(Exception e) {
try {
callback.onUnexpectedError(e);
} catch (Exception anException) {
Log.e(LOG_TAG, "forget exception " + anException.getMessage());
}
}
});
}
/**
* Kick a user from the room.
*
* @param userId the user id
* @param callback the async callback
*/
public void kick(String userId, ApiCallback<Void> callback) {
mDataHandler.getDataRetriever().getRoomsRestClient().kickFromRoom(getRoomId(), userId, callback);
}
/**
* Ban a user from the room.
*
* @param userId the user id
* @param reason ban reason
* @param callback the async callback
*/
public void ban(String userId, String reason, ApiCallback<Void> callback) {
BannedUser user = new BannedUser();
user.userId = userId;
if (!TextUtils.isEmpty(reason)) {
user.reason = reason;
}
mDataHandler.getDataRetriever().getRoomsRestClient().banFromRoom(getRoomId(), user, callback);
}
/**
* Unban a user.
*
* @param userId the user id
* @param callback the async callback
*/
public void unban(String userId, ApiCallback<Void> callback) {
BannedUser user = new BannedUser();
user.userId = userId;
mDataHandler.getDataRetriever().getRoomsRestClient().unbanFromRoom(getRoomId(), user, callback);
}
//================================================================================
// Encryption
//================================================================================
private ApiCallback<Void> mRoomEncryptionCallback;
private final MXEventListener mEncryptionListener = new MXEventListener() {
@Override
public void onLiveEvent(Event event, RoomState roomState) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE_ENCRYPTION)) {
if (null != mRoomEncryptionCallback) {
mRoomEncryptionCallback.onSuccess(null);
mRoomEncryptionCallback = null;
}
}
}
};
/**
* @return if the room content is encrypted
*/
public boolean isEncrypted() {
return !TextUtils.isEmpty(getLiveState().algorithm);
}
/**
* Enable the encryption.
*
* @param algorithm the used algorithm
* @param callback the asynchronous callback
*/
public void enableEncryptionWithAlgorithm(final String algorithm, final ApiCallback<Void> callback) {
// ensure that the crypto has been update
if (null != mDataHandler.getCrypto() && !TextUtils.isEmpty(algorithm)) {
HashMap<String, Object> params = new HashMap<>();
params.put("algorithm", algorithm);
if (null != callback) {
mRoomEncryptionCallback = callback;
addEventListener(mEncryptionListener);
}
mDataHandler.getDataRetriever().getRoomsRestClient().sendStateEvent(getRoomId(), Event.EVENT_TYPE_MESSAGE_ENCRYPTION, null, params, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// Wait for the event coming back from the hs
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
removeEventListener(mEncryptionListener);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
removeEventListener(mEncryptionListener);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
removeEventListener(mEncryptionListener);
}
}
});
} else if (null != callback) {
if (null == mDataHandler.getCrypto()) {
callback.onMatrixError(new MXCryptoError(MXCryptoError.ENCRYPTING_NOT_ENABLED_ERROR_CODE, MXCryptoError.ENCRYPTING_NOT_ENABLED_REASON, MXCryptoError.ENCRYPTING_NOT_ENABLED_REASON));
} else {
callback.onMatrixError(new MXCryptoError(MXCryptoError.MISSING_FIELDS_ERROR_CODE, MXCryptoError.UNABLE_TO_ENCRYPT, MXCryptoError.MISSING_FIELDS_REASON));
}
}
}
//==============================================================================================================
// Room events helper
//==============================================================================================================
private RoomMediaMessagesSender mRoomMediaMessagesSender;
/**
* Init the mRoomDataItemsSender instance
*/
private void initRoomDataItemsSender() {
if (null == mRoomMediaMessagesSender) {
mRoomMediaMessagesSender = new RoomMediaMessagesSender(mDataHandler.getStore().getContext(), mDataHandler, this);
}
}
/**
* Send a text message asynchronously.
*
* @param text the unformatted text
* @param HTMLFormattedText the HTML formatted text
* @param format the formatted text format
* @param listener the event creation listener
*/
public void sendTextMessage(String text, String HTMLFormattedText, String format, RoomMediaMessage.EventCreationListener listener) {
sendTextMessage(text, HTMLFormattedText, format, Message.MSGTYPE_TEXT, listener);
}
/**
* Send an emote message asynchronously.
*
* @param text the unformatted text
* @param HTMLFormattedText the HTML formatted text
* @param format the formatted text format
* @param listener the event creation listener
*/
public void sendEmoteMessage(String text, String HTMLFormattedText, String format, final RoomMediaMessage.EventCreationListener listener) {
sendTextMessage(text, HTMLFormattedText, format, Message.MSGTYPE_EMOTE, listener);
}
/**
* Send a text message asynchronously.
*
* @param text the unformatted text
* @param HTMLFormattedText the HTML formatted text
* @param format the formatted text format
* @param msgType the message type
* @param listener the event creation listener
*/
private void sendTextMessage(String text, String HTMLFormattedText, String format, String msgType, final RoomMediaMessage.EventCreationListener listener) {
initRoomDataItemsSender();
RoomMediaMessage roomMediaMessage = new RoomMediaMessage(text, HTMLFormattedText, format);
roomMediaMessage.setMessageType(msgType);
roomMediaMessage.setEventCreationListener(listener);
mRoomMediaMessagesSender.send(roomMediaMessage);
}
/**
* Send an media message asynchronously
*
* @param roomMediaMessage the media message
*/
public void sendMediaMessage(final RoomMediaMessage roomMediaMessage, final int maxThumbnailWidth, final int maxThumbnailHeight, final RoomMediaMessage.EventCreationListener listener) {
initRoomDataItemsSender();
roomMediaMessage.setThumnailSize(new Pair<>(maxThumbnailWidth, maxThumbnailHeight));
roomMediaMessage.setEventCreationListener(listener);
mRoomMediaMessagesSender.send(roomMediaMessage);
}
//==============================================================================================================
// Unsent events managemenet
//==============================================================================================================
/**
* Provides the unsent messages list.
*
* @return the unsent events list
*/
public List<Event> getUnsentEvents() {
List<Event> unsent = new ArrayList<>();
List<Event> undeliverableEvents = mDataHandler.getStore().getUndeliverableEvents(getRoomId());
List<Event> unknownDeviceEvents = mDataHandler.getStore().getUnknownDeviceEvents(getRoomId());
if (null != undeliverableEvents) {
unsent.addAll(undeliverableEvents);
}
if (null != unknownDeviceEvents) {
unsent.addAll(unknownDeviceEvents);
}
return unsent;
}
/**
* Delete an events list.
*
* @param events the events list
*/
public void deleteEvents(List<Event> events) {
if ((null != events) && events.size() > 0) {
IMXStore store = mDataHandler.getStore();
// reset the timestamp
for (Event event : events) {
store.deleteEvent(event);
}
// update the summary
Event latestEvent = store.getLatestEvent(getRoomId());
// if there is an oldest event, use it to set a summary
if (latestEvent != null) {
if (RoomSummary.isSupportedEvent(latestEvent)) {
RoomSummary summary = store.getSummary(getRoomId());
if (null != summary) {
summary.setLatestReceivedEvent(latestEvent, getState());
} else {
summary = new RoomSummary(null, latestEvent, getState(), mDataHandler.getUserId());
}
store.storeSummary(summary);
}
}
store.commit();
}
}
}
|
Should fix https://github.com/vector-im/riot-android/issues/1678
cannot join #Furnet_#S:spydar007.com
|
matrix-sdk/src/main/java/org/matrix/androidsdk/data/Room.java
|
Should fix https://github.com/vector-im/riot-android/issues/1678 cannot join #Furnet_#S:spydar007.com
|
<ide><path>atrix-sdk/src/main/java/org/matrix/androidsdk/data/Room.java
<ide> * @param extraParams the join extra params
<ide> * @param callback the callback for when done
<ide> */
<del> private void join(String roomAlias, HashMap<String, Object> extraParams, final ApiCallback<Void> callback) {
<add> private void join(final String roomAlias, final HashMap<String, Object> extraParams, final ApiCallback<Void> callback) {
<ide> Log.d(LOG_TAG, "Join the room " + getRoomId() + " with alias " + roomAlias);
<ide>
<ide> mDataHandler.getDataRetriever().getRoomsRestClient().joinRoom((null != roomAlias) ? roomAlias : getRoomId(), extraParams, new SimpleApiCallback<RoomResponse>(callback) {
<ide> // minging kludge until https://matrix.org/jira/browse/SYN-678 is fixed
<ide> // 'Error when trying to join an empty room should be more explicit
<ide> e.error = mStore.getContext().getString(org.matrix.androidsdk.R.string.room_error_join_failed_empty_room);
<add> }
<add>
<add> // if the alias is not found
<add> // try with the room id
<add> if ((e.mStatus == 404) && !TextUtils.isEmpty(roomAlias)) {
<add> Log.e(LOG_TAG, "Retry without the room alias");
<add> join(null, extraParams, callback);
<add> return;
<ide> }
<ide>
<ide> callback.onMatrixError(e);
|
|
Java
|
apache-2.0
|
df6c24abf2987e084d0da0be5a0ab63a3e0a95ea
| 0 |
savvasdalkitsis/gameframe,savvasdalkitsis/gameframe
|
package com.savvasdalkitsis.gameframe.draw.view;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import com.savvasdalkitsis.gameframe.draw.model.Layer;
import com.savvasdalkitsis.gameframe.draw.model.LayerSettings;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.functions.Func1;
import rx.subjects.BehaviorSubject;
class LayersAdapter extends RecyclerView.Adapter<LayerViewHolder> {
private final List<Layer> layers = new ArrayList<>();
private final BehaviorSubject<List<Layer>> change = BehaviorSubject.create();
private int selectedPosition = 0;
LayersAdapter() {
Layer layer = Layer.create(LayerSettings.create().title("Background")).isBackground(true).build();
layer.getColorGrid().fill(Color.GRAY);
layers.add(layer);
}
@Override
public LayerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new LayerViewHolder(parent);
}
@Override
public void onBindViewHolder(LayerViewHolder holder, int position) {
holder.clearListeners();
holder.bind(layers.get(position));
holder.setSelected(selectedPosition == position);
holder.setOnClickListener(v -> select(holder.getAdapterPosition()));
holder.setOnLayerVisibilityChangedListener(visible ->
modifyLayer(holder, layer -> layer.isVisible(visible)));
holder.setOnLayerDeletedListener(() -> removeLayer(holder));
holder.setOnLayerDuplicatedListener(() -> duplicateLayer(holder));
holder.setOnLayerSettingsClickedListener(() -> layerSettings(holder));
}
@Override
public int getItemCount() {
return layers.size();
}
List<Layer> getLayers() {
return layers;
}
private void modifyLayer(LayerViewHolder holder, Func1<Layer.LayerBuilder, Layer.LayerBuilder> layerBuilder) {
int position = holder.getAdapterPosition();
Layer layer = layers.get(position);
layers.set(position, layerBuilder.call(Layer.from(layer)).build());
notifyItemChanged(position);
notifyObservers();
}
private void select(int position) {
notifyItemChanged(selectedPosition);
selectedPosition = position;
notifyItemChanged(selectedPosition);
}
private void removeLayer(LayerViewHolder holder) {
int position = holder.getAdapterPosition();
if (selectedPosition >= position) {
selectedPosition--;
}
layers.remove(position);
notifyItemRemoved(position);
notifyItemChanged(selectedPosition);
notifyObservers();
}
private void duplicateLayer(LayerViewHolder holder) {
int position = holder.getAdapterPosition();
Layer layer = layers.get(position);
Layer newLayer = Layer.from(layer)
.layerSettings(LayerSettings.from(layer.getLayerSettings())
.title(layer.getLayerSettings().getTitle() + " copy")
.build())
.build();
addNewLayer(newLayer, position + 1);
}
private void layerSettings(LayerViewHolder holder) {
Context context = holder.itemView.getContext();
LayerSettingsView.show(context, layers.get(holder.getAdapterPosition()), (ViewGroup) holder.itemView,
layerSettings -> modifyLayer(holder, layer -> layer.layerSettings(layerSettings)));
}
Layer getSelectedLayer() {
return layers.get(selectedPosition);
}
void addNewLayer() {
addNewLayer(Layer.create(LayerSettings.create().title("Layer " + layers.size())).build(), layers.size());
}
private void addNewLayer(Layer layer, int position) {
if (selectedPosition >= position) {
selectedPosition++;
}
layers.add(position, layer);
notifyItemInserted(position);
select(position);
notifyObservers();
}
private void notifyObservers() {
change.onNext(getLayers());
}
Observable<List<Layer>> onChange() {
return change;
}
}
|
app/src/main/java/com/savvasdalkitsis/gameframe/draw/view/LayersAdapter.java
|
package com.savvasdalkitsis.gameframe.draw.view;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import com.savvasdalkitsis.gameframe.draw.model.Layer;
import com.savvasdalkitsis.gameframe.draw.model.LayerSettings;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.functions.Func1;
import rx.subjects.BehaviorSubject;
class LayersAdapter extends RecyclerView.Adapter<LayerViewHolder> {
private final List<Layer> layers = new ArrayList<>();
private final BehaviorSubject<List<Layer>> change = BehaviorSubject.create();
private int selectedPosition = 0;
LayersAdapter() {
Layer layer = Layer.create(LayerSettings.create().title("Background")).isBackground(true).build();
layer.getColorGrid().fill(Color.GRAY);
layers.add(layer);
}
@Override
public LayerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new LayerViewHolder(parent);
}
@Override
public void onBindViewHolder(LayerViewHolder holder, int position) {
holder.clearListeners();
holder.bind(layers.get(position));
holder.setSelected(selectedPosition == position);
holder.setOnClickListener(v -> select(holder.getAdapterPosition()));
holder.setOnLayerVisibilityChangedListener(visible ->
modifyLayer(holder, layer -> layer.isVisible(visible)));
holder.setOnLayerDeletedListener(() -> removeLayer(holder));
holder.setOnLayerDuplicatedListener(() -> duplicateLayer(holder));
holder.setOnLayerSettingsClickedListener(() -> layerSettings(holder));
}
@Override
public int getItemCount() {
return layers.size();
}
List<Layer> getLayers() {
return layers;
}
private void modifyLayer(LayerViewHolder holder, Func1<Layer.LayerBuilder, Layer.LayerBuilder> layerBuilder) {
int position = holder.getAdapterPosition();
Layer layer = layers.get(position);
layers.set(position, layerBuilder.call(Layer.from(layer)).build());
notifyItemChanged(position);
notifyObservers();
}
private void select(int position) {
notifyItemChanged(selectedPosition);
selectedPosition = position;
notifyItemChanged(selectedPosition);
}
private void removeLayer(LayerViewHolder holder) {
int position = holder.getAdapterPosition();
if (selectedPosition >= position) {
selectedPosition--;
}
layers.remove(position);
notifyItemRemoved(position);
notifyItemChanged(selectedPosition);
notifyObservers();
}
private void duplicateLayer(LayerViewHolder holder) {
int position = holder.getAdapterPosition();
Layer layer = layers.get(position);
Layer newLayer = Layer.from(layer)
.layerSettings(LayerSettings.from(layer.getLayerSettings())
.title(layer.getLayerSettings().getTitle() + " copy")
.build())
.build();
addNewLayer(newLayer, position + 1);
}
private void layerSettings(LayerViewHolder holder) {
Context context = holder.itemView.getContext();
LayerSettingsView.show(context, layers.get(holder.getAdapterPosition()), (ViewGroup) holder.itemView,
layerSettings -> modifyLayer(holder, layer -> layer.layerSettings(layerSettings)));
}
Layer getSelectedLayer() {
return layers.get(selectedPosition);
}
void addNewLayer() {
addNewLayer(Layer.create(LayerSettings.create().title("Layer " + layers.size())).build(), layers.size());
}
private void addNewLayer(Layer layer, int position) {
layers.add(position, layer);
notifyItemInserted(position);
select(position);
notifyObservers();
}
private void notifyObservers() {
change.onNext(getLayers());
}
Observable<List<Layer>> onChange() {
return change;
}
}
|
Fix layer selection being wrong when duplicating layer
|
app/src/main/java/com/savvasdalkitsis/gameframe/draw/view/LayersAdapter.java
|
Fix layer selection being wrong when duplicating layer
|
<ide><path>pp/src/main/java/com/savvasdalkitsis/gameframe/draw/view/LayersAdapter.java
<ide> }
<ide>
<ide> private void addNewLayer(Layer layer, int position) {
<add> if (selectedPosition >= position) {
<add> selectedPosition++;
<add> }
<ide> layers.add(position, layer);
<ide> notifyItemInserted(position);
<ide> select(position);
|
|
Java
|
apache-2.0
|
5dfa70066c9155de8d72607500ee18c7c8d532a8
| 0 |
osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi
|
/*
* Copyright (c) OSGi Alliance (2009). 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 org.osgi.test.cases.composite.launch.junit;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
import org.osgi.service.composite.CompositeAdmin;
import org.osgi.service.composite.CompositeBundle;
import org.osgi.service.composite.CompositeConstants;
import org.osgi.service.condpermadmin.ConditionInfo;
import org.osgi.service.condpermadmin.ConditionalPermissionAdmin;
import org.osgi.service.condpermadmin.ConditionalPermissionInfo;
import org.osgi.service.condpermadmin.ConditionalPermissionUpdate;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.permissionadmin.PermissionAdmin;
import org.osgi.service.permissionadmin.PermissionInfo;
import org.osgi.service.startlevel.StartLevel;
import org.osgi.test.support.OSGiTestCase;
public class CompositePersistenceTests extends OSGiTestCase {
private static final String STORAGEROOT = "org.osgi.test.cases.composite.launch";
private static final String FRAMEWORK_FACTORY = "/META-INF/services/org.osgi.framework.launch.FrameworkFactory";
private String frameworkFactoryClassName;
private String rootStorageArea;
private FrameworkFactory frameworkFactory;
protected void setUp() throws Exception {
super.setUp();
frameworkFactoryClassName = getFrameworkFactoryClassName();
assertNotNull("Could not find framework factory class", frameworkFactoryClassName);
frameworkFactory = getFrameworkFactory();
rootStorageArea = getStorageAreaRoot();
assertNotNull("No storage area root found", rootStorageArea);
File rootFile = new File(rootStorageArea);
assertFalse("Root storage area is not a directory: " + rootFile.getPath(), rootFile.exists() && !rootFile.isDirectory());
if (!rootFile.isDirectory())
assertTrue("Could not create root directory: " + rootFile.getPath(), rootFile.mkdirs());
}
private Object getService(BundleContext context, String serviceName) {
assertNotNull("context is null!", context);
ServiceReference ref = context.getServiceReference(serviceName);
assertNotNull(serviceName + " reference is null!", ref);
Object service = context.getService(ref);
assertNotNull(serviceName + " is null!", service);
return service;
}
private String getFrameworkFactoryClassName() throws IOException {
BundleContext context = getBundleContextWithoutFail();
URL factoryService = context == null ? this.getClass().getResource(FRAMEWORK_FACTORY) : context.getBundle(0).getEntry(FRAMEWORK_FACTORY);
assertNotNull("Could not locate: " + FRAMEWORK_FACTORY, factoryService);
return getClassName(factoryService);
}
private String getClassName(URL factoryService) throws IOException {
InputStream in = factoryService.openStream();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(in));
for (String line = br.readLine(); line != null; line=br.readLine()) {
int pound = line.indexOf('#');
if (pound >= 0)
line = line.substring(0, pound);
line.trim();
if (!"".equals(line))
return line;
}
} finally {
try {
if (br != null)
br.close();
}
catch (IOException e) {
// did our best; just ignore
}
}
return null;
}
private String getStorageAreaRoot() {
BundleContext context = getBundleContextWithoutFail();
if (context == null) {
String storageroot = System.getProperty(STORAGEROOT);
assertNotNull("Must set property: " + STORAGEROOT, storageroot);
return storageroot;
}
return context.getDataFile("storageroot").getAbsolutePath();
}
private Class loadFrameworkClass(String className)
throws ClassNotFoundException {
BundleContext context = getBundleContextWithoutFail();
return context == null ? Class.forName(className) : getContext().getBundle(0).loadClass(className);
}
private BundleContext getBundleContextWithoutFail() {
try {
if ("true".equals(System.getProperty("noframework")))
return null;
return getContext();
} catch (Throwable t) {
return null; // don't fail
}
}
private FrameworkFactory getFrameworkFactory() {
try {
Class clazz = loadFrameworkClass(frameworkFactoryClassName);
return (FrameworkFactory) clazz.newInstance();
} catch (Exception e) {
fail("Failed to get the framework constructor", e);
}
return null;
}
private File getStorageArea(String testName, boolean delete) {
File storageArea = new File(rootStorageArea, testName);
if (delete) {
assertTrue("Could not clean up storage area: " + storageArea.getPath(), delete(storageArea));
assertTrue("Could not create storage area directory: " + storageArea.getPath(), storageArea.mkdirs());
}
return storageArea;
}
private boolean delete(File file) {
if (file.exists()) {
if (file.isDirectory()) {
String list[] = file.list();
if (list != null) {
int len = list.length;
for (int i = 0; i < len; i++)
if (!delete(new File(file, list[i])))
return false;
}
}
return file.delete();
}
return (true);
}
private Framework createFramework(Map configuration) {
Framework framework = null;
try {
framework = frameworkFactory.newFramework(configuration);
}
catch (Exception e) {
fail("Failed to construct the framework", e);
}
assertEquals("Wrong state for newly constructed framework", Bundle.INSTALLED, framework.getState());
return framework;
}
private Map getConfiguration(String testName) {
return getConfiguration(testName, true);
}
private Map getConfiguration(String testName, boolean delete) {
Map configuration = new HashMap();
if (testName != null)
configuration.put(Constants.FRAMEWORK_STORAGE, getStorageArea(testName, delete).getAbsolutePath());
return configuration;
}
private Bundle installBundle(Framework framework, String bundle) {
BundleContext fwkContext = framework.getBundleContext();
assertNotNull("Framework context is null", fwkContext);
URL input = getBundleInput(bundle);
assertNotNull("Cannot find resource: " + bundle, input);
try {
return fwkContext.installBundle(bundle, input.openStream());
} catch (Exception e) {
fail("Unexpected exception installing: " + bundle, e);
return null;
}
}
private URL getBundleInput(String bundle) {
BundleContext context = getBundleContextWithoutFail();
return context == null ? this.getClass().getResource(bundle) : context.getBundle().getEntry(bundle);
}
private void initFramework(Framework framework) {
try {
framework.init();
assertNotNull("BundleContext is null after init", framework.getBundleContext());
}
catch (BundleException e) {
fail("Unexpected BundleException initializing", e);
}
assertEquals("Wrong framework state after init", Bundle.STARTING, framework.getState());
}
private void startFramework(Framework framework) {
try {
framework.start();
assertNotNull("BundleContext is null after start", framework.getBundleContext());
}
catch (BundleException e) {
fail("Unexpected BundleException initializing", e);
}
assertEquals("Wrong framework state after init", Bundle.ACTIVE, framework.getState());
}
private void stopFramework(Framework framework) {
int previousState = framework.getState();
try {
framework.stop();
FrameworkEvent event = framework.waitForStop(10000);
assertNotNull("FrameworkEvent is null", event);
assertEquals("Wrong event type", FrameworkEvent.STOPPED, event.getType());
assertNull("BundleContext is not null after stop", framework.getBundleContext());
}
catch (BundleException e) {
fail("Unexpected BundleException stopping", e);
}
catch (InterruptedException e) {
fail("Unexpected InterruptedException waiting for stop", e);
}
// if the framework was not STARTING STOPPING or ACTIVE then we assume the waitForStop returned immediately with a FrameworkEvent.STOPPED
// and does not change the state of the framework
int expectedState = (previousState & (Bundle.STARTING | Bundle.ACTIVE | Bundle.STOPPING)) != 0 ? Bundle.RESOLVED : previousState;
assertEquals("Wrong framework state after init", expectedState, framework.getState());
}
private CompositeBundle createCompositeBundle(CompositeAdmin factory, String location, Map compositeManifest, Map configuration) {
return createCompositeBundle(factory, location, compositeManifest, configuration, false);
}
private CompositeBundle createCompositeBundle(CompositeAdmin factory, String location, Map compositeManifest, Map configuration, boolean expectedFail) {
if (configuration == null)
configuration = new HashMap();
if (compositeManifest == null)
compositeManifest = new HashMap();
if (compositeManifest.get(Constants.BUNDLE_SYMBOLICNAME) == null)
compositeManifest.put(Constants.BUNDLE_SYMBOLICNAME, location + "; " + CompositeConstants.COMPOSITE_DIRECTIVE + ":=true");
CompositeBundle composite = null;
try {
composite = factory.installCompositeBundle(location, compositeManifest, configuration);
if (expectedFail)
fail("Expected to fail composite installation: " + location);
} catch (BundleException e) {
if (!expectedFail)
fail("Unexpected exception creating composite bundle", e); //$NON-NLS-1$
return null;
}
assertNotNull("Composite is null", composite); //$NON-NLS-1$
assertEquals("Wrong composite location", location, composite.getLocation()); //$NON-NLS-1$
assertNotNull("Compoisite System Bundle context must not be null", composite.getSystemBundleContext());
assertEquals("Wrong state for SystemBundle", Bundle.STARTING, composite.getSystemBundleContext().getBundle().getState()); //$NON-NLS-1$
return composite;
}
protected Bundle installConstituent(CompositeBundle composite, String location, String name) {
return installConstituent(composite, location, name, false);
}
protected Bundle installConstituent(CompositeBundle composite, String location, String name, boolean expectFail) {
try {
URL content = getBundleInput(name);
String externalForm = content.toExternalForm();
if (location == null)
location = externalForm;
BundleContext context = composite.getSystemBundleContext();
Bundle result = (externalForm.equals(location)) ? context.installBundle(location) : context.installBundle(location, content.openStream());
if (expectFail)
fail("Expected a failure to install test bundle: " + name);
return result;
} catch (BundleException e) {
if (!expectFail)
fail("failed to install test bundle", e); //$NON-NLS-1$
} catch (IOException e) {
fail("failed to install test bundle", e); //$NON-NLS-1$
}
return null;
}
private void startBundle(Bundle bundle, boolean expectFail) {
try {
bundle.start();
if (expectFail)
fail("Expected to fail starting bundle: " + bundle.getLocation());
} catch (BundleException e) {
if (!expectFail)
fail("Unexpected failure to start bundle: " + bundle.getLocation());
}
}
private void refreshPackages(BundleContext context, Bundle[] bundles) {
ServiceReference ref = context.getServiceReference(PackageAdmin.class.getName());
assertNotNull("PackageAdmin ref is null.", ref);
PackageAdmin pa = (PackageAdmin) context.getService(ref);
assertNotNull("PackageAdmin service is null.", pa);
final boolean[] monitor = new boolean[] {false};
FrameworkListener l = new FrameworkListener() {
public void frameworkEvent(FrameworkEvent event) {
if (event.getType() != FrameworkEvent.PACKAGES_REFRESHED)
return;
synchronized (monitor) {
monitor[0] = true;
monitor.notify();
}
}
};
context.addFrameworkListener(l);
try {
pa.refreshPackages(bundles);
synchronized (monitor) {
if (!monitor[0])
monitor.wait(5000);
if (!monitor[0])
fail("Failed to finish refresh in a reasonable amount of time.");
}
} catch (InterruptedException e) {
fail("Unexpected interruption", e);
} finally {
context.ungetService(ref);
context.removeFrameworkListener(l);
}
}
public void testBasicPersistence01() {
// create a root framework
Framework rootFramework = createFramework(getConfiguration(getName()));
initFramework(rootFramework);
CompositeAdmin compositeAdmin = (CompositeAdmin) getService(rootFramework.getBundleContext(), CompositeAdmin.class.getName());
// create a composite to test persistence
CompositeBundle composite = createCompositeBundle(compositeAdmin, getName(), null, null);
long compID = composite.getBundleId(); // save the id for later
try {
composite.start();
} catch (BundleException e) {
fail("Failed to mark composite for start", e);
}
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(getConfiguration(getName(), false));
initFramework(rootFramework);
// find the persistent composite
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
}
public void testBasicPersistence02() {
// get and save a configuration for the root framework
Map configuration = getConfiguration(getName());
// create a root framework
Framework rootFramework = createFramework(configuration);
initFramework(rootFramework);
CompositeAdmin compositeAdmin = (CompositeAdmin) getService(rootFramework.getBundleContext(), CompositeAdmin.class.getName());
// create a composite to test persistence
CompositeBundle composite = createCompositeBundle(compositeAdmin, getName(), null, null);
long compID = composite.getBundleId(); // save the id for later
try {
composite.start();
} catch (BundleException e) {
fail("Failed to mark composite for start", e);
}
// install some bundles to test persistence
Bundle tb1 = installConstituent(composite, null, "/launch.tb1.jar");
Bundle tb2 = installBundle(rootFramework, "/launch.tb2.jar");
// save the ids for later
long tb1ID = tb1.getBundleId();
long tb2ID = tb2.getBundleId();
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
startFramework(rootFramework);
startBundle(tb1, false);
startBundle(tb2, true); // expect the bundle to fail to start because it cannot resolve
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
// test that the bundles are still installed
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
assertEquals("tb1 should be active", Bundle.ACTIVE, tb1.getState());
assertEquals("tb2 should be installed", Bundle.INSTALLED, tb2.getState()); // still cannot resolve the bundle
// update the composite to allow tb2 to resolve
Map manifest = new HashMap();
manifest.put(Constants.BUNDLE_SYMBOLICNAME, getName() + ';' + CompositeConstants.COMPOSITE_DIRECTIVE + ":=" + true);
manifest.put(CompositeConstants.COMPOSITE_PACKAGE_EXPORT_POLICY, "org.osgi.test.cases.composite.launch.tb1");
try {
composite.update(manifest);
} catch (BundleException e) {
fail("Failed to update composite", e);
}
refreshPackages(rootFramework.getBundleContext(), new Bundle[] {composite});
startBundle(tb2, false); // we should be able to start tb2 now.
assertEquals("tb2 should be active", Bundle.ACTIVE, tb2.getState());
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
// test that the bundles are still installed
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
assertEquals("tb1 should be active", Bundle.ACTIVE, tb1.getState());
assertEquals("tb2 should be active", Bundle.ACTIVE, tb2.getState());
try {
tb1.stop(); // test persistently stopping a tb1
} catch (BundleException e) {
fail("Failed to stop bundle", e);
}
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
// test that the bundles are still installed
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
// should be resolved but not active
assertEquals("tb1 should not be active", Bundle.RESOLVED, tb1.getState());
assertEquals("tb2 should be active", Bundle.ACTIVE, tb2.getState());
try {
composite.stop(); // test persistent stop of composite
} catch (BundleException e) {
fail("Failed to stop bundle", e);
}
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
startFramework(rootFramework);
// Both the composite and constituent bundle tb1 should not be active
assertEquals("Composite should not be active", Bundle.RESOLVED, composite.getState());
assertEquals("tb1 should not be active", Bundle.RESOLVED, tb1.getState());
assertEquals("tb2 should be active", Bundle.ACTIVE, tb2.getState());
try {
tb1.uninstall();
tb2.uninstall();
} catch (BundleException e) {
fail("Failed to uninstall bundle", e);
}
stopFramework(rootFramework);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertNotNull(composite);
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNull(tb2);
// test perstent uninstall of composite
try {
composite.uninstall();
} catch (BundleException e) {
fail("Failed to uninstall bundle", e);
}
stopFramework(rootFramework);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertNull(composite);
stopFramework(rootFramework);
}
private void setInitialStartLevel(BundleContext context, int level) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
sl.setInitialBundleStartLevel(level);
} finally {
context.ungetService(ref);
}
}
private void setBundleStartLevel(BundleContext context, Bundle bundle, int level) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
sl.setBundleStartLevel(bundle, level);
} finally {
context.ungetService(ref);
}
}
private void setStartLevel(BundleContext context, int level) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
sl.setStartLevel(level);
} finally {
context.ungetService(ref);
}
}
private int getInitialStartLevel(BundleContext context) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
return sl.getInitialBundleStartLevel();
} finally {
context.ungetService(ref);
}
}
private int getBundleStartLevel(BundleContext context, Bundle bundle) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
return sl.getBundleStartLevel(bundle);
} finally {
context.ungetService(ref);
}
}
private int getStartLevel(BundleContext context) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
return sl.getStartLevel();
} finally {
context.ungetService(ref);
}
}
public void testStartLevelPersistence01() {
// get and save a configuration for the root framework
Map configuration = getConfiguration(getName());
// create a root framework
Framework rootFramework = createFramework(configuration);
initFramework(rootFramework);
CompositeAdmin compositeAdmin = (CompositeAdmin) getService(rootFramework.getBundleContext(), CompositeAdmin.class.getName());
// create a composite to test persistence
Map compConfiguration = new HashMap();
compConfiguration.put(Constants.FRAMEWORK_BEGINNING_STARTLEVEL, "10");
CompositeBundle composite = createCompositeBundle(compositeAdmin, getName(), null, compConfiguration);
long compID = composite.getBundleId(); // save the id for later
try {
composite.start();
} catch (BundleException e) {
fail("Failed to mark composite for start", e);
}
setInitialStartLevel(composite.getSystemBundleContext(), 5);
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
startFramework(rootFramework);
assertEquals("Wrong framework start level", 1, getStartLevel(rootFramework.getBundleContext()));
assertEquals("Wrong initial start level", 1, getInitialStartLevel(rootFramework.getBundleContext()));
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertNotNull(composite);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
assertEquals("Wrong framework start level", 10, getStartLevel(composite.getSystemBundleContext()));
assertEquals("Wrong intial start level", 5, getInitialStartLevel(composite.getSystemBundleContext()));
// install some bundles to test persistence of start-level
Bundle tb1 = installConstituent(composite, null, "/launch.tb1.jar");
Bundle tb2 = installConstituent(composite, null, "/launch.tb2.jar");
Bundle tb1InRoot = installBundle(rootFramework, "/launch.tb1.jar");
// save the ids for later
long tb1ID = tb1.getBundleId();
long tb2ID = tb2.getBundleId();
long tb1InRootID = tb1InRoot.getBundleId();
// make sure their initial start-level is correct
assertEquals("Wrong bundle startlevel", 5, getBundleStartLevel(composite.getSystemBundleContext(), tb1));
assertEquals("Wrong bundle startlevel", 5, getBundleStartLevel(composite.getSystemBundleContext(), tb2));
assertEquals("Wrong bundle startlevel", 1, getBundleStartLevel(rootFramework.getBundleContext(), tb1InRoot));
setBundleStartLevel(composite.getSystemBundleContext(), tb1, 6);
setBundleStartLevel(composite.getSystemBundleContext(), tb2, 6);
setBundleStartLevel(rootFramework.getBundleContext(), tb1InRoot, 2);
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
startFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertNotNull(composite);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = composite.getSystemBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
tb1InRoot = rootFramework.getBundleContext().getBundle(tb1InRootID);
assertNotNull(tb1InRoot);
// make sure their start-level is correct
assertEquals("Wrong bundle startlevel", 6, getBundleStartLevel(composite.getSystemBundleContext(), tb1));
assertEquals("Wrong bundle startlevel", 6, getBundleStartLevel(composite.getSystemBundleContext(), tb2));
assertEquals("Wrong bundle startlevel", 2, getBundleStartLevel(rootFramework.getBundleContext(), tb1InRoot));
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
}
// TODO should split this out into another project; the RI has Cond/PermAdmin services available even without a security manager set
// For now we just make sure there is a Cond/PermAdmin service available before preceeding to test.
public void testPermisisonAdminPersistence01() {
// get and save a configuration for the root framework
Map configuration = getConfiguration(getName());
// create a root framework
Framework rootFramework = createFramework(configuration);
startFramework(rootFramework);
if (rootFramework.getBundleContext().getServiceReference(PermissionAdmin.class.getName()) == null) {
System.err.println("Cannot run test without PermissionAdmin: " + getName());
return;
}
if (rootFramework.getBundleContext().getServiceReference(ConditionalPermissionAdmin.class.getName()) == null) {
System.err.println("Cannot run test without ConditionalPermissionAdmin: " + getName());
return;
}
CompositeAdmin compositeAdmin = (CompositeAdmin) getService(rootFramework.getBundleContext(), CompositeAdmin.class.getName());
// create a composite to test persistence
CompositeBundle composite1 = createCompositeBundle(compositeAdmin, getName() + "_1", null, null);
long compID1 = composite1.getBundleId(); // save the id for later
try {
composite1.start();
} catch (BundleException e) {
fail("Failed to mark composite for start", e);
}
PermissionAdmin permAdmin1 = (PermissionAdmin) getService(composite1.getSystemBundleContext(), PermissionAdmin.class.getName());
PermissionInfo defaultPerm1 = new PermissionInfo("w.WPermission", null, null);
permAdmin1.setDefaultPermissions(new PermissionInfo[] {defaultPerm1});
PermissionInfo locationPerm1 = new PermissionInfo("x.XPermission", null, null);
permAdmin1.setPermissions("y", new PermissionInfo[] {locationPerm1});
ConditionalPermissionAdmin condAdmin1 = (ConditionalPermissionAdmin) getService(composite1.getSystemBundleContext(), ConditionalPermissionAdmin.class.getName());
ConditionalPermissionUpdate update1 = condAdmin1.newConditionalPermissionUpdate();
List infos1 = update1.getConditionalPermissionInfos();
ConditionalPermissionInfo info1 = condAdmin1.newConditionalPermissionInfo("a", new ConditionInfo[] {new ConditionInfo("a.ACondition", new String[0])},
new PermissionInfo[] {new PermissionInfo("a.APermission", null, null)}, ConditionalPermissionInfo.ALLOW);
infos1.add(info1);
update1.commit();
// create a composite to test persistence
CompositeBundle composite2 = createCompositeBundle(compositeAdmin, getName() + "_2", null, null);
long compID2 = composite2.getBundleId(); // save the id for later
try {
composite2.start();
} catch (BundleException e) {
fail("Failed to mark composite for start", e);
}
PermissionAdmin permAdmin2 = (PermissionAdmin) getService(composite2.getSystemBundleContext(), PermissionAdmin.class.getName());
PermissionInfo defaultPerm2 = new PermissionInfo("y.YPermission", null, null);
permAdmin2.setDefaultPermissions(new PermissionInfo[] {defaultPerm2});
PermissionInfo locationPerm2 = new PermissionInfo("z.ZPermission", null, null);
permAdmin2.setPermissions("z", new PermissionInfo[] {locationPerm2});
ConditionalPermissionAdmin condAdmin2 = (ConditionalPermissionAdmin) getService(composite2.getSystemBundleContext(), ConditionalPermissionAdmin.class.getName());
ConditionalPermissionUpdate update2 = condAdmin2.newConditionalPermissionUpdate();
List infos2 = update2.getConditionalPermissionInfos();
ConditionalPermissionInfo info2 = condAdmin2.newConditionalPermissionInfo("b", new ConditionInfo[] {new ConditionInfo("b.BCondition", new String[0])},
new PermissionInfo[] {new PermissionInfo("b.BPermission", null, null)}, ConditionalPermissionInfo.ALLOW);
infos2.add(info2);
update2.commit();
stopFramework(rootFramework);
assertFalse("Composite is active", composite2.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
startFramework(rootFramework);
composite1 = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID1);
assertNotNull(composite1);
assertEquals("Composite1 is not active", Bundle.ACTIVE, composite1.getState());
composite2 = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID2);
assertNotNull(composite2);
assertEquals("Composite2 is not active", Bundle.ACTIVE, composite2.getState());
permAdmin1 = (PermissionAdmin) getService(composite1.getSystemBundleContext(), PermissionAdmin.class.getName());
PermissionInfo[] defaultPerms1 = permAdmin1.getDefaultPermissions();
assertNotNull("Default permissions is null.", defaultPerms1);
assertEquals("Wrong number of permissions.", 1, defaultPerms1.length);
assertEquals("Wrong permission info.", defaultPerm1.getEncoded(), defaultPerms1[0].getEncoded());
String[] locations1 = permAdmin1.getLocations();
assertNotNull("locations is null.", locations1);
assertEquals("Wrong number of locations.", 1, locations1.length);
assertEquals("Wrong location.", "y", locations1[0]);
PermissionInfo[] locationPerms1 = permAdmin1.getPermissions(locations1[0]);
assertEquals("Wrong number of permissions.", 1, locationPerms1.length);
assertEquals("Wrong permission info.", locationPerm1.getEncoded(), locationPerms1[0].getEncoded());
condAdmin1 = (ConditionalPermissionAdmin) getService(composite1.getSystemBundleContext(), ConditionalPermissionAdmin.class.getName());
update1 = condAdmin1.newConditionalPermissionUpdate();
infos1 = update1.getConditionalPermissionInfos();
assertEquals("Wrong number of infos.", 1, infos1.size());
ConditionalPermissionInfo info1_reify = (ConditionalPermissionInfo) infos1.get(0);
assertEquals("Wrong info", info1.getEncoded(), info1_reify.getEncoded());
permAdmin2 = (PermissionAdmin) getService(composite2.getSystemBundleContext(), PermissionAdmin.class.getName());
PermissionInfo[] defaultPerms2 = permAdmin2.getDefaultPermissions();
assertNotNull("Default permissions is null.", defaultPerms2);
assertEquals("Wrong number of permissions.", 1, defaultPerms2.length);
assertEquals("Wrong permission info.", defaultPerm2.getEncoded(), defaultPerms2[0].getEncoded());
String[] locations2 = permAdmin2.getLocations();
assertNotNull("locations is null.", locations2);
assertEquals("Wrong number of locations.", 1, locations2.length);
assertEquals("Wrong location.", "z", locations2[0]);
PermissionInfo[] locationPerms2 = permAdmin2.getPermissions(locations2[0]);
assertEquals("Wrong number of permissions.", 1, locationPerms2.length);
assertEquals("Wrong permission info.", locationPerm2.getEncoded(), locationPerms2[0].getEncoded());
condAdmin2 = (ConditionalPermissionAdmin) getService(composite2.getSystemBundleContext(), ConditionalPermissionAdmin.class.getName());
update2 = condAdmin2.newConditionalPermissionUpdate();
infos2 = update2.getConditionalPermissionInfos();
assertEquals("Wrong number of infos.", 1, infos2.size());
ConditionalPermissionInfo info2_reify = (ConditionalPermissionInfo) infos2.get(0);
assertEquals("Wrong info", info2.getEncoded(), info2_reify.getEncoded());
stopFramework(rootFramework);
assertFalse("Composite is active", composite2.getState() == Bundle.ACTIVE);
}
}
|
org.osgi.test.cases.composite.launch/src/org/osgi/test/cases/composite/launch/junit/CompositePersistenceTests.java
|
/*
* Copyright (c) OSGi Alliance (2009). 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 org.osgi.test.cases.composite.launch.junit;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
import org.osgi.service.composite.CompositeAdmin;
import org.osgi.service.composite.CompositeBundle;
import org.osgi.service.composite.CompositeConstants;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.startlevel.StartLevel;
import org.osgi.test.support.OSGiTestCase;
public class CompositePersistenceTests extends OSGiTestCase {
private static final String STORAGEROOT = "org.osgi.test.cases.composite.launch";
private static final String FRAMEWORK_FACTORY = "/META-INF/services/org.osgi.framework.launch.FrameworkFactory";
private String frameworkFactoryClassName;
private String rootStorageArea;
private FrameworkFactory frameworkFactory;
protected void setUp() throws Exception {
super.setUp();
frameworkFactoryClassName = getFrameworkFactoryClassName();
assertNotNull("Could not find framework factory class", frameworkFactoryClassName);
frameworkFactory = getFrameworkFactory();
rootStorageArea = getStorageAreaRoot();
assertNotNull("No storage area root found", rootStorageArea);
File rootFile = new File(rootStorageArea);
assertFalse("Root storage area is not a directory: " + rootFile.getPath(), rootFile.exists() && !rootFile.isDirectory());
if (!rootFile.isDirectory())
assertTrue("Could not create root directory: " + rootFile.getPath(), rootFile.mkdirs());
}
private Object getService(BundleContext context, String serviceName) {
assertNotNull("context is null!", context);
ServiceReference ref = context.getServiceReference(serviceName);
assertNotNull(serviceName + " reference is null!", ref);
Object service = context.getService(ref);
assertNotNull(serviceName + " is null!", service);
return service;
}
private String getFrameworkFactoryClassName() throws IOException {
BundleContext context = getBundleContextWithoutFail();
URL factoryService = context == null ? this.getClass().getResource(FRAMEWORK_FACTORY) : context.getBundle(0).getEntry(FRAMEWORK_FACTORY);
assertNotNull("Could not locate: " + FRAMEWORK_FACTORY, factoryService);
return getClassName(factoryService);
}
private String getClassName(URL factoryService) throws IOException {
InputStream in = factoryService.openStream();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(in));
for (String line = br.readLine(); line != null; line=br.readLine()) {
int pound = line.indexOf('#');
if (pound >= 0)
line = line.substring(0, pound);
line.trim();
if (!"".equals(line))
return line;
}
} finally {
try {
if (br != null)
br.close();
}
catch (IOException e) {
// did our best; just ignore
}
}
return null;
}
private String getStorageAreaRoot() {
BundleContext context = getBundleContextWithoutFail();
if (context == null) {
String storageroot = System.getProperty(STORAGEROOT);
assertNotNull("Must set property: " + STORAGEROOT, storageroot);
return storageroot;
}
return context.getDataFile("storageroot").getAbsolutePath();
}
private Class loadFrameworkClass(String className)
throws ClassNotFoundException {
BundleContext context = getBundleContextWithoutFail();
return context == null ? Class.forName(className) : getContext().getBundle(0).loadClass(className);
}
private BundleContext getBundleContextWithoutFail() {
try {
if ("true".equals(System.getProperty("noframework")))
return null;
return getContext();
} catch (Throwable t) {
return null; // don't fail
}
}
private FrameworkFactory getFrameworkFactory() {
try {
Class clazz = loadFrameworkClass(frameworkFactoryClassName);
return (FrameworkFactory) clazz.newInstance();
} catch (Exception e) {
fail("Failed to get the framework constructor", e);
}
return null;
}
private File getStorageArea(String testName, boolean delete) {
File storageArea = new File(rootStorageArea, testName);
if (delete) {
assertTrue("Could not clean up storage area: " + storageArea.getPath(), delete(storageArea));
assertTrue("Could not create storage area directory: " + storageArea.getPath(), storageArea.mkdirs());
}
return storageArea;
}
private boolean delete(File file) {
if (file.exists()) {
if (file.isDirectory()) {
String list[] = file.list();
if (list != null) {
int len = list.length;
for (int i = 0; i < len; i++)
if (!delete(new File(file, list[i])))
return false;
}
}
return file.delete();
}
return (true);
}
private Framework createFramework(Map configuration) {
Framework framework = null;
try {
framework = frameworkFactory.newFramework(configuration);
}
catch (Exception e) {
fail("Failed to construct the framework", e);
}
assertEquals("Wrong state for newly constructed framework", Bundle.INSTALLED, framework.getState());
return framework;
}
private Map getConfiguration(String testName) {
return getConfiguration(testName, true);
}
private Map getConfiguration(String testName, boolean delete) {
Map configuration = new HashMap();
if (testName != null)
configuration.put(Constants.FRAMEWORK_STORAGE, getStorageArea(testName, delete).getAbsolutePath());
return configuration;
}
private Bundle installBundle(Framework framework, String bundle) {
BundleContext fwkContext = framework.getBundleContext();
assertNotNull("Framework context is null", fwkContext);
URL input = getBundleInput(bundle);
assertNotNull("Cannot find resource: " + bundle, input);
try {
return fwkContext.installBundle(bundle, input.openStream());
} catch (Exception e) {
fail("Unexpected exception installing: " + bundle, e);
return null;
}
}
private URL getBundleInput(String bundle) {
BundleContext context = getBundleContextWithoutFail();
return context == null ? this.getClass().getResource(bundle) : context.getBundle().getEntry(bundle);
}
private void initFramework(Framework framework) {
try {
framework.init();
assertNotNull("BundleContext is null after init", framework.getBundleContext());
}
catch (BundleException e) {
fail("Unexpected BundleException initializing", e);
}
assertEquals("Wrong framework state after init", Bundle.STARTING, framework.getState());
}
private void startFramework(Framework framework) {
try {
framework.start();
assertNotNull("BundleContext is null after start", framework.getBundleContext());
}
catch (BundleException e) {
fail("Unexpected BundleException initializing", e);
}
assertEquals("Wrong framework state after init", Bundle.ACTIVE, framework.getState());
}
private void stopFramework(Framework framework) {
int previousState = framework.getState();
try {
framework.stop();
FrameworkEvent event = framework.waitForStop(10000);
assertNotNull("FrameworkEvent is null", event);
assertEquals("Wrong event type", FrameworkEvent.STOPPED, event.getType());
assertNull("BundleContext is not null after stop", framework.getBundleContext());
}
catch (BundleException e) {
fail("Unexpected BundleException stopping", e);
}
catch (InterruptedException e) {
fail("Unexpected InterruptedException waiting for stop", e);
}
// if the framework was not STARTING STOPPING or ACTIVE then we assume the waitForStop returned immediately with a FrameworkEvent.STOPPED
// and does not change the state of the framework
int expectedState = (previousState & (Bundle.STARTING | Bundle.ACTIVE | Bundle.STOPPING)) != 0 ? Bundle.RESOLVED : previousState;
assertEquals("Wrong framework state after init", expectedState, framework.getState());
}
private CompositeBundle createCompositeBundle(CompositeAdmin factory, String location, Map compositeManifest, Map configuration) {
return createCompositeBundle(factory, location, compositeManifest, configuration, false);
}
private CompositeBundle createCompositeBundle(CompositeAdmin factory, String location, Map compositeManifest, Map configuration, boolean expectedFail) {
if (configuration == null)
configuration = new HashMap();
if (compositeManifest == null)
compositeManifest = new HashMap();
if (compositeManifest.get(Constants.BUNDLE_SYMBOLICNAME) == null)
compositeManifest.put(Constants.BUNDLE_SYMBOLICNAME, location + "; " + CompositeConstants.COMPOSITE_DIRECTIVE + ":=true");
CompositeBundle composite = null;
try {
composite = factory.installCompositeBundle(location, compositeManifest, configuration);
if (expectedFail)
fail("Expected to fail composite installation: " + location);
} catch (BundleException e) {
if (!expectedFail)
fail("Unexpected exception creating composite bundle", e); //$NON-NLS-1$
return null;
}
assertNotNull("Composite is null", composite); //$NON-NLS-1$
assertEquals("Wrong composite location", location, composite.getLocation()); //$NON-NLS-1$
assertNotNull("Compoisite System Bundle context must not be null", composite.getSystemBundleContext());
assertEquals("Wrong state for SystemBundle", Bundle.STARTING, composite.getSystemBundleContext().getBundle().getState()); //$NON-NLS-1$
return composite;
}
protected Bundle installConstituent(CompositeBundle composite, String location, String name) {
return installConstituent(composite, location, name, false);
}
protected Bundle installConstituent(CompositeBundle composite, String location, String name, boolean expectFail) {
try {
URL content = getBundleInput(name);
String externalForm = content.toExternalForm();
if (location == null)
location = externalForm;
BundleContext context = composite.getSystemBundleContext();
Bundle result = (externalForm.equals(location)) ? context.installBundle(location) : context.installBundle(location, content.openStream());
if (expectFail)
fail("Expected a failure to install test bundle: " + name);
return result;
} catch (BundleException e) {
if (!expectFail)
fail("failed to install test bundle", e); //$NON-NLS-1$
} catch (IOException e) {
fail("failed to install test bundle", e); //$NON-NLS-1$
}
return null;
}
private void startBundle(Bundle bundle, boolean expectFail) {
try {
bundle.start();
if (expectFail)
fail("Expected to fail starting bundle: " + bundle.getLocation());
} catch (BundleException e) {
if (!expectFail)
fail("Unexpected failure to start bundle: " + bundle.getLocation());
}
}
private void refreshPackages(BundleContext context, Bundle[] bundles) {
ServiceReference ref = context.getServiceReference(PackageAdmin.class.getName());
assertNotNull("PackageAdmin ref is null.", ref);
PackageAdmin pa = (PackageAdmin) context.getService(ref);
assertNotNull("PackageAdmin service is null.", pa);
final boolean[] monitor = new boolean[] {false};
FrameworkListener l = new FrameworkListener() {
public void frameworkEvent(FrameworkEvent event) {
if (event.getType() != FrameworkEvent.PACKAGES_REFRESHED)
return;
synchronized (monitor) {
monitor[0] = true;
monitor.notify();
}
}
};
context.addFrameworkListener(l);
try {
pa.refreshPackages(bundles);
synchronized (monitor) {
if (!monitor[0])
monitor.wait(5000);
if (!monitor[0])
fail("Failed to finish refresh in a reasonable amount of time.");
}
} catch (InterruptedException e) {
fail("Unexpected interruption", e);
} finally {
context.ungetService(ref);
context.removeFrameworkListener(l);
}
}
public void testBasicPersistence01() {
// create a root framework
Framework rootFramework = createFramework(getConfiguration(getName()));
initFramework(rootFramework);
CompositeAdmin compositeAdmin = (CompositeAdmin) getService(rootFramework.getBundleContext(), CompositeAdmin.class.getName());
// create a composite to test persistence
CompositeBundle composite = createCompositeBundle(compositeAdmin, getName(), null, null);
long compID = composite.getBundleId(); // save the id for later
try {
composite.start();
} catch (BundleException e) {
fail("Failed to mark composite for start", e);
}
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(getConfiguration(getName(), false));
initFramework(rootFramework);
// find the persistent composite
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
}
public void testBasicPersistence02() {
// get and save a configuration for the root framework
Map configuration = getConfiguration(getName());
// create a root framework
Framework rootFramework = createFramework(configuration);
initFramework(rootFramework);
CompositeAdmin compositeAdmin = (CompositeAdmin) getService(rootFramework.getBundleContext(), CompositeAdmin.class.getName());
// create a composite to test persistence
CompositeBundle composite = createCompositeBundle(compositeAdmin, getName(), null, null);
long compID = composite.getBundleId(); // save the id for later
try {
composite.start();
} catch (BundleException e) {
fail("Failed to mark composite for start", e);
}
// install some bundles to test persistence
Bundle tb1 = installConstituent(composite, null, "/launch.tb1.jar");
Bundle tb2 = installBundle(rootFramework, "/launch.tb2.jar");
// save the ids for later
long tb1ID = tb1.getBundleId();
long tb2ID = tb2.getBundleId();
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
startFramework(rootFramework);
startBundle(tb1, false);
startBundle(tb2, true); // expect the bundle to fail to start because it cannot resolve
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
// test that the bundles are still installed
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
assertEquals("tb1 should be active", Bundle.ACTIVE, tb1.getState());
assertEquals("tb2 should be installed", Bundle.INSTALLED, tb2.getState()); // still cannot resolve the bundle
// update the composite to allow tb2 to resolve
Map manifest = new HashMap();
manifest.put(Constants.BUNDLE_SYMBOLICNAME, getName() + ';' + CompositeConstants.COMPOSITE_DIRECTIVE + ":=" + true);
manifest.put(CompositeConstants.COMPOSITE_PACKAGE_EXPORT_POLICY, "org.osgi.test.cases.composite.launch.tb1");
try {
composite.update(manifest);
} catch (BundleException e) {
fail("Failed to update composite", e);
}
refreshPackages(rootFramework.getBundleContext(), new Bundle[] {composite});
startBundle(tb2, false); // we should be able to start tb2 now.
assertEquals("tb2 should be active", Bundle.ACTIVE, tb2.getState());
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
// test that the bundles are still installed
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
assertEquals("tb1 should be active", Bundle.ACTIVE, tb1.getState());
assertEquals("tb2 should be active", Bundle.ACTIVE, tb2.getState());
try {
tb1.stop(); // test persistently stopping a tb1
} catch (BundleException e) {
fail("Failed to stop bundle", e);
}
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
// test that the bundles are still installed
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
startFramework(rootFramework);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
// should be resolved but not active
assertEquals("tb1 should not be active", Bundle.RESOLVED, tb1.getState());
assertEquals("tb2 should be active", Bundle.ACTIVE, tb2.getState());
try {
composite.stop(); // test persistent stop of composite
} catch (BundleException e) {
fail("Failed to stop bundle", e);
}
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
startFramework(rootFramework);
// Both the composite and constituent bundle tb1 should not be active
assertEquals("Composite should not be active", Bundle.RESOLVED, composite.getState());
assertEquals("tb1 should not be active", Bundle.RESOLVED, tb1.getState());
assertEquals("tb2 should be active", Bundle.ACTIVE, tb2.getState());
try {
tb1.uninstall();
tb2.uninstall();
} catch (BundleException e) {
fail("Failed to uninstall bundle", e);
}
stopFramework(rootFramework);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertNotNull(composite);
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNull(tb1);
tb2 = rootFramework.getBundleContext().getBundle(tb2ID);
assertNull(tb2);
// test perstent uninstall of composite
try {
composite.uninstall();
} catch (BundleException e) {
fail("Failed to uninstall bundle", e);
}
stopFramework(rootFramework);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
initFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertNull(composite);
stopFramework(rootFramework);
}
private void setInitialStartLevel(BundleContext context, int level) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
sl.setInitialBundleStartLevel(level);
} finally {
context.ungetService(ref);
}
}
private void setBundleStartLevel(BundleContext context, Bundle bundle, int level) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
sl.setBundleStartLevel(bundle, level);
} finally {
context.ungetService(ref);
}
}
private void setStartLevel(BundleContext context, int level) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
sl.setStartLevel(level);
} finally {
context.ungetService(ref);
}
}
private int getInitialStartLevel(BundleContext context) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
return sl.getInitialBundleStartLevel();
} finally {
context.ungetService(ref);
}
}
private int getBundleStartLevel(BundleContext context, Bundle bundle) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
return sl.getBundleStartLevel(bundle);
} finally {
context.ungetService(ref);
}
}
private int getStartLevel(BundleContext context) {
ServiceReference ref = context.getServiceReference(StartLevel.class.getName());
assertNotNull(ref);
StartLevel sl = (StartLevel) context.getService(ref);
assertNotNull(sl);
try {
return sl.getStartLevel();
} finally {
context.ungetService(ref);
}
}
public void testStartLevelPersistence01() {
// get and save a configuration for the root framework
Map configuration = getConfiguration(getName());
// create a root framework
Framework rootFramework = createFramework(configuration);
initFramework(rootFramework);
CompositeAdmin compositeAdmin = (CompositeAdmin) getService(rootFramework.getBundleContext(), CompositeAdmin.class.getName());
// create a composite to test persistence
Map compConfiguration = new HashMap();
compConfiguration.put(Constants.FRAMEWORK_BEGINNING_STARTLEVEL, "10");
CompositeBundle composite = createCompositeBundle(compositeAdmin, getName(), null, compConfiguration);
long compID = composite.getBundleId(); // save the id for later
try {
composite.start();
} catch (BundleException e) {
fail("Failed to mark composite for start", e);
}
setInitialStartLevel(composite.getSystemBundleContext(), 5);
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
startFramework(rootFramework);
assertEquals("Wrong framework start level", 1, getStartLevel(rootFramework.getBundleContext()));
assertEquals("Wrong initial start level", 1, getInitialStartLevel(rootFramework.getBundleContext()));
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertNotNull(composite);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
assertEquals("Wrong framework start level", 10, getStartLevel(composite.getSystemBundleContext()));
assertEquals("Wrong intial start level", 5, getInitialStartLevel(composite.getSystemBundleContext()));
// install some bundles to test persistence of start-level
Bundle tb1 = installConstituent(composite, null, "/launch.tb1.jar");
Bundle tb2 = installConstituent(composite, null, "/launch.tb2.jar");
Bundle tb1InRoot = installBundle(rootFramework, "/launch.tb1.jar");
// save the ids for later
long tb1ID = tb1.getBundleId();
long tb2ID = tb2.getBundleId();
long tb1InRootID = tb1InRoot.getBundleId();
// make sure their initial start-level is correct
assertEquals("Wrong bundle startlevel", 5, getBundleStartLevel(composite.getSystemBundleContext(), tb1));
assertEquals("Wrong bundle startlevel", 5, getBundleStartLevel(composite.getSystemBundleContext(), tb2));
assertEquals("Wrong bundle startlevel", 1, getBundleStartLevel(rootFramework.getBundleContext(), tb1InRoot));
setBundleStartLevel(composite.getSystemBundleContext(), tb1, 6);
setBundleStartLevel(composite.getSystemBundleContext(), tb2, 6);
setBundleStartLevel(rootFramework.getBundleContext(), tb1InRoot, 2);
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
// reify the root framework from the previously used storage area
rootFramework = createFramework(configuration);
startFramework(rootFramework);
composite = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID);
assertNotNull(composite);
assertEquals("Composite is not active", Bundle.ACTIVE, composite.getState());
tb1 = composite.getSystemBundleContext().getBundle(tb1ID);
assertNotNull(tb1);
tb2 = composite.getSystemBundleContext().getBundle(tb2ID);
assertNotNull(tb2);
tb1InRoot = rootFramework.getBundleContext().getBundle(tb1InRootID);
assertNotNull(tb1InRoot);
// make sure their start-level is correct
assertEquals("Wrong bundle startlevel", 6, getBundleStartLevel(composite.getSystemBundleContext(), tb1));
assertEquals("Wrong bundle startlevel", 6, getBundleStartLevel(composite.getSystemBundleContext(), tb2));
assertEquals("Wrong bundle startlevel", 2, getBundleStartLevel(rootFramework.getBundleContext(), tb1InRoot));
stopFramework(rootFramework);
assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
}
}
|
Add test for permission admin persistence.
|
org.osgi.test.cases.composite.launch/src/org/osgi/test/cases/composite/launch/junit/CompositePersistenceTests.java
|
Add test for permission admin persistence.
|
<ide><path>rg.osgi.test.cases.composite.launch/src/org/osgi/test/cases/composite/launch/junit/CompositePersistenceTests.java
<ide> import java.io.InputStreamReader;
<ide> import java.net.URL;
<ide> import java.util.HashMap;
<add>import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import org.osgi.framework.Bundle;
<ide> import org.osgi.service.composite.CompositeAdmin;
<ide> import org.osgi.service.composite.CompositeBundle;
<ide> import org.osgi.service.composite.CompositeConstants;
<add>import org.osgi.service.condpermadmin.ConditionInfo;
<add>import org.osgi.service.condpermadmin.ConditionalPermissionAdmin;
<add>import org.osgi.service.condpermadmin.ConditionalPermissionInfo;
<add>import org.osgi.service.condpermadmin.ConditionalPermissionUpdate;
<ide> import org.osgi.service.packageadmin.PackageAdmin;
<add>import org.osgi.service.permissionadmin.PermissionAdmin;
<add>import org.osgi.service.permissionadmin.PermissionInfo;
<ide> import org.osgi.service.startlevel.StartLevel;
<ide> import org.osgi.test.support.OSGiTestCase;
<ide>
<ide> stopFramework(rootFramework);
<ide> assertFalse("Composite is active", composite.getState() == Bundle.ACTIVE);
<ide> }
<add>
<add> // TODO should split this out into another project; the RI has Cond/PermAdmin services available even without a security manager set
<add> // For now we just make sure there is a Cond/PermAdmin service available before preceeding to test.
<add> public void testPermisisonAdminPersistence01() {
<add> // get and save a configuration for the root framework
<add> Map configuration = getConfiguration(getName());
<add> // create a root framework
<add> Framework rootFramework = createFramework(configuration);
<add> startFramework(rootFramework);
<add> if (rootFramework.getBundleContext().getServiceReference(PermissionAdmin.class.getName()) == null) {
<add> System.err.println("Cannot run test without PermissionAdmin: " + getName());
<add> return;
<add> }
<add> if (rootFramework.getBundleContext().getServiceReference(ConditionalPermissionAdmin.class.getName()) == null) {
<add> System.err.println("Cannot run test without ConditionalPermissionAdmin: " + getName());
<add> return;
<add> }
<add>
<add> CompositeAdmin compositeAdmin = (CompositeAdmin) getService(rootFramework.getBundleContext(), CompositeAdmin.class.getName());
<add>
<add> // create a composite to test persistence
<add> CompositeBundle composite1 = createCompositeBundle(compositeAdmin, getName() + "_1", null, null);
<add> long compID1 = composite1.getBundleId(); // save the id for later
<add> try {
<add> composite1.start();
<add> } catch (BundleException e) {
<add> fail("Failed to mark composite for start", e);
<add> }
<add>
<add> PermissionAdmin permAdmin1 = (PermissionAdmin) getService(composite1.getSystemBundleContext(), PermissionAdmin.class.getName());
<add> PermissionInfo defaultPerm1 = new PermissionInfo("w.WPermission", null, null);
<add> permAdmin1.setDefaultPermissions(new PermissionInfo[] {defaultPerm1});
<add> PermissionInfo locationPerm1 = new PermissionInfo("x.XPermission", null, null);
<add> permAdmin1.setPermissions("y", new PermissionInfo[] {locationPerm1});
<add> ConditionalPermissionAdmin condAdmin1 = (ConditionalPermissionAdmin) getService(composite1.getSystemBundleContext(), ConditionalPermissionAdmin.class.getName());
<add> ConditionalPermissionUpdate update1 = condAdmin1.newConditionalPermissionUpdate();
<add> List infos1 = update1.getConditionalPermissionInfos();
<add> ConditionalPermissionInfo info1 = condAdmin1.newConditionalPermissionInfo("a", new ConditionInfo[] {new ConditionInfo("a.ACondition", new String[0])},
<add> new PermissionInfo[] {new PermissionInfo("a.APermission", null, null)}, ConditionalPermissionInfo.ALLOW);
<add> infos1.add(info1);
<add> update1.commit();
<add>
<add> // create a composite to test persistence
<add> CompositeBundle composite2 = createCompositeBundle(compositeAdmin, getName() + "_2", null, null);
<add> long compID2 = composite2.getBundleId(); // save the id for later
<add> try {
<add> composite2.start();
<add> } catch (BundleException e) {
<add> fail("Failed to mark composite for start", e);
<add> }
<add>
<add> PermissionAdmin permAdmin2 = (PermissionAdmin) getService(composite2.getSystemBundleContext(), PermissionAdmin.class.getName());
<add> PermissionInfo defaultPerm2 = new PermissionInfo("y.YPermission", null, null);
<add> permAdmin2.setDefaultPermissions(new PermissionInfo[] {defaultPerm2});
<add> PermissionInfo locationPerm2 = new PermissionInfo("z.ZPermission", null, null);
<add> permAdmin2.setPermissions("z", new PermissionInfo[] {locationPerm2});
<add> ConditionalPermissionAdmin condAdmin2 = (ConditionalPermissionAdmin) getService(composite2.getSystemBundleContext(), ConditionalPermissionAdmin.class.getName());
<add> ConditionalPermissionUpdate update2 = condAdmin2.newConditionalPermissionUpdate();
<add> List infos2 = update2.getConditionalPermissionInfos();
<add> ConditionalPermissionInfo info2 = condAdmin2.newConditionalPermissionInfo("b", new ConditionInfo[] {new ConditionInfo("b.BCondition", new String[0])},
<add> new PermissionInfo[] {new PermissionInfo("b.BPermission", null, null)}, ConditionalPermissionInfo.ALLOW);
<add> infos2.add(info2);
<add> update2.commit();
<add>
<add> stopFramework(rootFramework);
<add> assertFalse("Composite is active", composite2.getState() == Bundle.ACTIVE);
<add>
<add> // reify the root framework from the previously used storage area
<add> rootFramework = createFramework(configuration);
<add> startFramework(rootFramework);
<add> composite1 = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID1);
<add> assertNotNull(composite1);
<add> assertEquals("Composite1 is not active", Bundle.ACTIVE, composite1.getState());
<add> composite2 = (CompositeBundle) rootFramework.getBundleContext().getBundle(compID2);
<add> assertNotNull(composite2);
<add> assertEquals("Composite2 is not active", Bundle.ACTIVE, composite2.getState());
<add>
<add> permAdmin1 = (PermissionAdmin) getService(composite1.getSystemBundleContext(), PermissionAdmin.class.getName());
<add> PermissionInfo[] defaultPerms1 = permAdmin1.getDefaultPermissions();
<add> assertNotNull("Default permissions is null.", defaultPerms1);
<add> assertEquals("Wrong number of permissions.", 1, defaultPerms1.length);
<add> assertEquals("Wrong permission info.", defaultPerm1.getEncoded(), defaultPerms1[0].getEncoded());
<add> String[] locations1 = permAdmin1.getLocations();
<add> assertNotNull("locations is null.", locations1);
<add> assertEquals("Wrong number of locations.", 1, locations1.length);
<add> assertEquals("Wrong location.", "y", locations1[0]);
<add> PermissionInfo[] locationPerms1 = permAdmin1.getPermissions(locations1[0]);
<add> assertEquals("Wrong number of permissions.", 1, locationPerms1.length);
<add> assertEquals("Wrong permission info.", locationPerm1.getEncoded(), locationPerms1[0].getEncoded());
<add> condAdmin1 = (ConditionalPermissionAdmin) getService(composite1.getSystemBundleContext(), ConditionalPermissionAdmin.class.getName());
<add> update1 = condAdmin1.newConditionalPermissionUpdate();
<add> infos1 = update1.getConditionalPermissionInfos();
<add> assertEquals("Wrong number of infos.", 1, infos1.size());
<add> ConditionalPermissionInfo info1_reify = (ConditionalPermissionInfo) infos1.get(0);
<add> assertEquals("Wrong info", info1.getEncoded(), info1_reify.getEncoded());
<add>
<add> permAdmin2 = (PermissionAdmin) getService(composite2.getSystemBundleContext(), PermissionAdmin.class.getName());
<add> PermissionInfo[] defaultPerms2 = permAdmin2.getDefaultPermissions();
<add> assertNotNull("Default permissions is null.", defaultPerms2);
<add> assertEquals("Wrong number of permissions.", 1, defaultPerms2.length);
<add> assertEquals("Wrong permission info.", defaultPerm2.getEncoded(), defaultPerms2[0].getEncoded());
<add> String[] locations2 = permAdmin2.getLocations();
<add> assertNotNull("locations is null.", locations2);
<add> assertEquals("Wrong number of locations.", 1, locations2.length);
<add> assertEquals("Wrong location.", "z", locations2[0]);
<add> PermissionInfo[] locationPerms2 = permAdmin2.getPermissions(locations2[0]);
<add> assertEquals("Wrong number of permissions.", 1, locationPerms2.length);
<add> assertEquals("Wrong permission info.", locationPerm2.getEncoded(), locationPerms2[0].getEncoded());
<add> condAdmin2 = (ConditionalPermissionAdmin) getService(composite2.getSystemBundleContext(), ConditionalPermissionAdmin.class.getName());
<add> update2 = condAdmin2.newConditionalPermissionUpdate();
<add> infos2 = update2.getConditionalPermissionInfos();
<add> assertEquals("Wrong number of infos.", 1, infos2.size());
<add> ConditionalPermissionInfo info2_reify = (ConditionalPermissionInfo) infos2.get(0);
<add> assertEquals("Wrong info", info2.getEncoded(), info2_reify.getEncoded());
<add>
<add> stopFramework(rootFramework);
<add> assertFalse("Composite is active", composite2.getState() == Bundle.ACTIVE);
<add>
<add> }
<ide> }
|
|
JavaScript
|
mit
|
e9b408eddfc237ab8133adfbbf708f68455a3c2f
| 0 |
jellydn/gschool,jellydn/gschool,jellydn/gschool,jellydn/gschool,jellydn/gschool
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Note = mongoose.model('Note'),
Notifications = mongoose.model('Notification'),
Comment = mongoose.model('Comment'),
User = mongoose.model('User'),
_ = require('lodash');
/**
* List of notes
*/
exports.all = function(req, res) {
var q = Comment.find({onNote : req.query.noteId});
q.sort({ dateCreate : 'desc' }).populate('createBy', 'name username avatar').exec(function(err, comments) {
if (err) {
console.log(err);
res.render('error', {
status: 500
});
} else {
res.jsonp(comments);
}
});
};
// Get note by id
exports.comment = function(req, res, next, id) {
Comment.load(id, function(err, comment) {
if (err) return next(err);
if (!comment) return next(new Error('Failed to load comment ' + id));
req.comment = comment;
next();
});
};
/**
* Create a ntoe
*/
exports.create = function(req, res) {
var comment = new Comment(req.body);
comment.createBy = req.user;
// todo: send to class and member
comment.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
comment: comment
});
} else {
// update comment
res.jsonp(comment);
// find and pregmatch username from list
var re = /(@\w+)/gi;
var found = comment.content.match(re);
console.log('find username in ' + comment.content);
console.log(found);
var userArr =[];
if(found != undefined && (found instanceof Array))
{
for (var i = 0; i < found.length; i++) {
userArr[i] = found[i].replace('@','');
};
User.find({ username : {'$in': userArr} },'id name username',function(err,users){
if (err) {
console.error(err)
}
else
for (var i = 0; i < users.length; i++) {
var userid = users[i]._id;
var notify = new Notifications();
notify.source = comment;
notify.from = req.user;
notify.to = userid;
notify.type = 'comment';
notify.content = req.user.name + ' has mentioned you on comment.' ;
notify.save();
};
})
}
Note.load(comment.onNote , function(err, note) {
if (err) return next(err);
if (!note) return next(new Error('Failed to load note ' + id));
var query = Comment.find( {onNote : comment.onNote } );
query.count(function(err,totals){
if (err) {
console.error(err);
}
else
{
note.totalComments = totals;
// notify to member and owner of note
for (var i = 0; i < note.sendToMembers.length; i++) {
var userid = note.sendToMembers[i];
var notify = new Notifications();
notify.source = comment;
notify.from = req.user;
notify.to = userid;
notify.type = 'comment';
notify.content = req.user.name + ' has commented on note "' + note.title + '"' ;
notify.save();
};
note.save();
}
});
});
}
});
};
exports.show = function(req, res) {
res.jsonp(req.comment);
};
|
packages/notes/server/controllers/comments.js
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Note = mongoose.model('Note'),
Notifications = mongoose.model('Notification'),
Comment = mongoose.model('Comment'),
User = mongoose.model('User'),
_ = require('lodash');
/**
* List of notes
*/
exports.all = function(req, res) {
var q = Comment.find({onNote : req.query.noteId});
q.sort({ dateCreate : 'desc' }).populate('createBy', 'name username avatar').exec(function(err, comments) {
if (err) {
console.log(err);
res.render('error', {
status: 500
});
} else {
res.jsonp(comments);
}
});
};
// Get note by id
exports.comment = function(req, res, next, id) {
Comment.load(id, function(err, comment) {
if (err) return next(err);
if (!comment) return next(new Error('Failed to load comment ' + id));
req.comment = comment;
next();
});
};
/**
* Create a ntoe
*/
exports.create = function(req, res) {
var comment = new Comment(req.body);
comment.createBy = req.user;
// todo: send to class and member
comment.save(function(err) {
if (err) {
return res.send('users/signup', {
errors: err.errors,
comment: comment
});
} else {
// update comment
res.jsonp(comment);
// find and pregmatch username from list
var re = /(@\w+)/gi;
var found = comment.content.match(re);
console.log('find username in ' + comment.content);
console.log(found);
var userArr =[];
if(found != undefined && (found instanceof Array))
{
for (var i = 0; i < found.length; i++) {
userArr[i] = found[i].replace('@','');
};
User.find({ username : {'$in': userArr} },'id name username',function(err,users){
if (err) {
console.error(err)
}
else
for (var i = 0; i < users.length; i++) {
userid = users[i]._id;
var notify = new Notifications();
notify.source = comment;
notify.from = req.user;
notify.to = userid;
notify.type = 'comment';
notify.content = req.user.name + ' has mentioned you on comment.' ;
notify.save();
};
})
}
Note.load(comment.onNote , function(err, note) {
if (err) return next(err);
if (!note) return next(new Error('Failed to load note ' + id));
var query = Comment.find( {onNote : comment.onNote } );
query.count(function(err,totals){
if (err) {
console.error(err);
}
else
{
note.totalComments = totals;
// notify to member and owner of note
for (var i = 0; i < note.sendToMembers.length; i++) {
var userid = note.sendToMembers[i];
var notify = new Notifications();
notify.source = comment;
notify.from = req.user;
notify.to = userid;
notify.type = 'comment';
notify.content = req.user.name + ' has commented on note "' + note.title + '"' ;
notify.save();
};
note.save();
}
});
});
}
});
};
exports.show = function(req, res) {
res.jsonp(req.comment);
};
|
Debug - comment on note
|
packages/notes/server/controllers/comments.js
|
Debug - comment on note
|
<ide><path>ackages/notes/server/controllers/comments.js
<ide> }
<ide> else
<ide> for (var i = 0; i < users.length; i++) {
<del> userid = users[i]._id;
<add> var userid = users[i]._id;
<ide> var notify = new Notifications();
<ide> notify.source = comment;
<ide> notify.from = req.user;
|
|
Java
|
apache-2.0
|
fabcc836055744ea0939b8ed09d9b83ddd023e27
| 0 |
SeleniumHQ/buck,Addepar/buck,shybovycha/buck,facebook/buck,shs96c/buck,SeleniumHQ/buck,rmaz/buck,rmaz/buck,zpao/buck,shs96c/buck,marcinkwiatkowski/buck,shs96c/buck,Addepar/buck,dsyang/buck,shs96c/buck,k21/buck,robbertvanginkel/buck,rmaz/buck,romanoid/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,zhan-xiong/buck,romanoid/buck,Addepar/buck,brettwooldridge/buck,rmaz/buck,rmaz/buck,k21/buck,dsyang/buck,romanoid/buck,SeleniumHQ/buck,robbertvanginkel/buck,shs96c/buck,marcinkwiatkowski/buck,rmaz/buck,shybovycha/buck,zhan-xiong/buck,Addepar/buck,rmaz/buck,k21/buck,LegNeato/buck,ilya-klyuchnikov/buck,zpao/buck,ilya-klyuchnikov/buck,LegNeato/buck,romanoid/buck,LegNeato/buck,romanoid/buck,rmaz/buck,JoelMarcey/buck,Addepar/buck,brettwooldridge/buck,SeleniumHQ/buck,shybovycha/buck,shybovycha/buck,JoelMarcey/buck,zhan-xiong/buck,rmaz/buck,zhan-xiong/buck,rmaz/buck,robbertvanginkel/buck,marcinkwiatkowski/buck,marcinkwiatkowski/buck,brettwooldridge/buck,clonetwin26/buck,SeleniumHQ/buck,robbertvanginkel/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,romanoid/buck,JoelMarcey/buck,JoelMarcey/buck,marcinkwiatkowski/buck,dsyang/buck,zpao/buck,JoelMarcey/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,brettwooldridge/buck,robbertvanginkel/buck,clonetwin26/buck,ilya-klyuchnikov/buck,rmaz/buck,facebook/buck,zhan-xiong/buck,shs96c/buck,dsyang/buck,clonetwin26/buck,shs96c/buck,k21/buck,romanoid/buck,dsyang/buck,kageiit/buck,k21/buck,marcinkwiatkowski/buck,facebook/buck,LegNeato/buck,dsyang/buck,kageiit/buck,zpao/buck,shybovycha/buck,brettwooldridge/buck,LegNeato/buck,robbertvanginkel/buck,shybovycha/buck,marcinkwiatkowski/buck,k21/buck,zpao/buck,zhan-xiong/buck,zhan-xiong/buck,kageiit/buck,shybovycha/buck,shybovycha/buck,LegNeato/buck,brettwooldridge/buck,marcinkwiatkowski/buck,dsyang/buck,Addepar/buck,SeleniumHQ/buck,k21/buck,nguyentruongtho/buck,k21/buck,zhan-xiong/buck,shybovycha/buck,JoelMarcey/buck,brettwooldridge/buck,clonetwin26/buck,ilya-klyuchnikov/buck,Addepar/buck,clonetwin26/buck,dsyang/buck,robbertvanginkel/buck,nguyentruongtho/buck,shybovycha/buck,JoelMarcey/buck,zhan-xiong/buck,brettwooldridge/buck,shs96c/buck,ilya-klyuchnikov/buck,k21/buck,romanoid/buck,clonetwin26/buck,JoelMarcey/buck,facebook/buck,brettwooldridge/buck,dsyang/buck,kageiit/buck,romanoid/buck,rmaz/buck,LegNeato/buck,LegNeato/buck,ilya-klyuchnikov/buck,Addepar/buck,Addepar/buck,SeleniumHQ/buck,brettwooldridge/buck,dsyang/buck,shs96c/buck,SeleniumHQ/buck,k21/buck,SeleniumHQ/buck,romanoid/buck,kageiit/buck,JoelMarcey/buck,Addepar/buck,clonetwin26/buck,rmaz/buck,clonetwin26/buck,marcinkwiatkowski/buck,LegNeato/buck,robbertvanginkel/buck,robbertvanginkel/buck,nguyentruongtho/buck,dsyang/buck,robbertvanginkel/buck,nguyentruongtho/buck,clonetwin26/buck,JoelMarcey/buck,SeleniumHQ/buck,dsyang/buck,shs96c/buck,ilya-klyuchnikov/buck,k21/buck,shybovycha/buck,facebook/buck,romanoid/buck,romanoid/buck,clonetwin26/buck,robbertvanginkel/buck,Addepar/buck,kageiit/buck,zhan-xiong/buck,LegNeato/buck,k21/buck,JoelMarcey/buck,zpao/buck,marcinkwiatkowski/buck,SeleniumHQ/buck,brettwooldridge/buck,robbertvanginkel/buck,Addepar/buck,zpao/buck,zhan-xiong/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,clonetwin26/buck,shs96c/buck,ilya-klyuchnikov/buck,romanoid/buck,clonetwin26/buck,ilya-klyuchnikov/buck,nguyentruongtho/buck,Addepar/buck,shybovycha/buck,shs96c/buck,facebook/buck,facebook/buck,shs96c/buck,LegNeato/buck,SeleniumHQ/buck,zhan-xiong/buck,robbertvanginkel/buck,LegNeato/buck,clonetwin26/buck,brettwooldridge/buck,LegNeato/buck,k21/buck,JoelMarcey/buck,marcinkwiatkowski/buck,zhan-xiong/buck,dsyang/buck,kageiit/buck,marcinkwiatkowski/buck,shybovycha/buck,nguyentruongtho/buck
|
/*
* Copyright 2014-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.cli.bootstrapper;
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.Arrays;
/**
* This class sets up a separate ClassLoader for most of Buck's implementation, leaving only the
* bare minimum bootstrapping classes (and a few classes for compatibility with library code that is
* not ClassLoader-aware) in the system ClassLoader. This is done so that annotation processors do
* not have their classpaths polluted with Buck's dependencies when Buck is compiling Java code
* in-process.
*
* <p>Under JSR-199, when the Java compiler is run in-process it uses a ClassLoader that is a child
* of the system ClassLoader. In order for annotation processors to access the Compiler Tree API
* (which lives in tools.jar with the compiler itself), they must be loaded with a ClassLoader
* descended from the compiler's. If Buck used the system ClassLoader as a normal Java application
* would, this would result in annotation processors getting Buck's versions of Guava, Jackson, etc.
* instead of their own.
*/
public final class ClassLoaderBootstrapper {
private static final ClassLoader classLoader = createClassLoader();
private ClassLoaderBootstrapper() {}
public static void main(String[] args) throws Exception {
// Some things (notably Jetty) use the context class loader to load stuff
Thread.currentThread().setContextClassLoader(classLoader);
String mainClassName = args[0];
String[] remainingArgs = Arrays.copyOfRange(args, 1, args.length);
Class<?> mainClass = classLoader.loadClass(mainClassName);
Method mainMethod = mainClass.getMethod("main", String[].class);
mainMethod.invoke(null, (Object) remainingArgs);
}
public static Class<?> loadClass(String name) {
try {
return classLoader.loadClass(name);
} catch (ClassNotFoundException e) {
throw new NoClassDefFoundError(name);
}
}
private static ClassLoader createClassLoader() {
String classPath = System.getenv("BUCK_CLASSPATH");
if (classPath == null) {
throw new RuntimeException("BUCK_CLASSPATH not set");
}
String[] strings = classPath.split(File.pathSeparator);
URL[] urls = new URL[strings.length];
for (int i = 0; i < urls.length; i++) {
try {
urls[i] = Paths.get(strings[i]).toUri().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return new URLClassLoader(urls);
}
}
|
src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapper.java
|
/*
* Copyright 2014-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.cli.bootstrapper;
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.Arrays;
/**
* This class sets up a separate ClassLoader for most of Buck's implementation, leaving only the
* bare minimum bootstrapping classes (and a few classes for compatibility with library code that is
* not ClassLoader-aware) in the system ClassLoader. This is done so that annotation processors do
* not have their classpaths polluted with Buck's dependencies when Buck is compiling Java code
* in-process.
*
* <p>Under JSR-199, when the Java compiler is run in-process it uses a ClassLoader that is a child
* of the system ClassLoader. In order for annotation processors to access the Compiler Tree API
* (which lives in tools.jar with the compiler itself), they must be loaded with a ClassLoader
* descended from the compiler's. If Buck used the system ClassLoader as a normal Java application
* would, this would result in annotation processors getting Buck's versions of Guava, Jackson, etc.
* instead of their own.
*/
public final class ClassLoaderBootstrapper {
private static ClassLoader classLoader;
private ClassLoaderBootstrapper() {}
public static void main(String[] args) throws Exception {
String classPath = System.getenv("BUCK_CLASSPATH");
if (classPath == null) {
throw new RuntimeException("BUCK_CLASSPATH not set");
}
String mainClassName = args[0];
String[] remainingArgs = Arrays.copyOfRange(args, 1, args.length);
classLoader = createClassLoader(classPath);
// Some things (notably Jetty) use the context class loader to load stuff
Thread.currentThread().setContextClassLoader(classLoader);
Class<?> mainClass = classLoader.loadClass(mainClassName);
Method mainMethod = mainClass.getMethod("main", String[].class);
mainMethod.invoke(null, (Object) remainingArgs);
}
public static Class<?> loadClass(String name) {
try {
return classLoader.loadClass(name);
} catch (ClassNotFoundException e) {
throw new NoClassDefFoundError(name);
}
}
private static ClassLoader createClassLoader(String classPath) throws MalformedURLException {
String[] strings = classPath.split(File.pathSeparator);
URL[] urls = new URL[strings.length];
for (int i = 0; i < urls.length; i++) {
urls[i] = Paths.get(strings[i]).toUri().toURL();
}
return new URLClassLoader(urls);
}
}
|
ClassLoaderBootstrapper: Create ClassLoader earlier
Summary:
When an agent such as YourKit is present in the process, it may cause `java.util.logging`
to be initialized earlier than usual, even before `main` is run. That results in a
`NullPointerException` as `com.facebook.buck.cli.bootstrapper.LogConfig` attempts to
load `com.facebook.buck.log.LogConfig`. That exception is swallowed, and simply results
in no logging.
Test Plan:
Run Buck with the YourKit agent attached from the start, observe `buck-0.log` and friends
are created and have content.
Reviewed By: dreiss
fbshipit-source-id: 013df61
|
src/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapper.java
|
ClassLoaderBootstrapper: Create ClassLoader earlier
|
<ide><path>rc/com/facebook/buck/cli/bootstrapper/ClassLoaderBootstrapper.java
<ide> * instead of their own.
<ide> */
<ide> public final class ClassLoaderBootstrapper {
<del> private static ClassLoader classLoader;
<add> private static final ClassLoader classLoader = createClassLoader();
<ide>
<ide> private ClassLoaderBootstrapper() {}
<ide>
<ide> public static void main(String[] args) throws Exception {
<del> String classPath = System.getenv("BUCK_CLASSPATH");
<del> if (classPath == null) {
<del> throw new RuntimeException("BUCK_CLASSPATH not set");
<del> }
<add> // Some things (notably Jetty) use the context class loader to load stuff
<add> Thread.currentThread().setContextClassLoader(classLoader);
<ide>
<ide> String mainClassName = args[0];
<ide> String[] remainingArgs = Arrays.copyOfRange(args, 1, args.length);
<del> classLoader = createClassLoader(classPath);
<del>
<del> // Some things (notably Jetty) use the context class loader to load stuff
<del> Thread.currentThread().setContextClassLoader(classLoader);
<ide>
<ide> Class<?> mainClass = classLoader.loadClass(mainClassName);
<ide> Method mainMethod = mainClass.getMethod("main", String[].class);
<ide> }
<ide> }
<ide>
<del> private static ClassLoader createClassLoader(String classPath) throws MalformedURLException {
<add> private static ClassLoader createClassLoader() {
<add> String classPath = System.getenv("BUCK_CLASSPATH");
<add> if (classPath == null) {
<add> throw new RuntimeException("BUCK_CLASSPATH not set");
<add> }
<add>
<ide> String[] strings = classPath.split(File.pathSeparator);
<ide> URL[] urls = new URL[strings.length];
<ide> for (int i = 0; i < urls.length; i++) {
<del> urls[i] = Paths.get(strings[i]).toUri().toURL();
<add> try {
<add> urls[i] = Paths.get(strings[i]).toUri().toURL();
<add> } catch (MalformedURLException e) {
<add> throw new RuntimeException(e);
<add> }
<ide> }
<ide>
<ide> return new URLClassLoader(urls);
|
|
Java
|
apache-2.0
|
6e6aecfb603e557192be38dbbfd10fec1ccf03a5
| 0 |
fabric8io/docker-maven-plugin,rhuss/docker-maven-plugin,fabric8io/docker-maven-plugin,rhuss/docker-maven-plugin,vjuranek/docker-maven-plugin,fabric8io/docker-maven-plugin,vjuranek/docker-maven-plugin,vjuranek/docker-maven-plugin
|
package io.fabric8.maven.docker.access.log;/*
*
* Copyright 2014 Roland Huss
*
* 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 java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import io.fabric8.maven.docker.access.DockerAccessException;
import io.fabric8.maven.docker.access.UrlBuilder;
import io.fabric8.maven.docker.access.util.RequestUtil;
import io.fabric8.maven.docker.util.Timestamp;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
/**
* Extractor for parsing the response of a log request
*
* @author roland
* @since 28/11/14
*/
public class LogRequestor extends Thread implements LogGetHandle {
// Patter for matching log entries
static final Pattern LOG_LINE = Pattern.compile("^\\[?(?<timestamp>[^\\s\\]]*)]? (?<entry>.*?)\\s*$", Pattern.DOTALL);
private final CloseableHttpClient client;
private final String containerId;
// callback called for each line extracted
private LogCallback callback;
private DockerAccessException exception;
// Remember for asynchronous handling so that the request can be aborted from the outside
private HttpUriRequest request;
private final UrlBuilder urlBuilder;
/**
* Create a helper object for requesting log entries synchronously ({@link #fetchLogs()}) or asynchronously ({@link #start()}.
*
* @param client HTTP client to use for requesting the docker host
* @param urlBuilder builder that creates docker urls
* @param containerId container for which to fetch the host
* @param callback callback to call for each line received
*/
public LogRequestor(CloseableHttpClient client, UrlBuilder urlBuilder, String containerId, LogCallback callback) {
this.client = client;
this.containerId = containerId;
this.urlBuilder = urlBuilder;
this.callback = callback;
this.exception = null;
}
/**
* Get logs and feed a callback with the content
*/
public void fetchLogs() {
try {
callback.open();
this.request = getLogRequest(false);
final HttpResponse response = client.execute(request);
parseResponse(response);
} catch (LogCallback.DoneException e) {
// Signifies we're finished with the log stream.
} catch (IOException exp) {
callback.error(exp.getMessage());
} finally {
callback.close();
}
}
// Fetch log asynchronously as stream and follow stream
public void run() {
try {
callback.open();
this.request = getLogRequest(true);
final HttpResponse response = client.execute(request);
parseResponse(response);
} catch (LogCallback.DoneException e) {
// Signifies we're finished with the log stream.
} catch (IOException e) {
callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName());
} finally {
callback.close();
}
}
private static class NoBytesReadException extends IOException {
public NoBytesReadException() {
}
}
/**
* This is a copy of ByteStreams.readFully(), with the slight change that it throws
* NoBytesReadException if zero bytes are read. Otherwise it is identical.
*
* @param in
* @param bytes
* @throws IOException
*/
private void readFully(InputStream in, byte[] bytes) throws IOException {
int read = ByteStreams.read(in, bytes, 0, bytes.length);
if (read == 0) {
throw new NoBytesReadException();
} else if (read != bytes.length) {
throw new EOFException("reached end of stream after reading "
+ read + " bytes; " + bytes.length + " bytes expected");
}
}
private boolean readStreamFrame(InputStream is) throws IOException, LogCallback.DoneException {
// Read the header, which is composed of eight bytes. The first byte is an integer
// indicating the stream type (0 = stdin, 1 = stdout, 2 = stderr), the next three are thrown
// out, and the final four are the size of the remaining stream as an integer.
ByteBuffer headerBuffer = ByteBuffer.allocate(8);
headerBuffer.order(ByteOrder.BIG_ENDIAN);
try {
this.readFully(is, headerBuffer.array());
} catch (NoBytesReadException e) {
// Not bytes read for stream. Return false to stop consuming stream.
return false;
} catch (EOFException e) {
throw new IOException("Failed to read log header. Could not read all 8 bytes. " + e.getMessage(), e);
}
// Grab the stream type (stdout, stderr, stdin) from first byte and throw away other 3 bytes.
int type = headerBuffer.get();
// Skip three bytes, then read size from remaining four bytes.
int size = headerBuffer.getInt(4);
// Ignore empty messages and keep reading.
if (size <= 0) {
return true;
}
// Read the actual message
ByteBuffer payload = ByteBuffer.allocate(size);
try {
ByteStreams.readFully(is, payload.array());
} catch (EOFException e) {
throw new IOException("Failed to read log message. Could not read all " + size + " bytes. " + e.getMessage() +
" [ Header: " + Hex.encodeHexString(headerBuffer.array()) + "]", e);
}
String message = Charsets.UTF_8.newDecoder().decode(payload).toString();
callLogCallback(type, message);
return true;
}
private void parseResponse(HttpResponse response) throws LogCallback.DoneException, IOException {
final StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
exception = new DockerAccessException("Error while reading logs (" + status + ")");
throw new LogCallback.DoneException();
}
try (InputStream is = response.getEntity().getContent()) {
while (true) {
if (!readStreamFrame(is)) {
return;
}
}
}
}
private void callLogCallback(int type, String txt) throws LogCallback.DoneException {
Matcher matcher = LOG_LINE.matcher(txt);
if (!matcher.matches()) {
callback.error(String.format("Invalid log format for '%s' (expected: \"<timestamp> <txt>\") [%04x %04x]",
txt,(int) (txt.toCharArray())[0],(int) (txt.toCharArray())[1]));
throw new LogCallback.DoneException();
}
Timestamp ts = new Timestamp(matcher.group("timestamp"));
String logTxt = matcher.group("entry");
callback.log(type, ts, logTxt);
}
private HttpUriRequest getLogRequest(boolean follow) {
return RequestUtil.newGet(urlBuilder.containerLogs(containerId, follow));
}
@Override
public void finish() {
if (request != null) {
request.abort();
request = null;
}
}
@Override
public boolean isError() {
return exception != null;
}
@Override
public DockerAccessException getException() {
return exception;
}
}
|
src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java
|
package io.fabric8.maven.docker.access.log;/*
*
* Copyright 2014 Roland Huss
*
* 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 java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import io.fabric8.maven.docker.access.DockerAccessException;
import io.fabric8.maven.docker.access.UrlBuilder;
import io.fabric8.maven.docker.access.util.RequestUtil;
import io.fabric8.maven.docker.util.Timestamp;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
/**
* Extractor for parsing the response of a log request
*
* @author roland
* @since 28/11/14
*/
public class LogRequestor extends Thread implements LogGetHandle {
// Patter for matching log entries
static final Pattern LOG_LINE = Pattern.compile("^\\[?(?<timestamp>[^\\s\\]]*)]? (?<entry>.*?)\\s*$", Pattern.DOTALL);
private final CloseableHttpClient client;
private final String containerId;
// callback called for each line extracted
private LogCallback callback;
private DockerAccessException exception;
// Remember for asynchronous handling so that the request can be aborted from the outside
private HttpUriRequest request;
private final UrlBuilder urlBuilder;
// Lock for synchronizing closing of requests
private final Object lock = new Object();
/**
* Create a helper object for requesting log entries synchronously ({@link #fetchLogs()}) or asynchronously ({@link #start()}.
*
* @param client HTTP client to use for requesting the docker host
* @param urlBuilder builder that creates docker urls
* @param containerId container for which to fetch the host
* @param callback callback to call for each line received
*/
public LogRequestor(CloseableHttpClient client, UrlBuilder urlBuilder, String containerId, LogCallback callback) {
this.client = client;
this.containerId = containerId;
this.urlBuilder = urlBuilder;
this.callback = callback;
this.exception = null;
}
/**
* Get logs and feed a callback with the content
*/
public void fetchLogs() {
try {
callback.open();
this.request = getLogRequest(false);
final HttpResponse respone = client.execute(request);
parseResponse(respone);
} catch (LogCallback.DoneException e) {
finish();
} catch (IOException exp) {
callback.error(exp.getMessage());
} finally {
callback.close();
}
}
// Fetch log asynchronously as stream and follow stream
public void run() {
synchronized (lock) {
try {
callback.open();
this.request = getLogRequest(true);
final HttpResponse response = client.execute(request);
parseResponse(response);
} catch (LogCallback.DoneException e) {
finish();
} catch (IOException e) {
callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName());
} finally {
callback.close();
}
}
}
private static class NoBytesReadException extends IOException {
public NoBytesReadException() {
}
}
/**
* This is a copy of ByteStreams.readFully(), with the slight change that it throws
* NoBytesReadException if zero bytes are read. Otherwise it is identical.
*
* @param in
* @param bytes
* @throws IOException
*/
private void readFully(InputStream in, byte[] bytes) throws IOException {
int read = ByteStreams.read(in, bytes, 0, bytes.length);
if (read == 0) {
throw new NoBytesReadException();
} else if (read != bytes.length) {
throw new EOFException("reached end of stream after reading "
+ read + " bytes; " + bytes.length + " bytes expected");
}
}
private boolean readStreamFrame(InputStream is) throws IOException, LogCallback.DoneException {
// Read the header, which is composed of eight bytes. The first byte is an integer
// indicating the stream type (0 = stdin, 1 = stdout, 2 = stderr), the next three are thrown
// out, and the final four are the size of the remaining stream as an integer.
ByteBuffer headerBuffer = ByteBuffer.allocate(8);
headerBuffer.order(ByteOrder.BIG_ENDIAN);
try {
this.readFully(is, headerBuffer.array());
} catch (NoBytesReadException e) {
// Not bytes read for stream. Return false to stop consuming stream.
return false;
} catch (EOFException e) {
throw new IOException("Failed to read log header. Could not read all 8 bytes. " + e.getMessage(), e);
}
// Grab the stream type (stdout, stderr, stdin) from first byte and throw away other 3 bytes.
int type = headerBuffer.get();
// Skip three bytes, then read size from remaining four bytes.
int size = headerBuffer.getInt(4);
// Ignore empty messages and keep reading.
if (size <= 0) {
return true;
}
// Read the actual message
ByteBuffer payload = ByteBuffer.allocate(size);
try {
ByteStreams.readFully(is, payload.array());
} catch (EOFException e) {
throw new IOException("Failed to read log message. Could not read all " + size + " bytes. " + e.getMessage() +
" [ Header: " + Hex.encodeHexString(headerBuffer.array()) + "]", e);
}
String message = Charsets.UTF_8.newDecoder().decode(payload).toString();
callLogCallback(type, message);
return true;
}
private void parseResponse(HttpResponse response) throws LogCallback.DoneException, IOException {
final StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
exception = new DockerAccessException("Error while reading logs (" + status + ")");
throw new LogCallback.DoneException();
}
final InputStream is = response.getEntity().getContent();
try {
while (true) {
if (!readStreamFrame(is)) {
return;
}
}
} finally {
if ((is != null) && (is.available() > 0)) {
is.close();
}
}
}
private void callLogCallback(int type, String txt) throws LogCallback.DoneException {
Matcher matcher = LOG_LINE.matcher(txt);
if (!matcher.matches()) {
callback.error(String.format("Invalid log format for '%s' (expected: \"<timestamp> <txt>\") [%04x %04x]",
txt,(int) (txt.toCharArray())[0],(int) (txt.toCharArray())[1]));
throw new LogCallback.DoneException();
}
Timestamp ts = new Timestamp(matcher.group("timestamp"));
String logTxt = matcher.group("entry");
callback.log(type, ts, logTxt);
}
private HttpUriRequest getLogRequest(boolean follow) {
return RequestUtil.newGet(urlBuilder.containerLogs(containerId, follow));
}
@Override
public void finish() {
synchronized (lock) {
if (request != null) {
request.abort();
request = null;
}
}
}
@Override
public boolean isError() {
return exception != null;
}
@Override
public DockerAccessException getException() {
return exception;
}
}
|
Fix hang waiting on docker log pattern to match - regression introduced in 0.24.0
Apache HTTP Client will drain an http request upon closing the input stream.
In this case we consume the docker logs in 'follow' mode which will cause the docker daemon to never close the connection on its end.
Thus the close() call will block forever.
The main thread is responsible for calling request.abort() will will signal Apache HTTP Client to close the socket on it's end and thus the close() call can unblock.
|
src/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java
|
Fix hang waiting on docker log pattern to match - regression introduced in 0.24.0
|
<ide><path>rc/main/java/io/fabric8/maven/docker/access/log/LogRequestor.java
<ide>
<ide> private final UrlBuilder urlBuilder;
<ide>
<del> // Lock for synchronizing closing of requests
<del> private final Object lock = new Object();
<del>
<ide> /**
<ide> * Create a helper object for requesting log entries synchronously ({@link #fetchLogs()}) or asynchronously ({@link #start()}.
<ide> *
<ide> try {
<ide> callback.open();
<ide> this.request = getLogRequest(false);
<del> final HttpResponse respone = client.execute(request);
<del> parseResponse(respone);
<add> final HttpResponse response = client.execute(request);
<add> parseResponse(response);
<ide> } catch (LogCallback.DoneException e) {
<del> finish();
<add> // Signifies we're finished with the log stream.
<ide> } catch (IOException exp) {
<ide> callback.error(exp.getMessage());
<ide> } finally {
<ide>
<ide> // Fetch log asynchronously as stream and follow stream
<ide> public void run() {
<del> synchronized (lock) {
<del> try {
<del> callback.open();
<del>
<del> this.request = getLogRequest(true);
<del> final HttpResponse response = client.execute(request);
<del> parseResponse(response);
<del> } catch (LogCallback.DoneException e) {
<del> finish();
<del> } catch (IOException e) {
<del> callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName());
<del> } finally {
<del> callback.close();
<del> }
<add> try {
<add> callback.open();
<add> this.request = getLogRequest(true);
<add> final HttpResponse response = client.execute(request);
<add> parseResponse(response);
<add> } catch (LogCallback.DoneException e) {
<add> // Signifies we're finished with the log stream.
<add> } catch (IOException e) {
<add> callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName());
<add> } finally {
<add> callback.close();
<ide> }
<ide> }
<ide>
<ide> throw new LogCallback.DoneException();
<ide> }
<ide>
<del> final InputStream is = response.getEntity().getContent();
<del>
<del> try {
<add> try (InputStream is = response.getEntity().getContent()) {
<ide> while (true) {
<ide> if (!readStreamFrame(is)) {
<ide> return;
<ide> }
<del> }
<del> } finally {
<del> if ((is != null) && (is.available() > 0)) {
<del> is.close();
<ide> }
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void finish() {
<del> synchronized (lock) {
<del> if (request != null) {
<del> request.abort();
<del> request = null;
<del> }
<add> if (request != null) {
<add> request.abort();
<add> request = null;
<ide> }
<ide> }
<ide>
|
|
JavaScript
|
mit
|
3112cbf4652aae25237bdf2897508fd5ec2b26dd
| 0 |
stremlenye/immutable-http
|
const supportedMethods = ['GET', 'POST', 'PUT', 'DELETE']
const validTypes = ['', 'arraybuffer', 'blob', 'document', 'text', 'json']
/**
* Validate HTTP method
* @param {String} method – HTTP method
*/
function validateMethod (method) {
if (!method) {
throw Error(`HTTP method is not specified`)
}
if (typeof method !== 'string') {
throw Error(`HTTP method should be type of string`)
}
if (method in supportedMethods) {
throw Error(`Http method ${method} is not supported`)
}
}
/**
* Basicly validate url
* @param {String} url – URL
*/
function validateUrl (url) {
if (!url) {
throw Error(`Url is not specified`)
}
if (typeof url !== 'string') {
throw Error(`Url should be type of string`)
}
}
/**
* Validate header to all parts be strings
* @param {String} key – Header key
* @param {String} value – Header value
*/
function validateHeader (key, value) {
if (typeof key !== 'string' || typeof value !== 'string')
throw new Error('Headers must be strings')
}
/**
* Validate headers
* @param {Object} headers – headers
*/
function validateHeaders (headers) {
for (let [key, value] of headers.entries()) {
validateHeader(key, value)
}
}
/**
* Validates response type
* @param {string} type - response type
*/
function validateResponseType (type) {
if (type !== null || !(type in validTypes))
throw Error(`Response content type ${type} is not currently supported`)
}
/**
* Validate HTTP request model
* @param {Object} http – Http object
*/
function validate (http) {
validateUrl(http.url)
validateMethod(http.method)
validateHeaders(http.headers)
validateResponseType(http.responseType)
}
export default validate
|
src/validate.js
|
const supportedMethods = ['GET', 'POST', 'PUT', 'DELETE']
const validTypes = ['', 'arraybuffer', 'blob', 'document', 'text', 'json']
/**
* Validate HTTP method
* @param {String} method – HTTP method
*/
function validateMethod (method) {
if (!method) {
throw Error(`HTTP method is not specified`)
}
if (typeof method !== 'string') {
throw Error(`HTTP method should be type of string`)
}
if (method in supportedMethods < 0) {
throw Error(`Http method ${method} is not supported`)
}
}
/**
* Basicly validate url
* @param {String} url – URL
*/
function validateUrl (url) {
if (!url) {
throw Error(`Url is not specified`)
}
if (typeof url !== 'string') {
throw Error(`Url should be type of string`)
}
}
/**
* Validate header to all parts be strings
* @param {String} key – Header key
* @param {String} value – Header value
*/
function validateHeader (key, value) {
if (typeof key !== 'string' || typeof value !== 'string')
throw new Error('Headers must be strings')
}
/**
* Validate headers
* @param {Object} headers – headers
*/
function validateHeaders (headers) {
for (let [key, value] of headers.entries()) {
validateHeader(key, value)
}
}
/**
* Validates response type
* @param {string} type - response type
*/
function validateResponseType (type) {
if (type !== null || !(type in validTypes))
throw Error(`Response content type ${type} is not currently supported`)
}
/**
* Validate HTTP request model
* @param {Object} http – Http object
*/
function validate (http) {
validateUrl(http.url)
validateMethod(http.method)
validateHeaders(http.headers)
validateResponseType(http.responseType)
}
export default validate
|
Fix ckeck
|
src/validate.js
|
Fix ckeck
|
<ide><path>rc/validate.js
<ide> if (typeof method !== 'string') {
<ide> throw Error(`HTTP method should be type of string`)
<ide> }
<del> if (method in supportedMethods < 0) {
<add> if (method in supportedMethods) {
<ide> throw Error(`Http method ${method} is not supported`)
<ide> }
<ide> }
|
|
Java
|
apache-2.0
|
error: pathspec 'AdventOfCode/2019/day17/part2/Function.java' did not match any file(s) known to git
|
c15243ed27b3fa856ae5e484501b901d46ffda43
| 1 |
nmcl/wfswarm-example-arjuna-old,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch,nmcl/scratch
|
import java.util.Objects;
public class Function
{
public Function (String command, int numberOfCommands)
{
_command = command;
_numberOfCommands = numberOfCommands;
}
public String getCommand ()
{
return _command;
}
public int numberOfCommands ()
{
return _numberOfCommands;
}
@Override
public String toString ()
{
return "Command: "+_command;
}
@Override
public int hashCode ()
{
return Objects.hash(_command, _numberOfCommands);
}
@Override
public boolean equals (Object obj)
{
if (obj == null)
return false;
if (this == obj)
return true;
if (getClass() == obj.getClass())
{
Function temp = (Function) obj;
return (_command.equals(temp._command));
}
return false;
}
private String _command;
private int _numberOfCommands;
}
|
AdventOfCode/2019/day17/part2/Function.java
|
Create Function.java
|
AdventOfCode/2019/day17/part2/Function.java
|
Create Function.java
|
<ide><path>dventOfCode/2019/day17/part2/Function.java
<add>import java.util.Objects;
<add>
<add>public class Function
<add>{
<add> public Function (String command, int numberOfCommands)
<add> {
<add> _command = command;
<add> _numberOfCommands = numberOfCommands;
<add> }
<add>
<add> public String getCommand ()
<add> {
<add> return _command;
<add> }
<add>
<add> public int numberOfCommands ()
<add> {
<add> return _numberOfCommands;
<add> }
<add>
<add> @Override
<add> public String toString ()
<add> {
<add> return "Command: "+_command;
<add> }
<add>
<add> @Override
<add> public int hashCode ()
<add> {
<add> return Objects.hash(_command, _numberOfCommands);
<add> }
<add>
<add> @Override
<add> public boolean equals (Object obj)
<add> {
<add> if (obj == null)
<add> return false;
<add>
<add> if (this == obj)
<add> return true;
<add>
<add> if (getClass() == obj.getClass())
<add> {
<add> Function temp = (Function) obj;
<add>
<add> return (_command.equals(temp._command));
<add> }
<add>
<add> return false;
<add> }
<add>
<add> private String _command;
<add> private int _numberOfCommands;
<add>}
|
|
Java
|
apache-2.0
|
82ae6a48e2673e61196907486e7b07a1dda58ade
| 0 |
javiersantos/PiracyChecker,javiersantos/PiracyChecker
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.javiersantos.licensing;
/**
* Policy used by {@link LicenseChecker} to determine whether a user should have access to the
* application.
*/
public interface Policy {
/**
* Change these values to make it more difficult for tools to automatically
* strip LVL protection from your APK.
*/
/**
* LICENSED means that the server returned back a valid license response
*/
int LICENSED = 0x0B8A;
/**
* NOT_LICENSED means that the server returned back a valid license response that indicated that
* the user definitively is not licensed
*/
int NOT_LICENSED = 0x01B3;
/**
* RETRY means that the license response was unable to be determined --- perhaps as a result of
* faulty networking
*/
int RETRY = 0x0C48;
/**
* Provide results from contact with the license server. Retry counts are incremented if the
* current value of response is RETRY. Results will be used for any future policy decisions.
*
* @param response the result from validating the server response
* @param rawData the raw server response data, can be null for RETRY
*/
void processServerResponse(int response, ResponseData rawData);
/**
* Check if the user should be allowed access to the application.
*/
boolean allowAccess();
}
|
library/src/main/java/com/github/javiersantos/licensing/Policy.java
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.javiersantos.licensing;
/**
* Policy used by {@link LicenseChecker} to determine whether a user should have access to the
* application.
*/
public interface Policy {
/**
* Change these values to make it more difficult for tools to automatically
* strip LVL protection from your APK.
*/
/**
* LICENSED means that the server returned back a valid license response
*/
int LICENSED = 0x0100;
/**
* NOT_LICENSED means that the server returned back a valid license response that indicated that
* the user definitively is not licensed
*/
int NOT_LICENSED = 0x0231;
/**
* RETRY means that the license response was unable to be determined --- perhaps as a result of
* faulty networking
*/
int RETRY = 0x0123;
/**
* Provide results from contact with the license server. Retry counts are incremented if the
* current value of response is RETRY. Results will be used for any future policy decisions.
*
* @param response the result from validating the server response
* @param rawData the raw server response data, can be null for RETRY
*/
void processServerResponse(int response, ResponseData rawData);
/**
* Check if the user should be allowed access to the application.
*/
boolean allowAccess();
}
|
Update Policy values
|
library/src/main/java/com/github/javiersantos/licensing/Policy.java
|
Update Policy values
|
<ide><path>ibrary/src/main/java/com/github/javiersantos/licensing/Policy.java
<ide> /**
<ide> * LICENSED means that the server returned back a valid license response
<ide> */
<del> int LICENSED = 0x0100;
<add> int LICENSED = 0x0B8A;
<ide> /**
<ide> * NOT_LICENSED means that the server returned back a valid license response that indicated that
<ide> * the user definitively is not licensed
<ide> */
<del> int NOT_LICENSED = 0x0231;
<add> int NOT_LICENSED = 0x01B3;
<ide> /**
<ide> * RETRY means that the license response was unable to be determined --- perhaps as a result of
<ide> * faulty networking
<ide> */
<del> int RETRY = 0x0123;
<add> int RETRY = 0x0C48;
<ide>
<ide> /**
<ide> * Provide results from contact with the license server. Retry counts are incremented if the
|
|
JavaScript
|
agpl-3.0
|
eb98ba3fd6a806ec062046983a4715f58b92b37c
| 0 |
srsman/odoo,ehirt/odoo,ShineFan/odoo,luiseduardohdbackup/odoo,deKupini/erp,Nick-OpusVL/odoo,waytai/odoo,glovebx/odoo,mvaled/OpenUpgrade,SAM-IT-SA/odoo,Antiun/odoo,oihane/odoo,slevenhagen/odoo-npg,nagyistoce/odoo-dev-odoo,bkirui/odoo,oliverhr/odoo,erkrishna9/odoo,ujjwalwahi/odoo,BT-ojossen/odoo,ChanduERP/odoo,sysadminmatmoz/OCB,dkubiak789/odoo,takis/odoo,sebalix/OpenUpgrade,AuyaJackie/odoo,feroda/odoo,janocat/odoo,glovebx/odoo,bakhtout/odoo-educ,guerrerocarlos/odoo,Codefans-fan/odoo,damdam-s/OpenUpgrade,gorjuce/odoo,MarcosCommunity/odoo,demon-ru/iml-crm,zchking/odoo,juanalfonsopr/odoo,dsfsdgsbngfggb/odoo,ihsanudin/odoo,tangyiyong/odoo,jesramirez/odoo,rubencabrera/odoo,dfang/odoo,rgeleta/odoo,JGarcia-Panach/odoo,rowemoore/odoo,hip-odoo/odoo,collex100/odoo,sve-odoo/odoo,Daniel-CA/odoo,Ernesto99/odoo,hassoon3/odoo,shivam1111/odoo,bwrsandman/OpenUpgrade,agrista/odoo-saas,numerigraphe/odoo,vnsofthe/odoo,dkubiak789/odoo,syci/OCB,realsaiko/odoo,dsfsdgsbngfggb/odoo,fjbatresv/odoo,cysnake4713/odoo,abdellatifkarroum/odoo,hbrunn/OpenUpgrade,Adel-Magebinary/odoo,alexcuellar/odoo,CubicERP/odoo,jfpla/odoo,doomsterinc/odoo,Endika/odoo,0k/OpenUpgrade,tinkhaven-organization/odoo,kirca/OpenUpgrade,florian-dacosta/OpenUpgrade,jusdng/odoo,VielSoft/odoo,slevenhagen/odoo,doomsterinc/odoo,Maspear/odoo,guewen/OpenUpgrade,ygol/odoo,osvalr/odoo,rahuldhote/odoo,nuncjo/odoo,datenbetrieb/odoo,ojengwa/odoo,ApuliaSoftware/odoo,avoinsystems/odoo,elmerdpadilla/iv,diagramsoftware/odoo,alhashash/odoo,poljeff/odoo,synconics/odoo,Ernesto99/odoo,shivam1111/odoo,BT-rmartin/odoo,xujb/odoo,jusdng/odoo,datenbetrieb/odoo,rdeheele/odoo,patmcb/odoo,JonathanStein/odoo,Kilhog/odoo,papouso/odoo,Eric-Zhong/odoo,florentx/OpenUpgrade,datenbetrieb/odoo,fossoult/odoo,waytai/odoo,QianBIG/odoo,luiseduardohdbackup/odoo,naousse/odoo,shaufi/odoo,takis/odoo,elmerdpadilla/iv,synconics/odoo,guewen/OpenUpgrade,thanhacun/odoo,feroda/odoo,CubicERP/odoo,KontorConsulting/odoo,mszewczy/odoo,abstract-open-solutions/OCB,joariasl/odoo,jfpla/odoo,bobisme/odoo,microcom/odoo,brijeshkesariya/odoo,fgesora/odoo,ecosoft-odoo/odoo,diagramsoftware/odoo,RafaelTorrealba/odoo,Noviat/odoo,SAM-IT-SA/odoo,BT-astauder/odoo,SAM-IT-SA/odoo,bobisme/odoo,Ichag/odoo,ramitalat/odoo,fgesora/odoo,pedrobaeza/OpenUpgrade,patmcb/odoo,Kilhog/odoo,tvtsoft/odoo8,mkieszek/odoo,numerigraphe/odoo,csrocha/OpenUpgrade,fuhongliang/odoo,odoousers2014/odoo,ApuliaSoftware/odoo,tarzan0820/odoo,rdeheele/odoo,alexcuellar/odoo,Elico-Corp/odoo_OCB,alhashash/odoo,kybriainfotech/iSocioCRM,juanalfonsopr/odoo,ApuliaSoftware/odoo,cloud9UG/odoo,joshuajan/odoo,cloud9UG/odoo,QianBIG/odoo,tinkerthaler/odoo,jpshort/odoo,alhashash/odoo,chiragjogi/odoo,joariasl/odoo,ujjwalwahi/odoo,CopeX/odoo,funkring/fdoo,hmen89/odoo,gavin-feng/odoo,slevenhagen/odoo,thanhacun/odoo,bobisme/odoo,BT-rmartin/odoo,ChanduERP/odoo,abstract-open-solutions/OCB,markeTIC/OCB,NL66278/OCB,demon-ru/iml-crm,dgzurita/odoo,odoousers2014/odoo,GauravSahu/odoo,ShineFan/odoo,OpenUpgrade/OpenUpgrade,Endika/odoo,nagyistoce/odoo-dev-odoo,stonegithubs/odoo,odoo-turkiye/odoo,FlorianLudwig/odoo,prospwro/odoo,cedk/odoo,avoinsystems/odoo,jeasoft/odoo,slevenhagen/odoo-npg,Adel-Magebinary/odoo,dgzurita/odoo,ramadhane/odoo,pedrobaeza/OpenUpgrade,kirca/OpenUpgrade,dllsf/odootest,lombritz/odoo,hanicker/odoo,Endika/OpenUpgrade,oasiswork/odoo,Grirrane/odoo,nhomar/odoo,hubsaysnuaa/odoo,nuuuboo/odoo,tangyiyong/odoo,cloud9UG/odoo,dezynetechnologies/odoo,abdellatifkarroum/odoo,ShineFan/odoo,ujjwalwahi/odoo,storm-computers/odoo,tinkerthaler/odoo,blaggacao/OpenUpgrade,jolevq/odoopub,factorlibre/OCB,mkieszek/odoo,xzYue/odoo,MarcosCommunity/odoo,glovebx/odoo,Nick-OpusVL/odoo,christophlsa/odoo,odootr/odoo,tarzan0820/odoo,fossoult/odoo,CopeX/odoo,rgeleta/odoo,aviciimaxwell/odoo,bobisme/odoo,sv-dev1/odoo,bealdav/OpenUpgrade,JGarcia-Panach/odoo,dllsf/odootest,mszewczy/odoo,minhtuancn/odoo,rubencabrera/odoo,oihane/odoo,AuyaJackie/odoo,hifly/OpenUpgrade,hassoon3/odoo,Adel-Magebinary/odoo,lightcn/odoo,jeasoft/odoo,sinbazhou/odoo,savoirfairelinux/OpenUpgrade,sysadminmatmoz/OCB,shaufi10/odoo,bealdav/OpenUpgrade,joariasl/odoo,glovebx/odoo,tvibliani/odoo,waytai/odoo,goliveirab/odoo,diagramsoftware/odoo,microcom/odoo,poljeff/odoo,dalegregory/odoo,tvibliani/odoo,wangjun/odoo,luiseduardohdbackup/odoo,csrocha/OpenUpgrade,jesramirez/odoo,hubsaysnuaa/odoo,stephen144/odoo,nuuuboo/odoo,abdellatifkarroum/odoo,fdvarela/odoo8,salaria/odoo,nexiles/odoo,gsmartway/odoo,virgree/odoo,ingadhoc/odoo,cedk/odoo,makinacorpus/odoo,rahuldhote/odoo,luistorresm/odoo,OpenUpgrade-dev/OpenUpgrade,slevenhagen/odoo,BT-astauder/odoo,ingadhoc/odoo,mustafat/odoo-1,inspyration/odoo,brijeshkesariya/odoo,Adel-Magebinary/odoo,feroda/odoo,simongoffin/website_version,patmcb/odoo,apanju/GMIO_Odoo,Kilhog/odoo,VielSoft/odoo,feroda/odoo,funkring/fdoo,wangjun/odoo,takis/odoo,Maspear/odoo,goliveirab/odoo,Nick-OpusVL/odoo,RafaelTorrealba/odoo,mkieszek/odoo,Gitlab11/odoo,pplatek/odoo,shingonoide/odoo,x111ong/odoo,n0m4dz/odoo,fdvarela/odoo8,windedge/odoo,acshan/odoo,lombritz/odoo,storm-computers/odoo,agrista/odoo-saas,wangjun/odoo,fjbatresv/odoo,ThinkOpen-Solutions/odoo,savoirfairelinux/odoo,PongPi/isl-odoo,sv-dev1/odoo,windedge/odoo,ygol/odoo,PongPi/isl-odoo,aviciimaxwell/odoo,havt/odoo,Bachaco-ve/odoo,makinacorpus/odoo,jfpla/odoo,BT-ojossen/odoo,hopeall/odoo,Endika/odoo,OpusVL/odoo,lgscofield/odoo,abstract-open-solutions/OCB,lsinfo/odoo,pedrobaeza/OpenUpgrade,xzYue/odoo,fuselock/odoo,addition-it-solutions/project-all,gvb/odoo,mvaled/OpenUpgrade,bplancher/odoo,mustafat/odoo-1,blaggacao/OpenUpgrade,lightcn/odoo,salaria/odoo,nexiles/odoo,lsinfo/odoo,eino-makitalo/odoo,tarzan0820/odoo,jiachenning/odoo,ShineFan/odoo,collex100/odoo,Nick-OpusVL/odoo,joariasl/odoo,papouso/odoo,bplancher/odoo,nhomar/odoo-mirror,apanju/GMIO_Odoo,kybriainfotech/iSocioCRM,JGarcia-Panach/odoo,bakhtout/odoo-educ,guerrerocarlos/odoo,bplancher/odoo,QianBIG/odoo,Eric-Zhong/odoo,apanju/odoo,Grirrane/odoo,javierTerry/odoo,joshuajan/odoo,alexteodor/odoo,osvalr/odoo,NL66278/OCB,christophlsa/odoo,slevenhagen/odoo-npg,hifly/OpenUpgrade,bealdav/OpenUpgrade,Danisan/odoo-1,ChanduERP/odoo,dsfsdgsbngfggb/odoo,leoliujie/odoo,Gitlab11/odoo,Elico-Corp/odoo_OCB,hmen89/odoo,shingonoide/odoo,ujjwalwahi/odoo,bguillot/OpenUpgrade,incaser/odoo-odoo,Noviat/odoo,Kilhog/odoo,funkring/fdoo,kittiu/odoo,elmerdpadilla/iv,kifcaliph/odoo,omprakasha/odoo,gvb/odoo,abdellatifkarroum/odoo,ShineFan/odoo,rahuldhote/odoo,chiragjogi/odoo,grap/OpenUpgrade,0k/odoo,fgesora/odoo,gavin-feng/odoo,numerigraphe/odoo,ovnicraft/odoo,Ernesto99/odoo,massot/odoo,fossoult/odoo,hifly/OpenUpgrade,incaser/odoo-odoo,hanicker/odoo,Endika/OpenUpgrade,fevxie/odoo,sv-dev1/odoo,mvaled/OpenUpgrade,tarzan0820/odoo,stonegithubs/odoo,shingonoide/odoo,dalegregory/odoo,hoatle/odoo,demon-ru/iml-crm,spadae22/odoo,ojengwa/odoo,Ichag/odoo,mlaitinen/odoo,brijeshkesariya/odoo,prospwro/odoo,chiragjogi/odoo,hubsaysnuaa/odoo,MarcosCommunity/odoo,nexiles/odoo,cpyou/odoo,deKupini/erp,Noviat/odoo,AuyaJackie/odoo,glovebx/odoo,simongoffin/website_version,shaufi/odoo,vnsofthe/odoo,sysadminmatmoz/OCB,sve-odoo/odoo,hanicker/odoo,dgzurita/odoo,osvalr/odoo,kittiu/odoo,Drooids/odoo,Elico-Corp/odoo_OCB,alqfahad/odoo,nhomar/odoo,juanalfonsopr/odoo,oasiswork/odoo,hip-odoo/odoo,Grirrane/odoo,jpshort/odoo,x111ong/odoo,pplatek/odoo,tinkerthaler/odoo,rubencabrera/odoo,gorjuce/odoo,srimai/odoo,ojengwa/odoo,FlorianLudwig/odoo,JGarcia-Panach/odoo,Maspear/odoo,tinkhaven-organization/odoo,cpyou/odoo,pedrobaeza/OpenUpgrade,charbeljc/OCB,prospwro/odoo,christophlsa/odoo,fevxie/odoo,apanju/odoo,lsinfo/odoo,sinbazhou/odoo,CopeX/odoo,lsinfo/odoo,damdam-s/OpenUpgrade,GauravSahu/odoo,cpyou/odoo,OpenUpgrade-dev/OpenUpgrade,steedos/odoo,nexiles/odoo,christophlsa/odoo,JonathanStein/odoo,leoliujie/odoo,javierTerry/odoo,JonathanStein/odoo,kirca/OpenUpgrade,alexcuellar/odoo,ingadhoc/odoo,Noviat/odoo,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,christophlsa/odoo,odoo-turkiye/odoo,tvibliani/odoo,collex100/odoo,ApuliaSoftware/odoo,dalegregory/odoo,damdam-s/OpenUpgrade,stonegithubs/odoo,lombritz/odoo,RafaelTorrealba/odoo,ShineFan/odoo,storm-computers/odoo,storm-computers/odoo,spadae22/odoo,goliveirab/odoo,colinnewell/odoo,markeTIC/OCB,funkring/fdoo,Daniel-CA/odoo,hanicker/odoo,grap/OpenUpgrade,luiseduardohdbackup/odoo,nuuuboo/odoo,idncom/odoo,lgscofield/odoo,odooindia/odoo,PongPi/isl-odoo,goliveirab/odoo,CatsAndDogsbvba/odoo,Codefans-fan/odoo,Nowheresly/odoo,kifcaliph/odoo,SAM-IT-SA/odoo,steedos/odoo,sysadminmatmoz/OCB,jaxkodex/odoo,markeTIC/OCB,incaser/odoo-odoo,funkring/fdoo,alqfahad/odoo,jaxkodex/odoo,florentx/OpenUpgrade,minhtuancn/odoo,SAM-IT-SA/odoo,odoo-turkiye/odoo,steedos/odoo,massot/odoo,sve-odoo/odoo,joshuajan/odoo,fuhongliang/odoo,Antiun/odoo,bkirui/odoo,joshuajan/odoo,TRESCLOUD/odoopub,odooindia/odoo,omprakasha/odoo,oliverhr/odoo,sergio-incaser/odoo,x111ong/odoo,leorochael/odoo,jiangzhixiao/odoo,synconics/odoo,jusdng/odoo,lsinfo/odoo,Ichag/odoo,kirca/OpenUpgrade,janocat/odoo,grap/OpenUpgrade,mmbtba/odoo,srimai/odoo,laslabs/odoo,goliveirab/odoo,sve-odoo/odoo,VielSoft/odoo,storm-computers/odoo,gavin-feng/odoo,abenzbiria/clients_odoo,sergio-incaser/odoo,dfang/odoo,savoirfairelinux/odoo,eino-makitalo/odoo,realsaiko/odoo,rahuldhote/odoo,kifcaliph/odoo,draugiskisprendimai/odoo,xzYue/odoo,bobisme/odoo,BT-fgarbely/odoo,rowemoore/odoo,mustafat/odoo-1,0k/OpenUpgrade,stephen144/odoo,zchking/odoo,virgree/odoo,nitinitprof/odoo,incaser/odoo-odoo,prospwro/odoo,jpshort/odoo,sysadminmatmoz/OCB,markeTIC/OCB,jesramirez/odoo,hubsaysnuaa/odoo,BT-astauder/odoo,Codefans-fan/odoo,Bachaco-ve/odoo,poljeff/odoo,sinbazhou/odoo,nagyistoce/odoo-dev-odoo,klunwebale/odoo,numerigraphe/odoo,ubic135/odoo-design,OpenUpgrade/OpenUpgrade,shingonoide/odoo,slevenhagen/odoo,cdrooom/odoo,dgzurita/odoo,ovnicraft/odoo,jpshort/odoo,idncom/odoo,windedge/odoo,NeovaHealth/odoo,dfang/odoo,Nick-OpusVL/odoo,Drooids/odoo,hip-odoo/odoo,apocalypsebg/odoo,gsmartway/odoo,Noviat/odoo,arthru/OpenUpgrade,odoousers2014/odoo,arthru/OpenUpgrade,zchking/odoo,syci/OCB,lgscofield/odoo,SAM-IT-SA/odoo,provaleks/o8,ehirt/odoo,dkubiak789/odoo,guewen/OpenUpgrade,KontorConsulting/odoo,BT-fgarbely/odoo,avoinsystems/odoo,NL66278/OCB,nuuuboo/odoo,acshan/odoo,alexcuellar/odoo,GauravSahu/odoo,markeTIC/OCB,ramitalat/odoo,jiangzhixiao/odoo,gorjuce/odoo,oihane/odoo,andreparames/odoo,steedos/odoo,factorlibre/OCB,microcom/odoo,MarcosCommunity/odoo,spadae22/odoo,mszewczy/odoo,grap/OpenUpgrade,abenzbiria/clients_odoo,gsmartway/odoo,nitinitprof/odoo,mmbtba/odoo,fuselock/odoo,elmerdpadilla/iv,brijeshkesariya/odoo,CatsAndDogsbvba/odoo,chiragjogi/odoo,Eric-Zhong/odoo,draugiskisprendimai/odoo,Endika/OpenUpgrade,hubsaysnuaa/odoo,kybriainfotech/iSocioCRM,Gitlab11/odoo,Endika/OpenUpgrade,ingadhoc/odoo,doomsterinc/odoo,mszewczy/odoo,cloud9UG/odoo,ujjwalwahi/odoo,0k/odoo,ygol/odoo,bguillot/OpenUpgrade,spadae22/odoo,ecosoft-odoo/odoo,numerigraphe/odoo,Bachaco-ve/odoo,Bachaco-ve/odoo,janocat/odoo,CatsAndDogsbvba/odoo,ClearCorp-dev/odoo,shivam1111/odoo,Nowheresly/odoo,simongoffin/website_version,lgscofield/odoo,luiseduardohdbackup/odoo,Drooids/odoo,erkrishna9/odoo,laslabs/odoo,luistorresm/odoo,jiachenning/odoo,Codefans-fan/odoo,ihsanudin/odoo,joariasl/odoo,fevxie/odoo,jusdng/odoo,janocat/odoo,jiachenning/odoo,leoliujie/odoo,osvalr/odoo,agrista/odoo-saas,kybriainfotech/iSocioCRM,kybriainfotech/iSocioCRM,gsmartway/odoo,tangyiyong/odoo,bakhtout/odoo-educ,lombritz/odoo,kittiu/odoo,Ichag/odoo,mszewczy/odoo,deKupini/erp,hoatle/odoo,apanju/GMIO_Odoo,sve-odoo/odoo,prospwro/odoo,hubsaysnuaa/odoo,idncom/odoo,incaser/odoo-odoo,BT-fgarbely/odoo,jaxkodex/odoo,provaleks/o8,provaleks/o8,RafaelTorrealba/odoo,optima-ict/odoo,klunwebale/odoo,kifcaliph/odoo,klunwebale/odoo,ramadhane/odoo,Maspear/odoo,jpshort/odoo,alqfahad/odoo,agrista/odoo-saas,windedge/odoo,srsman/odoo,ojengwa/odoo,abstract-open-solutions/OCB,apanju/GMIO_Odoo,JGarcia-Panach/odoo,apocalypsebg/odoo,elmerdpadilla/iv,fgesora/odoo,addition-it-solutions/project-all,Ernesto99/odoo,jolevq/odoopub,BT-astauder/odoo,hip-odoo/odoo,ecosoft-odoo/odoo,0k/OpenUpgrade,lombritz/odoo,apanju/odoo,wangjun/odoo,highco-groupe/odoo,abstract-open-solutions/OCB,TRESCLOUD/odoopub,mvaled/OpenUpgrade,doomsterinc/odoo,nexiles/odoo,florian-dacosta/OpenUpgrade,rahuldhote/odoo,windedge/odoo,jeasoft/odoo,dfang/odoo,bkirui/odoo,ramadhane/odoo,joariasl/odoo,wangjun/odoo,ojengwa/odoo,ojengwa/odoo,jfpla/odoo,0k/odoo,colinnewell/odoo,jiangzhixiao/odoo,lsinfo/odoo,mlaitinen/odoo,0k/OpenUpgrade,makinacorpus/odoo,makinacorpus/odoo,Ichag/odoo,ihsanudin/odoo,ingadhoc/odoo,FlorianLudwig/odoo,cysnake4713/odoo,rubencabrera/odoo,acshan/odoo,sergio-incaser/odoo,n0m4dz/odoo,fjbatresv/odoo,acshan/odoo,SerpentCS/odoo,rowemoore/odoo,cysnake4713/odoo,tinkhaven-organization/odoo,waytai/odoo,ecosoft-odoo/odoo,JGarcia-Panach/odoo,naousse/odoo,feroda/odoo,Endika/odoo,slevenhagen/odoo,apanju/GMIO_Odoo,lightcn/odoo,abstract-open-solutions/OCB,jolevq/odoopub,Codefans-fan/odoo,kittiu/odoo,tvibliani/odoo,prospwro/odoo,ubic135/odoo-design,OpenUpgrade-dev/OpenUpgrade,windedge/odoo,fevxie/odoo,minhtuancn/odoo,takis/odoo,alqfahad/odoo,ujjwalwahi/odoo,dllsf/odootest,goliveirab/odoo,ubic135/odoo-design,ramadhane/odoo,JonathanStein/odoo,apanju/GMIO_Odoo,pplatek/odoo,funkring/fdoo,florian-dacosta/OpenUpgrade,syci/OCB,jeasoft/odoo,apocalypsebg/odoo,Ernesto99/odoo,hopeall/odoo,avoinsystems/odoo,guerrerocarlos/odoo,spadae22/odoo,GauravSahu/odoo,nuncjo/odoo,Nick-OpusVL/odoo,jusdng/odoo,hopeall/odoo,laslabs/odoo,apanju/odoo,syci/OCB,CopeX/odoo,provaleks/o8,OpusVL/odoo,Ichag/odoo,SerpentCS/odoo,florian-dacosta/OpenUpgrade,srsman/odoo,alhashash/odoo,dezynetechnologies/odoo,zchking/odoo,tinkerthaler/odoo,sv-dev1/odoo,ChanduERP/odoo,Ernesto99/odoo,doomsterinc/odoo,rowemoore/odoo,SAM-IT-SA/odoo,odootr/odoo,leoliujie/odoo,ingadhoc/odoo,OpenUpgrade-dev/OpenUpgrade,RafaelTorrealba/odoo,Drooids/odoo,stephen144/odoo,steedos/odoo,kirca/OpenUpgrade,dariemp/odoo,ihsanudin/odoo,klunwebale/odoo,datenbetrieb/odoo,alexteodor/odoo,SerpentCS/odoo,CubicERP/odoo,odoo-turkiye/odoo,tangyiyong/odoo,PongPi/isl-odoo,jusdng/odoo,mlaitinen/odoo,Elico-Corp/odoo_OCB,javierTerry/odoo,storm-computers/odoo,nhomar/odoo,fgesora/odoo,damdam-s/OpenUpgrade,tinkhaven-organization/odoo,JCA-Developpement/Odoo,sebalix/OpenUpgrade,ramadhane/odoo,odoo-turkiye/odoo,collex100/odoo,salaria/odoo,sysadminmatmoz/OCB,draugiskisprendimai/odoo,savoirfairelinux/OpenUpgrade,guerrerocarlos/odoo,Noviat/odoo,bakhtout/odoo-educ,florentx/OpenUpgrade,Adel-Magebinary/odoo,deKupini/erp,tvibliani/odoo,ccomb/OpenUpgrade,ihsanudin/odoo,JCA-Developpement/Odoo,apanju/GMIO_Odoo,RafaelTorrealba/odoo,datenbetrieb/odoo,AuyaJackie/odoo,ramitalat/odoo,BT-fgarbely/odoo,doomsterinc/odoo,odoo-turkiye/odoo,bplancher/odoo,mkieszek/odoo,ThinkOpen-Solutions/odoo,ehirt/odoo,collex100/odoo,kybriainfotech/iSocioCRM,ccomb/OpenUpgrade,gvb/odoo,tvtsoft/odoo8,erkrishna9/odoo,shivam1111/odoo,janocat/odoo,BT-fgarbely/odoo,jiachenning/odoo,sadleader/odoo,gsmartway/odoo,fuselock/odoo,shaufi10/odoo,savoirfairelinux/OpenUpgrade,jfpla/odoo,christophlsa/odoo,luistorresm/odoo,cdrooom/odoo,factorlibre/OCB,javierTerry/odoo,n0m4dz/odoo,colinnewell/odoo,blaggacao/OpenUpgrade,ehirt/odoo,poljeff/odoo,cysnake4713/odoo,omprakasha/odoo,fevxie/odoo,fdvarela/odoo8,inspyration/odoo,JGarcia-Panach/odoo,eino-makitalo/odoo,simongoffin/website_version,ygol/odoo,andreparames/odoo,mmbtba/odoo,charbeljc/OCB,hanicker/odoo,bguillot/OpenUpgrade,odoousers2014/odoo,n0m4dz/odoo,fjbatresv/odoo,BT-rmartin/odoo,prospwro/odoo,guerrerocarlos/odoo,gavin-feng/odoo,alhashash/odoo,hopeall/odoo,leorochael/odoo,Endika/odoo,cysnake4713/odoo,feroda/odoo,addition-it-solutions/project-all,goliveirab/odoo,NeovaHealth/odoo,provaleks/o8,x111ong/odoo,gvb/odoo,hopeall/odoo,luistorresm/odoo,jaxkodex/odoo,ygol/odoo,abenzbiria/clients_odoo,CubicERP/odoo,hanicker/odoo,aviciimaxwell/odoo,SerpentCS/odoo,NeovaHealth/odoo,lightcn/odoo,realsaiko/odoo,shaufi10/odoo,klunwebale/odoo,erkrishna9/odoo,lgscofield/odoo,odooindia/odoo,NeovaHealth/odoo,shaufi10/odoo,CopeX/odoo,erkrishna9/odoo,tinkhaven-organization/odoo,slevenhagen/odoo-npg,bkirui/odoo,naousse/odoo,dgzurita/odoo,BT-ojossen/odoo,fdvarela/odoo8,rubencabrera/odoo,FlorianLudwig/odoo,srsman/odoo,sebalix/OpenUpgrade,srsman/odoo,SerpentCS/odoo,damdam-s/OpenUpgrade,naousse/odoo,rgeleta/odoo,minhtuancn/odoo,glovebx/odoo,jaxkodex/odoo,realsaiko/odoo,nitinitprof/odoo,tvtsoft/odoo8,nhomar/odoo-mirror,gvb/odoo,RafaelTorrealba/odoo,nexiles/odoo,leorochael/odoo,havt/odoo,provaleks/o8,Endika/OpenUpgrade,tinkerthaler/odoo,ehirt/odoo,eino-makitalo/odoo,bwrsandman/OpenUpgrade,bkirui/odoo,dariemp/odoo,srimai/odoo,SerpentCS/odoo,CopeX/odoo,fossoult/odoo,gavin-feng/odoo,vnsofthe/odoo,mlaitinen/odoo,Maspear/odoo,naousse/odoo,acshan/odoo,shivam1111/odoo,alexcuellar/odoo,ApuliaSoftware/odoo,apocalypsebg/odoo,hoatle/odoo,hassoon3/odoo,ecosoft-odoo/odoo,odooindia/odoo,Grirrane/odoo,QianBIG/odoo,Endika/OpenUpgrade,ClearCorp-dev/odoo,leoliujie/odoo,laslabs/odoo,BT-ojossen/odoo,optima-ict/odoo,tangyiyong/odoo,dariemp/odoo,fevxie/odoo,hip-odoo/odoo,dalegregory/odoo,CatsAndDogsbvba/odoo,Kilhog/odoo,savoirfairelinux/OpenUpgrade,aviciimaxwell/odoo,avoinsystems/odoo,highco-groupe/odoo,gavin-feng/odoo,optima-ict/odoo,tvibliani/odoo,omprakasha/odoo,virgree/odoo,thanhacun/odoo,fuhongliang/odoo,lombritz/odoo,charbeljc/OCB,Eric-Zhong/odoo,sergio-incaser/odoo,slevenhagen/odoo,hbrunn/OpenUpgrade,mlaitinen/odoo,avoinsystems/odoo,GauravSahu/odoo,guewen/OpenUpgrade,thanhacun/odoo,hmen89/odoo,papouso/odoo,NeovaHealth/odoo,patmcb/odoo,luistorresm/odoo,blaggacao/OpenUpgrade,Daniel-CA/odoo,havt/odoo,dezynetechnologies/odoo,AuyaJackie/odoo,gvb/odoo,csrocha/OpenUpgrade,oliverhr/odoo,jiangzhixiao/odoo,NL66278/OCB,rgeleta/odoo,dezynetechnologies/odoo,tarzan0820/odoo,OpenUpgrade/OpenUpgrade,NL66278/OCB,fuhongliang/odoo,virgree/odoo,odootr/odoo,apanju/odoo,jiachenning/odoo,blaggacao/OpenUpgrade,shaufi/odoo,microcom/odoo,fuselock/odoo,mmbtba/odoo,cloud9UG/odoo,tinkhaven-organization/odoo,xzYue/odoo,microcom/odoo,tvtsoft/odoo8,FlorianLudwig/odoo,Drooids/odoo,zchking/odoo,colinnewell/odoo,makinacorpus/odoo,cdrooom/odoo,rdeheele/odoo,demon-ru/iml-crm,wangjun/odoo,Maspear/odoo,inspyration/odoo,sv-dev1/odoo,GauravSahu/odoo,bguillot/OpenUpgrade,tinkerthaler/odoo,arthru/OpenUpgrade,alexteodor/odoo,Bachaco-ve/odoo,osvalr/odoo,mszewczy/odoo,nagyistoce/odoo-dev-odoo,Danisan/odoo-1,kittiu/odoo,fgesora/odoo,srimai/odoo,Gitlab11/odoo,javierTerry/odoo,sadleader/odoo,alexcuellar/odoo,matrixise/odoo,kifcaliph/odoo,matrixise/odoo,windedge/odoo,vnsofthe/odoo,mszewczy/odoo,highco-groupe/odoo,jiachenning/odoo,tarzan0820/odoo,oihane/odoo,minhtuancn/odoo,ramitalat/odoo,gavin-feng/odoo,salaria/odoo,hubsaysnuaa/odoo,abdellatifkarroum/odoo,savoirfairelinux/odoo,xujb/odoo,Eric-Zhong/odoo,jolevq/odoopub,klunwebale/odoo,blaggacao/OpenUpgrade,kirca/OpenUpgrade,x111ong/odoo,grap/OpenUpgrade,Antiun/odoo,draugiskisprendimai/odoo,diagramsoftware/odoo,idncom/odoo,shaufi10/odoo,jusdng/odoo,ShineFan/odoo,n0m4dz/odoo,xujb/odoo,BT-ojossen/odoo,nuncjo/odoo,CopeX/odoo,VielSoft/odoo,nexiles/odoo,shaufi/odoo,CubicERP/odoo,nhomar/odoo,charbeljc/OCB,xzYue/odoo,steedos/odoo,dalegregory/odoo,javierTerry/odoo,JonathanStein/odoo,Nowheresly/odoo,minhtuancn/odoo,ehirt/odoo,chiragjogi/odoo,christophlsa/odoo,dkubiak789/odoo,gorjuce/odoo,csrocha/OpenUpgrade,mkieszek/odoo,draugiskisprendimai/odoo,spadae22/odoo,bwrsandman/OpenUpgrade,damdam-s/OpenUpgrade,matrixise/odoo,vnsofthe/odoo,juanalfonsopr/odoo,tvibliani/odoo,cedk/odoo,pplatek/odoo,odootr/odoo,bwrsandman/OpenUpgrade,Eric-Zhong/odoo,ChanduERP/odoo,microcom/odoo,Nowheresly/odoo,sebalix/OpenUpgrade,takis/odoo,tangyiyong/odoo,numerigraphe/odoo,ygol/odoo,patmcb/odoo,dariemp/odoo,papouso/odoo,xujb/odoo,ThinkOpen-Solutions/odoo,arthru/OpenUpgrade,dgzurita/odoo,dkubiak789/odoo,idncom/odoo,CubicERP/odoo,odootr/odoo,leoliujie/odoo,xujb/odoo,synconics/odoo,Noviat/odoo,lightcn/odoo,oasiswork/odoo,MarcosCommunity/odoo,ujjwalwahi/odoo,stonegithubs/odoo,klunwebale/odoo,SerpentCS/odoo,rubencabrera/odoo,takis/odoo,CatsAndDogsbvba/odoo,VielSoft/odoo,markeTIC/OCB,gorjuce/odoo,joshuajan/odoo,jiangzhixiao/odoo,lightcn/odoo,eino-makitalo/odoo,nhomar/odoo-mirror,n0m4dz/odoo,factorlibre/OCB,BT-rmartin/odoo,savoirfairelinux/odoo,bguillot/OpenUpgrade,JonathanStein/odoo,fossoult/odoo,rgeleta/odoo,fuselock/odoo,oihane/odoo,Ernesto99/odoo,havt/odoo,apocalypsebg/odoo,Antiun/odoo,bakhtout/odoo-educ,csrocha/OpenUpgrade,nuuuboo/odoo,fossoult/odoo,KontorConsulting/odoo,sv-dev1/odoo,charbeljc/OCB,waytai/odoo,apocalypsebg/odoo,Grirrane/odoo,jfpla/odoo,jfpla/odoo,dariemp/odoo,Danisan/odoo-1,kittiu/odoo,omprakasha/odoo,dsfsdgsbngfggb/odoo,factorlibre/OCB,omprakasha/odoo,rahuldhote/odoo,GauravSahu/odoo,charbeljc/OCB,sinbazhou/odoo,inspyration/odoo,apanju/odoo,andreparames/odoo,chiragjogi/odoo,fuselock/odoo,sysadminmatmoz/OCB,nuncjo/odoo,abenzbiria/clients_odoo,shaufi/odoo,havt/odoo,AuyaJackie/odoo,ecosoft-odoo/odoo,addition-it-solutions/project-all,cpyou/odoo,grap/OpenUpgrade,nitinitprof/odoo,steedos/odoo,hassoon3/odoo,BT-fgarbely/odoo,x111ong/odoo,janocat/odoo,KontorConsulting/odoo,luistorresm/odoo,colinnewell/odoo,sadleader/odoo,ovnicraft/odoo,Eric-Zhong/odoo,poljeff/odoo,sv-dev1/odoo,rahuldhote/odoo,factorlibre/OCB,zchking/odoo,rowemoore/odoo,shaufi/odoo,TRESCLOUD/odoopub,datenbetrieb/odoo,hbrunn/OpenUpgrade,MarcosCommunity/odoo,thanhacun/odoo,ygol/odoo,cedk/odoo,draugiskisprendimai/odoo,slevenhagen/odoo,Bachaco-ve/odoo,fevxie/odoo,cloud9UG/odoo,thanhacun/odoo,papouso/odoo,tarzan0820/odoo,bobisme/odoo,bakhtout/odoo-educ,salaria/odoo,pedrobaeza/odoo,MarcosCommunity/odoo,OpenUpgrade/OpenUpgrade,KontorConsulting/odoo,grap/OpenUpgrade,acshan/odoo,oihane/odoo,chiragjogi/odoo,lsinfo/odoo,NeovaHealth/odoo,cedk/odoo,waytai/odoo,pplatek/odoo,oasiswork/odoo,OpenUpgrade-dev/OpenUpgrade,spadae22/odoo,makinacorpus/odoo,nuncjo/odoo,dalegregory/odoo,andreparames/odoo,incaser/odoo-odoo,OpusVL/odoo,idncom/odoo,leorochael/odoo,ramitalat/odoo,0k/odoo,OpusVL/odoo,stonegithubs/odoo,odoousers2014/odoo,fjbatresv/odoo,dllsf/odootest,guewen/OpenUpgrade,Adel-Magebinary/odoo,pedrobaeza/odoo,hopeall/odoo,fossoult/odoo,PongPi/isl-odoo,feroda/odoo,KontorConsulting/odoo,sadleader/odoo,nagyistoce/odoo-dev-odoo,hoatle/odoo,virgree/odoo,bakhtout/odoo-educ,dezynetechnologies/odoo,Drooids/odoo,alqfahad/odoo,diagramsoftware/odoo,oasiswork/odoo,addition-it-solutions/project-all,pedrobaeza/odoo,omprakasha/odoo,slevenhagen/odoo-npg,sergio-incaser/odoo,rubencabrera/odoo,dsfsdgsbngfggb/odoo,gsmartway/odoo,hifly/OpenUpgrade,lgscofield/odoo,abstract-open-solutions/OCB,apocalypsebg/odoo,Codefans-fan/odoo,cedk/odoo,ecosoft-odoo/odoo,savoirfairelinux/odoo,savoirfairelinux/OpenUpgrade,luiseduardohdbackup/odoo,x111ong/odoo,alexteodor/odoo,leorochael/odoo,mustafat/odoo-1,takis/odoo,JCA-Developpement/Odoo,ThinkOpen-Solutions/odoo,odoousers2014/odoo,hoatle/odoo,aviciimaxwell/odoo,gsmartway/odoo,acshan/odoo,optima-ict/odoo,diagramsoftware/odoo,nitinitprof/odoo,hifly/OpenUpgrade,highco-groupe/odoo,fgesora/odoo,brijeshkesariya/odoo,bealdav/OpenUpgrade,fuhongliang/odoo,vnsofthe/odoo,markeTIC/OCB,mmbtba/odoo,ramitalat/odoo,fuhongliang/odoo,bealdav/OpenUpgrade,sinbazhou/odoo,minhtuancn/odoo,dsfsdgsbngfggb/odoo,n0m4dz/odoo,OpenUpgrade/OpenUpgrade,deKupini/erp,dfang/odoo,datenbetrieb/odoo,realsaiko/odoo,Danisan/odoo-1,ccomb/OpenUpgrade,dariemp/odoo,ThinkOpen-Solutions/odoo,nuncjo/odoo,wangjun/odoo,alexteodor/odoo,oihane/odoo,ubic135/odoo-design,rgeleta/odoo,shingonoide/odoo,guewen/OpenUpgrade,QianBIG/odoo,ovnicraft/odoo,florian-dacosta/OpenUpgrade,nuuuboo/odoo,abdellatifkarroum/odoo,oasiswork/odoo,BT-ojossen/odoo,csrocha/OpenUpgrade,nhomar/odoo,jiangzhixiao/odoo,highco-groupe/odoo,alqfahad/odoo,dalegregory/odoo,ccomb/OpenUpgrade,florentx/OpenUpgrade,shaufi/odoo,pplatek/odoo,juanalfonsopr/odoo,optima-ict/odoo,doomsterinc/odoo,rdeheele/odoo,leorochael/odoo,massot/odoo,demon-ru/iml-crm,synconics/odoo,nitinitprof/odoo,ramadhane/odoo,arthru/OpenUpgrade,Daniel-CA/odoo,CatsAndDogsbvba/odoo,JCA-Developpement/Odoo,glovebx/odoo,naousse/odoo,rowemoore/odoo,xujb/odoo,leoliujie/odoo,Danisan/odoo-1,tvtsoft/odoo8,shivam1111/odoo,BT-astauder/odoo,ramadhane/odoo,jeasoft/odoo,jeasoft/odoo,hoatle/odoo,KontorConsulting/odoo,patmcb/odoo,collex100/odoo,addition-it-solutions/project-all,Daniel-CA/odoo,havt/odoo,guewen/OpenUpgrade,jesramirez/odoo,brijeshkesariya/odoo,vnsofthe/odoo,salaria/odoo,bkirui/odoo,Nick-OpusVL/odoo,aviciimaxwell/odoo,arthru/OpenUpgrade,salaria/odoo,mlaitinen/odoo,hopeall/odoo,odootr/odoo,ccomb/OpenUpgrade,Nowheresly/odoo,brijeshkesariya/odoo,bwrsandman/OpenUpgrade,oliverhr/odoo,dkubiak789/odoo,colinnewell/odoo,alhashash/odoo,jiangzhixiao/odoo,luiseduardohdbackup/odoo,pedrobaeza/OpenUpgrade,tinkerthaler/odoo,pedrobaeza/odoo,gorjuce/odoo,hanicker/odoo,alqfahad/odoo,kybriainfotech/iSocioCRM,Codefans-fan/odoo,lgscofield/odoo,nitinitprof/odoo,lightcn/odoo,ThinkOpen-Solutions/odoo,Gitlab11/odoo,virgree/odoo,massot/odoo,srimai/odoo,ehirt/odoo,tvtsoft/odoo8,TRESCLOUD/odoopub,factorlibre/OCB,leorochael/odoo,florian-dacosta/OpenUpgrade,juanalfonsopr/odoo,hifly/OpenUpgrade,jaxkodex/odoo,jpshort/odoo,Nowheresly/odoo,hip-odoo/odoo,savoirfairelinux/odoo,dfang/odoo,ThinkOpen-Solutions/odoo,ClearCorp-dev/odoo,PongPi/isl-odoo,ingadhoc/odoo,Gitlab11/odoo,0k/odoo,dezynetechnologies/odoo,blaggacao/OpenUpgrade,cpyou/odoo,mlaitinen/odoo,bealdav/OpenUpgrade,AuyaJackie/odoo,oliverhr/odoo,eino-makitalo/odoo,Endika/OpenUpgrade,joshuajan/odoo,mustafat/odoo-1,dsfsdgsbngfggb/odoo,nhomar/odoo-mirror,guerrerocarlos/odoo,andreparames/odoo,janocat/odoo,ovnicraft/odoo,optima-ict/odoo,synconics/odoo,florentx/OpenUpgrade,Nowheresly/odoo,PongPi/isl-odoo,BT-rmartin/odoo,jeasoft/odoo,cloud9UG/odoo,mustafat/odoo-1,OpenUpgrade/OpenUpgrade,hoatle/odoo,hbrunn/OpenUpgrade,florentx/OpenUpgrade,0k/OpenUpgrade,JonathanStein/odoo,poljeff/odoo,fjbatresv/odoo,andreparames/odoo,thanhacun/odoo,Antiun/odoo,hassoon3/odoo,juanalfonsopr/odoo,BT-rmartin/odoo,mvaled/OpenUpgrade,srimai/odoo,Bachaco-ve/odoo,BT-fgarbely/odoo,pedrobaeza/odoo,xzYue/odoo,Danisan/odoo-1,Maspear/odoo,bwrsandman/OpenUpgrade,VielSoft/odoo,shingonoide/odoo,sinbazhou/odoo,pedrobaeza/OpenUpgrade,tangyiyong/odoo,sebalix/OpenUpgrade,FlorianLudwig/odoo,dezynetechnologies/odoo,ChanduERP/odoo,kirca/OpenUpgrade,osvalr/odoo,hbrunn/OpenUpgrade,cedk/odoo,agrista/odoo-saas,ClearCorp-dev/odoo,guerrerocarlos/odoo,ccomb/OpenUpgrade,jesramirez/odoo,gvb/odoo,makinacorpus/odoo,dkubiak789/odoo,ClearCorp-dev/odoo,charbeljc/OCB,Daniel-CA/odoo,srsman/odoo,nuncjo/odoo,TRESCLOUD/odoopub,eino-makitalo/odoo,ovnicraft/odoo,pplatek/odoo,virgree/odoo,numerigraphe/odoo,jeasoft/odoo,fuselock/odoo,VielSoft/odoo,ovnicraft/odoo,mmbtba/odoo,stonegithubs/odoo,ccomb/OpenUpgrade,aviciimaxwell/odoo,Daniel-CA/odoo,mmbtba/odoo,savoirfairelinux/OpenUpgrade,Adel-Magebinary/odoo,hassoon3/odoo,xzYue/odoo,incaser/odoo-odoo,oliverhr/odoo,JCA-Developpement/Odoo,diagramsoftware/odoo,hmen89/odoo,rowemoore/odoo,BT-rmartin/odoo,nuuuboo/odoo,lombritz/odoo,waytai/odoo,bkirui/odoo,abdellatifkarroum/odoo,avoinsystems/odoo,nhomar/odoo,sadleader/odoo,Endika/odoo,luistorresm/odoo,simongoffin/website_version,Danisan/odoo-1,gorjuce/odoo,0k/OpenUpgrade,ojengwa/odoo,osvalr/odoo,srimai/odoo,funkring/fdoo,Grirrane/odoo,jpshort/odoo,dgzurita/odoo,MarcosCommunity/odoo,dariemp/odoo,pedrobaeza/odoo,syci/OCB,patmcb/odoo,tinkhaven-organization/odoo,papouso/odoo,CubicERP/odoo,fdvarela/odoo8,massot/odoo,Elico-Corp/odoo_OCB,idncom/odoo,oliverhr/odoo,apanju/odoo,nagyistoce/odoo-dev-odoo,ihsanudin/odoo,abenzbiria/clients_odoo,draugiskisprendimai/odoo,jaxkodex/odoo,stephen144/odoo,matrixise/odoo,synconics/odoo,bplancher/odoo,bguillot/OpenUpgrade,stephen144/odoo,stonegithubs/odoo,Ichag/odoo,CatsAndDogsbvba/odoo,Elico-Corp/odoo_OCB,shaufi10/odoo,Antiun/odoo,Kilhog/odoo,ApuliaSoftware/odoo,Kilhog/odoo,bobisme/odoo,odootr/odoo,slevenhagen/odoo-npg,bplancher/odoo,stephen144/odoo,poljeff/odoo,collex100/odoo,fuhongliang/odoo,bguillot/OpenUpgrade,zchking/odoo,colinnewell/odoo,laslabs/odoo,sebalix/OpenUpgrade,nhomar/odoo-mirror,mustafat/odoo-1,BT-ojossen/odoo,laslabs/odoo,rgeleta/odoo,jolevq/odoopub,syci/OCB,hmen89/odoo,provaleks/o8,rdeheele/odoo,sergio-incaser/odoo,ChanduERP/odoo,QianBIG/odoo,fjbatresv/odoo,alexcuellar/odoo,csrocha/OpenUpgrade,papouso/odoo,dllsf/odootest,oasiswork/odoo,naousse/odoo,Drooids/odoo,NeovaHealth/odoo,hbrunn/OpenUpgrade,shivam1111/odoo,andreparames/odoo,joariasl/odoo,OpenUpgrade-dev/OpenUpgrade,sinbazhou/odoo,Endika/odoo,xujb/odoo,shaufi10/odoo,havt/odoo,ApuliaSoftware/odoo,javierTerry/odoo,sebalix/OpenUpgrade,mkieszek/odoo,cdrooom/odoo,mvaled/OpenUpgrade,matrixise/odoo,srsman/odoo,OpenUpgrade/OpenUpgrade,odooindia/odoo,bwrsandman/OpenUpgrade,odoo-turkiye/odoo,kittiu/odoo,mvaled/OpenUpgrade,hifly/OpenUpgrade,slevenhagen/odoo-npg,shingonoide/odoo,Gitlab11/odoo,ihsanudin/odoo,Antiun/odoo,FlorianLudwig/odoo,nagyistoce/odoo-dev-odoo,ubic135/odoo-design
|
(function() {
var instance = openerp;
openerp.web.list = {};
var _t = instance.web._t,
_lt = instance.web._lt;
var QWeb = instance.web.qweb;
instance.web.views.add('list', 'instance.web.ListView');
instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
_template: 'ListView',
display_name: _lt('List'),
defaults: {
// records can be selected one by one
'selectable': true,
// list rows can be deleted
'deletable': false,
// whether the column headers should be displayed
'header': true,
// display addition button, with that label
'addable': _lt("Create"),
// whether the list view can be sorted, note that once a view has been
// sorted it can not be reordered anymore
'sortable': true,
// whether the view rows can be reordered (via vertical drag & drop)
'reorderable': true,
'action_buttons': true,
//whether the editable property of the view has to be disabled
'disable_editable_mode': false,
},
view_type: 'tree',
events: {
'click thead th.oe_sortable[data-id]': 'sort_by_column'
},
/**
* Core class for list-type displays.
*
* As a view, needs a number of view-related parameters to be correctly
* instantiated, provides options and overridable methods for behavioral
* customization.
*
* See constructor parameters and method documentations for information on
* the default behaviors and possible options for the list view.
*
* @constructs instance.web.ListView
* @extends instance.web.View
*
* @param parent parent object
* @param {instance.web.DataSet} dataset the dataset the view should work with
* @param {String} view_id the listview's identifier, if any
* @param {Object} options A set of options used to configure the view
* @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
* @param {Boolean} [options.header=true] should the list's header be displayed
* @param {Boolean} [options.deletable=true] are the list rows deletable
* @param {void|String} [options.addable="New"] should the new-record button be displayed, and what should its label be. Use ``null`` to hide the button.
* @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
* @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
*/
init: function(parent, dataset, view_id, options) {
var self = this;
this._super(parent);
this.set_default_options(_.extend({}, this.defaults, options || {}));
this.dataset = dataset;
this.model = dataset.model;
this.view_id = view_id;
this.previous_colspan = null;
this.colors = null;
this.fonts = null;
this.columns = [];
this.records = new Collection();
this.set_groups(new (this.options.GroupsType)(this));
if (this.dataset instanceof instance.web.DataSetStatic) {
this.groups.datagroup = new StaticDataGroup(this.dataset);
} else {
this.groups.datagroup = new DataGroup(
this, this.model,
dataset.get_domain(),
dataset.get_context());
this.groups.datagroup.sort = this.dataset._sort;
}
this.page = 0;
this.records.bind('change', function (event, record, key) {
if (!_(self.aggregate_columns).chain()
.pluck('name').contains(key).value()) {
return;
}
self.compute_aggregates();
});
this.no_leaf = false;
this.grouped = false;
},
view_loading: function(r) {
return this.load_list(r);
},
set_default_options: function (options) {
this._super(options);
_.defaults(this.options, {
GroupsType: instance.web.ListView.Groups,
ListType: instance.web.ListView.List
});
},
/**
* Retrieves the view's number of records per page (|| section)
*
* options > defaults > parent.action.limit > indefinite
*
* @returns {Number|null}
*/
limit: function () {
if (this._limit === undefined) {
this._limit = (this.options.limit
|| this.defaults.limit
|| (this.getParent().action || {}).limit
|| 80);
}
return this._limit;
},
/**
* Set a custom Group construct as the root of the List View.
*
* @param {instance.web.ListView.Groups} groups
*/
set_groups: function (groups) {
var self = this;
if (this.groups) {
$(this.groups).unbind("selected deleted action row_link");
delete this.groups;
}
this.groups = groups;
$(this.groups).bind({
'selected': function (e, ids, records, deselected) {
self.do_select(ids, records, deselected);
},
'deleted': function (e, ids) {
self.do_delete(ids);
},
'action': function (e, action_name, id, callback) {
self.do_button_action(action_name, id, callback);
},
'row_link': function (e, id, dataset, view) {
self.do_activate_record(dataset.index, id, dataset, view);
}
});
},
/**
* View startup method, the default behavior is to set the ``oe_list``
* class on its root element and to perform an RPC load call.
*
* @returns {$.Deferred} loading promise
*/
start: function() {
this.$el.addClass('oe_list');
return this._super();
},
/**
* Returns the style for the provided record in the current view (from the
* ``@colors`` and ``@fonts`` attributes)
*
* @param {Record} record record for the current row
* @returns {String} CSS style declaration
*/
style_for: function (record) {
var style= '';
var context = _.extend({}, record.attributes, {
uid: this.session.uid,
current_date: new Date().toString('yyyy-MM-dd')
// TODO: time, datetime, relativedelta
});
var i;
var pair;
var expression;
if (this.fonts) {
for(i=0, len=this.fonts.length; i<len; ++i) {
pair = this.fonts[i];
var font = pair[0];
expression = pair[1];
if (py.evaluate(expression, context).toJSON()) {
switch(font) {
case 'bold':
style += 'font-weight: bold;';
break;
case 'italic':
style += 'font-style: italic;';
break;
case 'underline':
style += 'text-decoration: underline;';
break;
}
}
}
}
if (!this.colors) { return style; }
for(i=0, len=this.colors.length; i<len; ++i) {
pair = this.colors[i];
var color = pair[0];
expression = pair[1];
if (py.evaluate(expression, context).toJSON()) {
return style += 'color: ' + color + ';';
}
// TODO: handle evaluation errors
}
return style;
},
/**
* Called after loading the list view's description, sets up such things
* as the view table's columns, renders the table itself and hooks up the
* various table-level and row-level DOM events (action buttons, deletion
* buttons, selection of records, [New] button, selection of a given
* record, ...)
*
* Sets up the following:
*
* * Processes arch and fields to generate a complete field descriptor for each field
* * Create the table itself and allocate visible columns
* * Hook in the top-level (header) [New|Add] and [Delete] button
* * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
* * Sets up event handlers for action buttons and per-row deletion button
* * Hooks global callback for clicking on a row
* * Sets up its sidebar, if any
*
* @param {Object} data wrapped fields_view_get result
* @param {Object} data.fields_view fields_view_get result (processed)
* @param {Object} data.fields_view.fields mapping of fields for the current model
* @param {Object} data.fields_view.arch current list view descriptor
* @param {Boolean} grouped Is the list view grouped
*/
load_list: function(data) {
var self = this;
this.fields_view = data;
this.name = "" + this.fields_view.arch.attrs.string;
if (this.fields_view.arch.attrs.colors) {
this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
.compact()
.map(function(color_pair) {
var pair = color_pair.split(':'),
color = pair[0],
expr = pair[1];
return [color, py.parse(py.tokenize(expr)), expr];
}).value();
}
if (this.fields_view.arch.attrs.fonts) {
this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
.map(function(font_pair) {
var pair = font_pair.split(':'),
font = pair[0],
expr = pair[1];
return [font, py.parse(py.tokenize(expr)), expr];
}).value();
}
this.setup_columns(this.fields_view.fields, this.grouped);
this.$el.html(QWeb.render(this._template, this));
this.$el.addClass(this.fields_view.arch.attrs['class']);
// Head hook
// Selecting records
this.$el.find('.oe_list_record_selector').click(function(){
self.$el.find('.oe_list_record_selector input').prop('checked',
self.$el.find('.oe_list_record_selector').prop('checked') || false);
var selection = self.groups.get_selection();
$(self.groups).trigger(
'selected', [selection.ids, selection.records]);
});
// Add button
if (!this.$buttons) {
this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
if (this.options.$buttons) {
this.$buttons.appendTo(this.options.$buttons);
} else {
this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
}
this.$buttons.find('.oe_list_add')
.click(this.proxy('do_add_record'))
.prop('disabled', this.grouped);
}
// Pager
if (!this.$pager) {
this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
if (this.options.$buttons) {
this.$pager.appendTo(this.options.$pager);
} else {
this.$el.find('.oe_list_pager').replaceWith(this.$pager);
}
this.$pager
.on('click', 'a[data-pager-action]', function () {
var $this = $(this);
var max_page = Math.floor(self.dataset.size() / self.limit());
switch ($this.data('pager-action')) {
case 'first':
self.page = 0; break;
case 'last':
self.page = max_page - 1;
break;
case 'next':
self.page += 1; break;
case 'previous':
self.page -= 1; break;
}
if (self.page < 0) {
self.page = max_page;
} else if (self.page > max_page) {
self.page = 0;
}
self.reload_content();
}).find('.oe_list_pager_state')
.click(function (e) {
e.stopPropagation();
var $this = $(this);
var $select = $('<select>')
.appendTo($this.empty())
.click(function (e) {e.stopPropagation();})
.append('<option value="80">80</option>' +
'<option value="200">200</option>' +
'<option value="500">500</option>' +
'<option value="2000">2000</option>' +
'<option value="NaN">' + _t("Unlimited") + '</option>')
.change(function () {
var val = parseInt($select.val(), 10);
self._limit = (isNaN(val) ? null : val);
self.page = 0;
self.reload_content();
}).blur(function() {
$(this).trigger('change');
})
.val(self._limit || 'NaN');
});
}
// Sidebar
if (!this.sidebar && this.options.$sidebar) {
this.sidebar = new instance.web.Sidebar(this);
this.sidebar.appendTo(this.options.$sidebar);
this.sidebar.add_items('other', _.compact([
{ label: _t("Export"), callback: this.on_sidebar_export },
self.is_action_enabled('delete') && { label: _t('Delete'), callback: this.do_delete_selected }
]));
this.sidebar.add_toolbar(this.fields_view.toolbar);
this.sidebar.$el.hide();
}
//Sort
if(this.dataset._sort.length){
if(this.dataset._sort[0].indexOf('-') == -1){
this.$el.find('th[data-id=' + this.dataset._sort[0] + ']').addClass("sortdown");
}else {
this.$el.find('th[data-id=' + this.dataset._sort[0].split('-')[1] + ']').addClass("sortup");
}
}
this.trigger('list_view_loaded', data, this.grouped);
},
sort_by_column: function (e) {
e.stopPropagation();
var $column = $(e.currentTarget);
var col_name = $column.data('id');
var field = this.fields_view.fields[col_name];
// test if the field is a function field with store=false, since it's impossible
// for the server to sort those fields we desactivate the feature
if (field && field.store === false) {
return false;
}
this.dataset.sort(col_name);
if($column.hasClass("sortdown") || $column.hasClass("sortup")) {
$column.toggleClass("sortup sortdown");
} else {
$column.addClass("sortdown");
}
$column.siblings('.oe_sortable').removeClass("sortup sortdown");
this.reload_content();
},
/**
* Configures the ListView pager based on the provided dataset's information
*
* Horrifying side-effect: sets the dataset's data on this.dataset?
*
* @param {instance.web.DataSet} dataset
*/
configure_pager: function (dataset) {
this.dataset.ids = dataset.ids;
// Not exactly clean
if (dataset._length) {
this.dataset._length = dataset._length;
}
var total = dataset.size();
var limit = this.limit() || total;
if (total === 0)
this.$pager.hide();
else
this.$pager.css("display", "");
this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
var spager = '-';
if (total) {
var range_start = this.page * limit + 1;
var range_stop = range_start - 1 + limit;
if (range_stop > total) {
range_stop = total;
}
spager = _.str.sprintf(_t("%d-%d of %d"), range_start, range_stop, total);
}
this.$pager.find('.oe_list_pager_state').text(spager);
},
/**
* Sets up the listview's columns: merges view and fields data, move
* grouped-by columns to the front of the columns list and make them all
* visible.
*
* @param {Object} fields fields_view_get's fields section
* @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
*/
setup_columns: function (fields, grouped) {
var registry = instance.web.list.columns;
this.columns.splice(0, this.columns.length);
this.columns.push.apply(this.columns,
_(this.fields_view.arch.children).map(function (field) {
var id = field.attrs.name;
return registry.for_(id, fields[id], field);
}));
if (grouped) {
this.columns.unshift(
new instance.web.list.MetaColumn('_group', _t("Group")));
}
this.visible_columns = _.filter(this.columns, function (column) {
return column.invisible !== '1';
});
this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
},
/**
* Used to handle a click on a table row, if no other handler caught the
* event.
*
* The default implementation asks the list view's view manager to switch
* to a different view (by calling
* :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
* provided record index (within the current list view's dataset).
*
* If the index is null, ``switch_to_record`` asks for the creation of a
* new record.
*
* @param {Number|void} index the record index (in the current dataset) to switch to
* @param {String} [view="page"] the view type to switch to
*/
select_record:function (index, view) {
view = view || index === null || index === undefined ? 'form' : 'form';
this.dataset.index = index;
_.delay(_.bind(function () {
this.do_switch_view(view);
}, this));
},
do_show: function () {
this._super();
if (this.$buttons) {
this.$buttons.show();
}
if (this.$pager) {
this.$pager.show();
}
},
do_hide: function () {
if (this.sidebar) {
this.sidebar.$el.hide();
}
if (this.$buttons) {
this.$buttons.hide();
}
if (this.$pager) {
this.$pager.hide();
}
this._super();
},
/**
* Reloads the list view based on the current settings (dataset & al)
*
* @deprecated
* @param {Boolean} [grouped] Should the list be displayed grouped
* @param {Object} [context] context to send the server while loading the view
*/
reload_view: function (grouped, context, initial) {
return this.load_view(context);
},
/**
* re-renders the content of the list view
*
* @returns {$.Deferred} promise to content reloading
*/
reload_content: function () {
var self = this;
self.$el.find('.oe_list_record_selector').prop('checked', false);
this.records.reset();
var reloaded = $.Deferred();
this.$el.find('.oe_list_content').append(
this.groups.render(function () {
if ((self.dataset.index === null || self.dataset.index === undefined) && self.records.length ||
self.dataset.index >= self.records.length) {
self.dataset.index = 0;
}
self.compute_aggregates();
reloaded.resolve();
}));
this.do_push_state({
page: this.page,
limit: this._limit
});
return reloaded.promise();
},
reload: function () {
return this.reload_content();
},
reload_record: function (record) {
var self = this;
return this.dataset.read_ids(
[record.get('id')],
_.pluck(_(this.columns).filter(function (r) {
return r.tag === 'field';
}), 'name')
).done(function (records) {
var values = records[0];
if (!values) {
self.records.remove(record);
return;
}
_(_.keys(values)).each(function(key){
record.set(key, values[key], {silent: true});
});
record.trigger('change', record);
});
},
do_load_state: function(state, warm) {
var reload = false;
if (state.page && this.page !== state.page) {
this.page = state.page;
reload = true;
}
if (state.limit) {
if (_.isString(state.limit)) {
state.limit = null;
}
if (state.limit !== this._limit) {
this._limit = state.limit;
reload = true;
}
}
if (reload) {
this.reload_content();
}
},
/**
* Handler for the result of eval_domain_and_context, actually perform the
* searching
*
* @param {Object} results results of evaluating domain and process for a search
*/
do_search: function (domain, context, group_by) {
this.page = 0;
this.groups.datagroup = new DataGroup(
this, this.model, domain, context, group_by);
this.groups.datagroup.sort = this.dataset._sort;
if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
group_by = null;
}
this.no_leaf = !!context['group_by_no_leaf'];
this.grouped = !!group_by;
return this.alive(this.load_view(context)).then(
this.proxy('reload_content'));
},
/**
* Handles the signal to delete lines from the records list
*
* @param {Array} ids the ids of the records to delete
*/
do_delete: function (ids) {
if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
return;
}
var self = this;
return $.when(this.dataset.unlink(ids)).done(function () {
_(ids).each(function (id) {
self.records.remove(self.records.get(id));
});
self.configure_pager(self.dataset);
self.compute_aggregates();
});
},
/**
* Handles the signal indicating that a new record has been selected
*
* @param {Array} ids selected record ids
* @param {Array} records selected record values
*/
do_select: function (ids, records, deselected) {
// uncheck header hook if at least one row has been deselected
if (deselected) {
this.$('.oe_list_record_selector').prop('checked', false);
}
if (!ids.length) {
this.dataset.index = 0;
if (this.sidebar) {
this.sidebar.$el.hide();
}
this.compute_aggregates();
return;
}
this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
if (this.sidebar) {
this.options.$sidebar.show();
this.sidebar.$el.show();
}
this.compute_aggregates(_(records).map(function (record) {
return {count: 1, values: record};
}));
},
/**
* Handles action button signals on a record
*
* @param {String} name action name
* @param {Object} id id of the record the action should be called on
* @param {Function} callback should be called after the action is executed, if non-null
*/
do_button_action: function (name, id, callback) {
this.handle_button(name, id, callback);
},
/**
* Base handling of buttons, can be called when overriding do_button_action
* in order to bypass parent overrides.
*
* The callback will be provided with the ``id`` as its parameter, in case
* handle_button's caller had to alter the ``id`` (or even create one)
* while not being ``callback``'s creator.
*
* This method should not be overridden.
*
* @param {String} name action name
* @param {Object} id id of the record the action should be called on
* @param {Function} callback should be called after the action is executed, if non-null
*/
handle_button: function (name, id, callback) {
var action = _.detect(this.columns, function (field) {
return field.name === name;
});
if (!action) { return; }
if ('confirm' in action && !window.confirm(action.confirm)) {
return;
}
var c = new instance.web.CompoundContext();
c.set_eval_context(_.extend({
active_id: id,
active_ids: [id],
active_model: this.dataset.model
}, this.records.get(id).toContext()));
if (action.context) {
c.add(action.context);
}
action.context = c;
this.do_execute_action(
action, this.dataset, id, _.bind(callback, null, id));
},
/**
* Handles the activation of a record (clicking on it)
*
* @param {Number} index index of the record in the dataset
* @param {Object} id identifier of the activated record
* @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
*/
do_activate_record: function (index, id, dataset, view) {
this.dataset.ids = dataset.ids;
this.select_record(index, view);
},
/**
* Handles signal for the addition of a new record (can be a creation,
* can be the addition from a remote source, ...)
*
* The default implementation is to switch to a new record on the form view
*/
do_add_record: function () {
this.select_record(null);
},
/**
* Handles deletion of all selected lines
*/
do_delete_selected: function () {
var ids = this.groups.get_selection().ids;
if (ids.length) {
this.do_delete(this.groups.get_selection().ids);
} else {
this.do_warn(_t("Warning"), _t("You must select at least one record."));
}
},
/**
* Computes the aggregates for the current list view, either on the
* records provided or on the records of the internal
* :js:class:`~instance.web.ListView.Group`, by calling
* :js:func:`~instance.web.ListView.group.get_records`.
*
* Then displays the aggregates in the table through
* :js:method:`~instance.web.ListView.display_aggregates`.
*
* @param {Array} [records]
*/
compute_aggregates: function (records) {
var columns = _(this.aggregate_columns).filter(function (column) {
return column['function']; });
if (_.isEmpty(columns)) { return; }
if (_.isEmpty(records)) {
records = this.groups.get_records();
}
records = _(records).compact();
var count = 0, sums = {};
_(columns).each(function (column) {
switch (column['function']) {
case 'max':
sums[column.id] = -Infinity;
break;
case 'min':
sums[column.id] = Infinity;
break;
default:
sums[column.id] = 0;
}
});
_(records).each(function (record) {
count += record.count || 1;
_(columns).each(function (column) {
var field = column.id,
value = record.values[field];
switch (column['function']) {
case 'sum':
sums[field] += value;
break;
case 'avg':
sums[field] += record.count * value;
break;
case 'min':
if (sums[field] > value) {
sums[field] = value;
}
break;
case 'max':
if (sums[field] < value) {
sums[field] = value;
}
break;
}
});
});
var aggregates = {};
_(columns).each(function (column) {
var field = column.id;
switch (column['function']) {
case 'avg':
aggregates[field] = {value: sums[field] / count};
break;
default:
aggregates[field] = {value: sums[field]};
}
});
this.display_aggregates(aggregates);
},
display_aggregates: function (aggregation) {
var self = this;
var $footer_cells = this.$el.find('.oe_list_footer');
_(this.aggregate_columns).each(function (column) {
if (!column['function']) {
return;
}
$footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
.html(column.format(aggregation, { process_modifiers: false }));
});
},
get_selected_ids: function() {
var ids = this.groups.get_selection().ids;
return ids;
},
/**
* Calculate the active domain of the list view. This should be done only
* if the header checkbox has been checked. This is done by evaluating the
* search results, and then adding the dataset domain (i.e. action domain).
*/
get_active_domain: function () {
var self = this;
if (this.$('.oe_list_record_selector').prop('checked')) {
var search_view = this.getParent().searchview;
var search_data = search_view.build_search_data();
return instance.web.pyeval.eval_domains_and_contexts({
domains: search_data.domains,
contexts: search_data.contexts,
group_by_seq: search_data.groupbys || []
}).then(function (results) {
var domain = self.dataset.domain.concat(results.domain || []);
return domain
});
}
else {
return $.Deferred().resolve();
}
},
/**
* Adds padding columns at the start or end of all table rows (including
* field names row)
*
* @param {Number} count number of columns to add
* @param {Object} options
* @param {"before"|"after"} [options.position="after"] insertion position for the new columns
* @param {Object} [options.except] content row to not pad
*/
pad_columns: function (count, options) {
options = options || {};
// padding for action/pager header
var $first_header = this.$el.find('thead tr:first th');
var colspan = $first_header.attr('colspan');
if (colspan) {
if (!this.previous_colspan) {
this.previous_colspan = colspan;
}
$first_header.attr('colspan', parseInt(colspan, 10) + count);
}
// Padding for column titles, footer and data rows
var $rows = this.$el
.find('.oe_list_header_columns, tr:not(thead tr)')
.not(options['except']);
var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
if (options.position === 'before') {
$rows.prepend(newcols);
} else {
$rows.append(newcols);
}
},
/**
* Removes all padding columns of the table
*/
unpad_columns: function () {
this.$el.find('.oe_list_padding').remove();
if (this.previous_colspan) {
this.$el
.find('thead tr:first th')
.attr('colspan', this.previous_colspan);
this.previous_colspan = null;
}
},
no_result: function () {
this.$el.find('.oe_view_nocontent').remove();
if (this.groups.group_by
|| !this.options.action
|| !this.options.action.help) {
return;
}
this.$el.find('table:first').hide();
this.$el.prepend(
$('<div class="oe_view_nocontent">').html(this.options.action.help)
);
var create_nocontent = this.$buttons;
this.$el.find('.oe_view_nocontent').click(function() {
create_nocontent.openerpBounce();
});
}
});
instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
/**
* List display for the ListView, handles basic DOM events and transforms
* them in the relevant higher-level events, to which the list view (or
* other consumers) can subscribe.
*
* Events on this object are registered via jQuery.
*
* Available events:
*
* `selected`
* Triggered when a row is selected (using check boxes), provides an
* array of ids of all the selected records.
* `deleted`
* Triggered when deletion buttons are hit, provide an array of ids of
* all the records being marked for suppression.
* `action`
* Triggered when an action button is clicked, provides two parameters:
*
* * The name of the action to execute (as a string)
* * The id of the record to execute the action on
* `row_link`
* Triggered when a row of the table is clicked, provides the index (in
* the rows array) and id of the selected record to the handle function.
*
* @constructs instance.web.ListView.List
* @extends instance.web.Class
*
* @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
*/
init: function (group, opts) {
var self = this;
this.group = group;
this.view = group.view;
this.session = this.view.session;
this.options = opts.options;
this.columns = opts.columns;
this.dataset = opts.dataset;
this.records = opts.records;
this.record_callbacks = {
'remove': function (event, record) {
var id = record.get('id');
self.dataset.remove_ids([id]);
var $row = self.$current.children('[data-id=' + id + ']');
var index = $row.data('index');
$row.remove();
},
'reset': function () { return self.on_records_reset(); },
'change': function (event, record, attribute, value, old_value) {
var $row;
if (attribute === 'id') {
if (old_value) {
throw new Error(_.str.sprintf( _t("Setting 'id' attribute on existing record %s"),
JSON.stringify(record.attributes) ));
}
self.dataset.add_ids([value], self.records.indexOf(record));
// Set id on new record
$row = self.$current.children('[data-id=false]');
} else {
$row = self.$current.children(
'[data-id=' + record.get('id') + ']');
}
$row.replaceWith(self.render_record(record));
},
'add': function (ev, records, record, index) {
var $new_row = $(self.render_record(record));
var id = record.get('id');
if (id) { self.dataset.add_ids([id], index); }
if (index === 0) {
$new_row.prependTo(self.$current);
} else {
var previous_record = records.at(index-1),
$previous_sibling = self.$current.children(
'[data-id=' + previous_record.get('id') + ']');
$new_row.insertAfter($previous_sibling);
}
}
};
_(this.record_callbacks).each(function (callback, event) {
this.records.bind(event, callback);
}, this);
this.$current = $('<tbody>')
.delegate('input[readonly=readonly]', 'click', function (e) {
/*
Against all logic and sense, as of right now @readonly
apparently does nothing on checkbox and radio inputs, so
the trick of using @readonly to have, well, readonly
checkboxes (which still let clicks go through) does not
work out of the box. We *still* need to preventDefault()
on the event, otherwise the checkbox's state *will* toggle
on click
*/
e.preventDefault();
})
.delegate('th.oe_list_record_selector', 'click', function (e) {
e.stopPropagation();
var selection = self.get_selection();
var checked = $(e.currentTarget).find('input').prop('checked');
$(self).trigger(
'selected', [selection.ids, selection.records, ! checked]);
})
.delegate('td.oe_list_record_delete button', 'click', function (e) {
e.stopPropagation();
var $row = $(e.target).closest('tr');
$(self).trigger('deleted', [[self.row_id($row)]]);
})
.delegate('td.oe_list_field_cell button', 'click', function (e) {
e.stopPropagation();
var $target = $(e.currentTarget),
field = $target.closest('td').data('field'),
$row = $target.closest('tr'),
record_id = self.row_id($row);
if ($target.attr('disabled')) {
return;
}
$target.attr('disabled', 'disabled');
// note: $.data converts data to number if it's composed only
// of digits, nice when storing actual numbers, not nice when
// storing strings composed only of digits. Force the action
// name to be a string
$(self).trigger('action', [field.toString(), record_id, function (id) {
$target.removeAttr('disabled');
return self.reload_record(self.records.get(id));
}]);
})
.delegate('a', 'click', function (e) {
e.stopPropagation();
})
.delegate('tr', 'click', function (e) {
var row_id = self.row_id(e.currentTarget);
if (row_id) {
e.stopPropagation();
if (!self.dataset.select_id(row_id)) {
throw new Error(_t("Could not find id in dataset"));
}
self.row_clicked(e);
}
});
},
row_clicked: function (e, view) {
$(this).trigger(
'row_link',
[this.dataset.ids[this.dataset.index],
this.dataset, view]);
},
render_cell: function (record, column) {
var value;
if(column.type === 'reference') {
value = record.get(column.id);
var ref_match;
// Ensure that value is in a reference "shape", otherwise we're
// going to loop on performing name_get after we've resolved (and
// set) a human-readable version. m2o does not have this issue
// because the non-human-readable is just a number, where the
// human-readable version is a pair
if (value && (ref_match = /^([\w\.]+),(\d+)$/.exec(value))) {
// reference values are in the shape "$model,$id" (as a
// string), we need to split and name_get this pair in order
// to get a correctly displayable value in the field
var model = ref_match[1],
id = parseInt(ref_match[2], 10);
new instance.web.DataSet(this.view, model).name_get([id]).done(function(names) {
if (!names.length) { return; }
record.set(column.id, names[0][1]);
});
}
} else if (column.type === 'many2one') {
value = record.get(column.id);
// m2o values are usually name_get formatted, [Number, String]
// pairs, but in some cases only the id is provided. In these
// cases, we need to perform a name_get call to fetch the actual
// displayable value
if (typeof value === 'number' || value instanceof Number) {
// fetch the name, set it on the record (in the right field)
// and let the various registered events handle refreshing the
// row
new instance.web.DataSet(this.view, column.relation)
.name_get([value]).done(function (names) {
if (!names.length) { return; }
record.set(column.id, names[0]);
});
}
} else if (column.type === 'many2many') {
value = record.get(column.id);
// non-resolved (string) m2m values are arrays
if (value instanceof Array && !_.isEmpty(value)
&& !record.get(column.id + '__display')) {
var ids;
// they come in two shapes:
if (value[0] instanceof Array) {
var command = value[0];
// 1. an array of m2m commands (usually (6, false, ids))
if (command[0] !== 6) {
throw new Error(_.str.sprintf( _t("Unknown m2m command %s"), command[0]));
}
ids = command[2];
} else {
// 2. an array of ids
ids = value;
}
new instance.web.Model(column.relation)
.call('name_get', [ids]).done(function (names) {
// FIXME: nth horrible hack in this poor listview
record.set(column.id + '__display',
_(names).pluck(1).join(', '));
record.set(column.id, ids);
});
// temp empty value
record.set(column.id, false);
}
}
return column.format(record.toForm().data, {
model: this.dataset.model,
id: record.get('id')
});
},
render: function () {
this.$current.empty().append(
QWeb.render('ListView.rows', _.extend({
render_cell: function () {
return self.render_cell.apply(self, arguments); }
}, this)));
this.pad_table_to(4);
},
pad_table_to: function (count) {
if (this.records.length >= count ||
_(this.columns).any(function(column) { return column.meta; })) {
return;
}
var cells = [];
if (this.options.selectable) {
cells.push('<th class="oe_list_record_selector"></td>');
}
_(this.columns).each(function(column) {
if (column.invisible === '1') {
return;
}
if (column.tag === 'button') {
cells.push('<td class="oe_button" title="' + column.string + '"> </td>');
} else {
cells.push('<td title="' + column.string + '"> </td>');
}
});
if (this.options.deletable) {
cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
}
cells.unshift('<tr>');
cells.push('</tr>');
var row = cells.join('');
this.$current
.children('tr:not([data-id])').remove().end()
.append(new Array(count - this.records.length + 1).join(row));
},
/**
* Gets the ids of all currently selected records, if any
* @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
*/
get_selection: function () {
var result = {ids: [], records: []};
if (!this.options.selectable) {
return result;
}
var records = this.records;
this.$current.find('th.oe_list_record_selector input:checked')
.closest('tr').each(function () {
var record = records.get($(this).data('id'));
result.ids.push(record.get('id'));
result.records.push(record.attributes);
});
return result;
},
/**
* Returns the identifier of the object displayed in the provided table
* row
*
* @param {Object} row the selected table row
* @returns {Number|String} the identifier of the row's object
*/
row_id: function (row) {
return $(row).data('id');
},
/**
* Death signal, cleans up list display
*/
on_records_reset: function () {
_(this.record_callbacks).each(function (callback, event) {
this.records.unbind(event, callback);
}, this);
if (!this.$current) { return; }
this.$current.remove();
},
get_records: function () {
return this.records.map(function (record) {
return {count: 1, values: record.attributes};
});
},
/**
* Reloads the provided record by re-reading its content from the server.
*
* @param {Record} record
* @returns {$.Deferred} promise to the finalization of the reloading
*/
reload_record: function (record) {
return this.view.reload_record(record);
},
/**
* Renders a list record to HTML
*
* @param {Record} record index of the record to render in ``this.rows``
* @returns {String} QWeb rendering of the selected record
*/
render_record: function (record) {
var self = this;
var index = this.records.indexOf(record);
return QWeb.render('ListView.row', {
columns: this.columns,
options: this.options,
record: record,
row_parity: (index % 2 === 0) ? 'even' : 'odd',
view: this.view,
render_cell: function () {
return self.render_cell.apply(self, arguments); }
});
}
});
instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
passthrough_events: 'action deleted row_link',
/**
* Grouped display for the ListView. Handles basic DOM events and interacts
* with the :js:class:`~DataGroup` bound to it.
*
* Provides events similar to those of
* :js:class:`~instance.web.ListView.List`
*
* @constructs instance.web.ListView.Groups
* @extends instance.web.Class
*
* @param {instance.web.ListView} view
* @param {Object} [options]
* @param {Collection} [options.records]
* @param {Object} [options.options]
* @param {Array} [options.columns]
*/
init: function (view, options) {
options = options || {};
this.view = view;
this.records = options.records || view.records;
this.options = options.options || view.options;
this.columns = options.columns || view.columns;
this.datagroup = null;
this.$row = null;
this.children = {};
this.page = 0;
var self = this;
this.records.bind('reset', function () {
return self.on_records_reset(); });
},
make_fragment: function () {
return document.createDocumentFragment();
},
/**
* Returns a DOM node after which a new tbody can be inserted, so that it
* follows the provided row.
*
* Necessary to insert the result of a new group or list view within an
* existing groups render, without losing track of the groups's own
* elements
*
* @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
* @returns {HTMLTableSectionElement} element after which a tbody can be inserted
*/
point_insertion: function (row) {
var $row = $(row);
var red_letter_tboday = $row.closest('tbody')[0];
var $next_siblings = $row.nextAll();
if ($next_siblings.length) {
var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
$root_kanal.append($next_siblings);
this.elements.splice(
_.indexOf(this.elements, red_letter_tboday),
0,
$root_kanal[0]);
}
return red_letter_tboday;
},
make_paginator: function () {
var self = this;
var $prev = $('<button type="button" data-pager-action="previous"><</button>')
.click(function (e) {
e.stopPropagation();
self.page -= 1;
self.$row.closest('tbody').next()
.replaceWith(self.render());
});
var $next = $('<button type="button" data-pager-action="next">></button>')
.click(function (e) {
e.stopPropagation();
self.page += 1;
self.$row.closest('tbody').next()
.replaceWith(self.render());
});
this.$row.children().last()
.addClass('oe_list_group_pagination')
.append($prev)
.append('<span class="oe_list_pager_state"></span>')
.append($next);
},
open: function (point_insertion) {
this.render().insertAfter(point_insertion);
var no_subgroups = _(this.datagroup.group_by).isEmpty(),
records_terminated = !this.datagroup.context['group_by_no_leaf'];
if (no_subgroups && records_terminated) {
this.make_paginator();
}
},
close: function () {
this.$row.children().last().empty();
this.records.reset();
},
/**
* Prefixes ``$node`` with floated spaces in order to indent it relative
* to its own left margin/baseline
*
* @param {jQuery} $node jQuery object to indent
* @param {Number} level current nesting level, >= 1
* @returns {jQuery} the indentation node created
*/
indent: function ($node, level) {
return $('<span>')
.css({'float': 'left', 'white-space': 'pre'})
.text(new Array(level).join(' '))
.prependTo($node);
},
render_groups: function (datagroups) {
var self = this;
var placeholder = this.make_fragment();
_(datagroups).each(function (group) {
if (self.children[group.value]) {
self.records.proxy(group.value).reset();
delete self.children[group.value];
}
var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
records: self.records.proxy(group.value),
options: self.options,
columns: self.columns
});
self.bind_child_events(child);
child.datagroup = group;
var $row = child.$row = $('<tr class="oe_group_header">');
if (group.openable && group.length) {
$row.click(function (e) {
if (!$row.data('open')) {
$row.data('open', true)
.find('span.ui-icon')
.removeClass('ui-icon-triangle-1-e')
.addClass('ui-icon-triangle-1-s');
child.open(self.point_insertion(e.currentTarget));
} else {
$row.removeData('open')
.find('span.ui-icon')
.removeClass('ui-icon-triangle-1-s')
.addClass('ui-icon-triangle-1-e');
child.close();
}
});
}
placeholder.appendChild($row[0]);
var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
// Don't fill this if group_by_no_leaf but no group_by
if (group.grouped_on) {
var row_data = {};
row_data[group.grouped_on] = group;
var group_column = _(self.columns).detect(function (column) {
return column.id === group.grouped_on; });
if (! group_column) {
throw new Error(_.str.sprintf(
_t("Grouping on field '%s' is not possible because that field does not appear in the list view."),
group.grouped_on));
}
var group_label;
try {
group_label = group_column.format(row_data, {
value_if_empty: _t("Undefined"),
process_modifiers: false
});
} catch (e) {
group_label = _.str.escapeHTML(row_data[group_column.id].value);
}
// group_label is html-clean (through format or explicit
// escaping if format failed), can inject straight into HTML
$group_column.html(_.str.sprintf(_t("%s (%d)"),
group_label, group.length));
if (group.length && group.openable) {
// Make openable if not terminal group & group_by_no_leaf
$group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
} else {
// Kinda-ugly hack: jquery-ui has no "empty" icon, so set
// wonky background position to ensure nothing is displayed
// there but the rest of the behavior is ui-icon's
$group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
}
}
self.indent($group_column, group.level);
if (self.options.selectable) {
$row.append('<td>');
}
_(self.columns).chain()
.filter(function (column) { return column.invisible !== '1'; })
.each(function (column) {
if (column.meta) {
// do not do anything
} else if (column.id in group.aggregates) {
var r = {};
r[column.id] = {value: group.aggregates[column.id]};
$('<td class="oe_number">')
.html(column.format(r, {process_modifiers: false}))
.appendTo($row);
} else {
$row.append('<td>');
}
});
if (self.options.deletable) {
$row.append('<td class="oe_list_group_pagination">');
}
});
return placeholder;
},
bind_child_events: function (child) {
var $this = $(this),
self = this;
$(child).bind('selected', function (e, _0, _1, deselected) {
// can have selections spanning multiple links
var selection = self.get_selection();
$this.trigger(e, [selection.ids, selection.records, deselected]);
}).bind(this.passthrough_events, function (e) {
// additional positional parameters are provided to trigger as an
// Array, following the event type or event object, but are
// provided to the .bind event handler as *args.
// Convert our *args back into an Array in order to trigger them
// on the group itself, so it can ultimately be forwarded wherever
// it's supposed to go.
var args = Array.prototype.slice.call(arguments, 1);
$this.trigger.call($this, e, args);
});
},
render_dataset: function (dataset) {
var self = this,
list = new (this.view.options.ListType)(this, {
options: this.options,
columns: this.columns,
dataset: dataset,
records: this.records
});
this.bind_child_events(list);
var view = this.view,
limit = view.limit(),
d = new $.Deferred(),
page = this.datagroup.openable ? this.page : view.page;
var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field";}), 'name');
var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
//TODO xmo: investigate why we need to put the setTimeout
$.async_when().done(function() {
dataset.read_slice(fields, options).done(function (records) {
// FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
if (self.records.length) {
self.records.reset(null, {silent: true});
}
if (!self.datagroup.openable) {
view.configure_pager(dataset);
} else {
if (dataset.size() == records.length) {
// only one page
self.$row.find('td.oe_list_group_pagination').empty();
} else {
var pages = Math.ceil(dataset.size() / limit);
self.$row
.find('.oe_list_pager_state')
.text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
page: page + 1,
page_count: pages
}))
.end()
.find('button[data-pager-action=previous]')
.css('visibility',
page === 0 ? 'hidden' : '')
.end()
.find('button[data-pager-action=next]')
.css('visibility',
page === pages - 1 ? 'hidden' : '');
}
}
self.records.add(records, {silent: true});
list.render();
d.resolve(list);
if (_.isEmpty(records)) {
view.no_result();
}
});
});
return d.promise();
},
setup_resequence_rows: function (list, dataset) {
// drag and drop enabled if list is not sorted and there is a
// visible column with @widget=handle or "sequence" column in the view.
if ((dataset.sort && dataset.sort())
|| !_(this.columns).any(function (column) {
return column.widget === 'handle'
|| column.name === 'sequence'; })) {
return;
}
var sequence_field = _(this.columns).find(function (c) {
return c.widget === 'handle';
});
var seqname = sequence_field ? sequence_field.name : 'sequence';
// ondrop, move relevant record & fix sequences
list.$current.sortable({
axis: 'y',
items: '> tr[data-id]',
helper: 'clone'
});
if (sequence_field) {
list.$current.sortable('option', 'handle', '.oe_list_field_handle');
}
list.$current.sortable('option', {
start: function (e, ui) {
ui.placeholder.height(ui.item.height());
},
stop: function (event, ui) {
var to_move = list.records.get(ui.item.data('id')),
target_id = ui.item.prev().data('id'),
from_index = list.records.indexOf(to_move),
target = list.records.get(target_id);
if (list.records.at(from_index - 1) == target) {
return;
}
list.records.remove(to_move);
var to = target_id ? list.records.indexOf(target) + 1 : 0;
list.records.add(to_move, { at: to });
// resequencing time!
var record, index = to,
// if drag to 1st row (to = 0), start sequencing from 0
// (exclusive lower bound)
seq = to ? list.records.at(to - 1).get(seqname) : 0;
var fct = function (dataset, id, seq) {
$.async_when().done(function () {
var attrs = {};
attrs[seqname] = seq;
dataset.write(id, attrs);
});
};
while (++seq, (record = list.records.at(index++))) {
// write are independent from one another, so we can just
// launch them all at the same time and we don't really
// give a fig about when they're done
// FIXME: breaks on o2ms (e.g. Accounting > Financial
// Accounting > Taxes > Taxes, child tax accounts)
// when synchronous (without setTimeout)
fct(dataset, record.get('id'), seq);
record.set(seqname, seq);
}
}
});
},
render: function (post_render) {
var self = this;
var $el = $('<tbody>');
this.elements = [$el[0]];
this.datagroup.list(
_(this.view.visible_columns).chain()
.filter(function (column) { return column.tag === 'field';})
.pluck('name').value(),
function (groups) {
$el[0].appendChild(
self.render_groups(groups));
if (post_render) { post_render(); }
}, function (dataset) {
self.render_dataset(dataset).done(function (list) {
self.children[null] = list;
self.elements =
[list.$current.replaceAll($el)[0]];
self.setup_resequence_rows(list, dataset);
if (post_render) { post_render(); }
});
});
return $el;
},
/**
* Returns the ids of all selected records for this group, and the records
* themselves
*/
get_selection: function () {
var ids = [], records = [];
_(this.children)
.each(function (child) {
var selection = child.get_selection();
ids.push.apply(ids, selection.ids);
records.push.apply(records, selection.records);
});
return {ids: ids, records: records};
},
on_records_reset: function () {
this.children = {};
$(this.elements).remove();
},
get_records: function () {
if (_(this.children).isEmpty()) {
if (!this.datagroup.length) {
return;
}
return {
count: this.datagroup.length,
values: this.datagroup.aggregates
};
}
return _(this.children).chain()
.map(function (child) {
return child.get_records();
}).flatten().value();
}
});
var DataGroup = instance.web.Class.extend({
init: function(parent, model, domain, context, group_by, level) {
this.model = new instance.web.Model(model, context, domain);
this.group_by = group_by;
this.context = context;
this.domain = domain;
this.level = level || 0;
},
list: function (fields, ifGroups, ifRecords) {
var self = this;
var query = this.model.query(fields).order_by(this.sort).group_by(this.group_by);
$.when(query).done(function (querygroups) {
// leaf node
if (!querygroups) {
var ds = new instance.web.DataSetSearch(self, self.model.name, self.model.context(), self.model.domain());
ds._sort = self.sort;
ifRecords(ds);
return;
}
// internal node
var child_datagroups = _(querygroups).map(function (group) {
var child_context = _.extend(
{}, self.model.context(), group.model.context());
var child_dg = new DataGroup(
self, self.model.name, group.model.domain(),
child_context, group.model._context.group_by,
self.level + 1);
child_dg.sort = self.sort;
// copy querygroup properties
child_dg.__context = child_context;
child_dg.__domain = group.model.domain();
child_dg.folded = group.get('folded');
child_dg.grouped_on = group.get('grouped_on');
child_dg.length = group.get('length');
child_dg.value = group.get('value');
child_dg.openable = group.get('has_children');
child_dg.aggregates = group.get('aggregates');
return child_dg;
});
ifGroups(child_datagroups);
});
}
});
var StaticDataGroup = DataGroup.extend({
init: function (dataset) {
this.dataset = dataset;
},
list: function (fields, ifGroups, ifRecords) {
ifRecords(this.dataset);
}
});
/**
* @mixin Events
*/
var Events = /** @lends Events# */{
/**
* @param {String} event event to listen to on the current object, null for all events
* @param {Function} handler event handler to bind to the relevant event
* @returns this
*/
bind: function (event, handler) {
var calls = this['_callbacks'] || (this._callbacks = {});
if (event in calls) {
calls[event].push(handler);
} else {
calls[event] = [handler];
}
return this;
},
/**
* @param {String} event event to unbind on the current object
* @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
* @returns this
*/
unbind: function (event, handler) {
var calls = this._callbacks || {};
if (!(event in calls)) { return this; }
if (!handler) {
delete calls[event];
} else {
var handlers = calls[event];
handlers.splice(
_(handlers).indexOf(handler),
1);
}
return this;
},
/**
* @param {String} event
* @returns this
*/
trigger: function (event) {
var calls;
if (!(calls = this._callbacks)) { return this; }
var callbacks = (calls[event] || []).concat(calls[null] || []);
for(var i=0, length=callbacks.length; i<length; ++i) {
callbacks[i].apply(this, arguments);
}
return this;
}
};
var Record = instance.web.Class.extend(/** @lends Record# */{
/**
* @constructs Record
* @extends instance.web.Class
*
* @mixes Events
* @param {Object} [data]
*/
init: function (data) {
this.attributes = data || {};
},
/**
* @param {String} key
* @returns {Object}
*/
get: function (key) {
return this.attributes[key];
},
/**
* @param key
* @param value
* @param {Object} [options]
* @param {Boolean} [options.silent=false]
* @returns {Record}
*/
set: function (key, value, options) {
options = options || {};
var old_value = this.attributes[key];
if (old_value === value) {
return this;
}
this.attributes[key] = value;
if (!options.silent) {
this.trigger('change:' + key, this, value, old_value);
this.trigger('change', this, key, value, old_value);
}
return this;
},
/**
* Converts the current record to the format expected by form views:
*
* .. code-block:: javascript
*
* data: {
* $fieldname: {
* value: $value
* }
* }
*
*
* @returns {Object} record displayable in a form view
*/
toForm: function () {
var form_data = {}, attrs = this.attributes;
for(var k in attrs) {
form_data[k] = {value: attrs[k]};
}
return {data: form_data};
},
/**
* Converts the current record to a format expected by context evaluations
* (identical to record.attributes, except m2o fields are their integer
* value rather than a pair)
*/
toContext: function () {
var output = {}, attrs = this.attributes;
for(var k in attrs) {
var val = attrs[k];
if (typeof val !== 'object') {
output[k] = val;
} else if (val instanceof Array) {
output[k] = val[0];
} else {
throw new Error(_.str.sprintf(_t("Can't convert value %s to context"), val));
}
}
return output;
}
});
Record.include(Events);
var Collection = instance.web.Class.extend(/** @lends Collection# */{
/**
* Smarter collections, with events, very strongly inspired by Backbone's.
*
* Using a "dumb" array of records makes synchronization between the
* various serious
*
* @constructs Collection
* @extends instance.web.Class
*
* @mixes Events
* @param {Array} [records] records to initialize the collection with
* @param {Object} [options]
*/
init: function (records, options) {
options = options || {};
_.bindAll(this, '_onRecordEvent');
this.length = 0;
this.records = [];
this._byId = {};
this._proxies = {};
this._key = options.key;
this._parent = options.parent;
if (records) {
this.add(records);
}
},
/**
* @param {Object|Array} record
* @param {Object} [options]
* @param {Number} [options.at]
* @param {Boolean} [options.silent=false]
* @returns this
*/
add: function (record, options) {
options = options || {};
var records = record instanceof Array ? record : [record];
for(var i=0, length=records.length; i<length; ++i) {
var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
instance_.bind(null, this._onRecordEvent);
this._byId[instance_.get('id')] = instance_;
if (options.at === undefined || options.at === null) {
this.records.push(instance_);
if (!options.silent) {
this.trigger('add', this, instance_, this.records.length-1);
}
} else {
var insertion_index = options.at + i;
this.records.splice(insertion_index, 0, instance_);
if (!options.silent) {
this.trigger('add', this, instance_, insertion_index);
}
}
this.length++;
}
return this;
},
/**
* Get a record by its index in the collection, can also take a group if
* the collection is not degenerate
*
* @param {Number} index
* @param {String} [group]
* @returns {Record|undefined}
*/
at: function (index, group) {
if (group) {
var groups = group.split('.');
return this._proxies[groups[0]].at(index, groups.join('.'));
}
return this.records[index];
},
/**
* Get a record by its database id
*
* @param {Number} id
* @returns {Record|undefined}
*/
get: function (id) {
if (!_(this._proxies).isEmpty()) {
var record = null;
_(this._proxies).detect(function (proxy) {
record = proxy.get(id);
return record;
});
return record;
}
return this._byId[id];
},
/**
* Builds a proxy (insert/retrieve) to a subtree of the collection, by
* the subtree's group
*
* @param {String} section group path section
* @returns {Collection}
*/
proxy: function (section) {
this._proxies[section] = new Collection(null, {
parent: this,
key: section
}).bind(null, this._onRecordEvent);
return this._proxies[section];
},
/**
* @param {Array} [records]
* @returns this
*/
reset: function (records, options) {
options = options || {};
_(this._proxies).each(function (proxy) {
proxy.reset();
});
this._proxies = {};
_(this.records).invoke('unbind', null, this._onRecordEvent);
this.length = 0;
this.records = [];
this._byId = {};
if (records) {
this.add(records);
}
if (!options.silent) {
this.trigger('reset', this);
}
return this;
},
/**
* Removes the provided record from the collection
*
* @param {Record} record
* @returns this
*/
remove: function (record) {
var index = this.indexOf(record);
if (index === -1) {
_(this._proxies).each(function (proxy) {
proxy.remove(record);
});
return this;
}
record.unbind(null, this._onRecordEvent);
this.records.splice(index, 1);
delete this._byId[record.get('id')];
this.length--;
this.trigger('remove', record, this);
return this;
},
_onRecordEvent: function (event) {
switch(event) {
// don't propagate reset events
case 'reset': return;
case 'change:id':
var record = arguments[1];
var new_value = arguments[2];
var old_value = arguments[3];
// [change:id, record, new_value, old_value]
if (this._byId[old_value] === record) {
delete this._byId[old_value];
this._byId[new_value] = record;
}
break;
}
this.trigger.apply(this, arguments);
},
// underscore-type methods
find: function (callback) {
var record;
for(var section in this._proxies) {
if (!this._proxies.hasOwnProperty(section)) {
continue;
}
if ((record = this._proxies[section].find(callback))) {
return record;
}
}
for(var i=0; i<this.length; ++i) {
record = this.records[i];
if (callback(record)) {
return record;
}
}
},
each: function (callback) {
for(var section in this._proxies) {
if (this._proxies.hasOwnProperty(section)) {
this._proxies[section].each(callback);
}
}
for(var i=0; i<this.length; ++i) {
callback(this.records[i]);
}
},
map: function (callback) {
var results = [];
this.each(function (record) {
results.push(callback(record));
});
return results;
},
pluck: function (fieldname) {
return this.map(function (record) {
return record.get(fieldname);
});
},
indexOf: function (record) {
return _(this.records).indexOf(record);
},
succ: function (record, options) {
options = options || {wraparound: false};
var result;
for(var section in this._proxies) {
if (!this._proxies.hasOwnProperty(section)) {
continue;
}
if ((result = this._proxies[section].succ(record, options))) {
return result;
}
}
var index = this.indexOf(record);
if (index === -1) { return null; }
var next_index = index + 1;
if (options.wraparound && (next_index === this.length)) {
return this.at(0);
}
return this.at(next_index);
},
pred: function (record, options) {
options = options || {wraparound: false};
var result;
for (var section in this._proxies) {
if (!this._proxies.hasOwnProperty(section)) {
continue;
}
if ((result = this._proxies[section].pred(record, options))) {
return result;
}
}
var index = this.indexOf(record);
if (index === -1) { return null; }
var next_index = index - 1;
if (options.wraparound && (next_index === -1)) {
return this.at(this.length - 1);
}
return this.at(next_index);
}
});
Collection.include(Events);
instance.web.list = {
Events: Events,
Record: Record,
Collection: Collection
};
/**
* Registry for column objects used to format table cells (and some other tasks
* e.g. aggregation computations).
*
* Maps a field or button to a Column type via its ``$tag.$widget``,
* ``$tag.$type`` or its ``$tag`` (alone).
*
* This specific registry has a dedicated utility method ``for_`` taking a
* field (from fields_get/fields_view_get.field) and a node (from a view) and
* returning the right object *already instantiated from the data provided*.
*
* @type {instance.web.Registry}
*/
instance.web.list.columns = new instance.web.Registry({
'field': 'instance.web.list.Column',
'field.boolean': 'instance.web.list.Boolean',
'field.binary': 'instance.web.list.Binary',
'field.char': 'instance.web.list.Char',
'field.progressbar': 'instance.web.list.ProgressBar',
'field.handle': 'instance.web.list.Handle',
'button': 'instance.web.list.Button',
'field.many2onebutton': 'instance.web.list.Many2OneButton',
'field.many2many': 'instance.web.list.Many2Many'
});
instance.web.list.columns.for_ = function (id, field, node) {
var description = _.extend({tag: node.tag}, field, node.attrs);
var tag = description.tag;
var Type = this.get_any([
tag + '.' + description.widget,
tag + '.'+ description.type,
tag
]);
return new Type(id, node.tag, description);
};
instance.web.list.Column = instance.web.Class.extend({
init: function (id, tag, attrs) {
_.extend(attrs, {
id: id,
tag: tag
});
this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
delete attrs.modifiers;
_.extend(this, attrs);
if (this.modifiers['tree_invisible']) {
this.invisible = '1';
} else { delete this.invisible; }
},
modifiers_for: function (fields) {
var out = {};
var domain_computer = instance.web.form.compute_domain;
for (var attr in this.modifiers) {
if (!this.modifiers.hasOwnProperty(attr)) { continue; }
var modifier = this.modifiers[attr];
out[attr] = _.isBoolean(modifier)
? modifier
: domain_computer(modifier, fields);
}
return out;
},
to_aggregate: function () {
if (this.type !== 'integer' && this.type !== 'float') {
return {};
}
var aggregation_func = this['group_operator'] || 'sum';
if (!(aggregation_func in this)) {
return {};
}
var C = function (fn, label) {
this['function'] = fn;
this.label = label;
};
C.prototype = this;
return new C(aggregation_func, this[aggregation_func]);
},
/**
*
* @param row_data record whose values should be displayed in the cell
* @param {Object} [options]
* @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
* @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
* @param {String} [options.model] current record's model
* @param {Number} [options.id] current record's id
* @return {String}
*/
format: function (row_data, options) {
options = options || {};
var attrs = {};
if (options.process_modifiers !== false) {
attrs = this.modifiers_for(row_data);
}
if (attrs.invisible) { return ''; }
if (!row_data[this.id]) {
return options.value_if_empty === undefined
? ''
: options.value_if_empty;
}
return this._format(row_data, options);
},
/**
* Method to override in order to provide alternative HTML content for the
* cell. Column._format will simply call ``instance.web.format_value`` and
* escape the output.
*
* The output of ``_format`` will *not* be escaped by ``format``, any
* escaping *must be done* by ``format``.
*
* @private
*/
_format: function (row_data, options) {
return _.escape(instance.web.format_value(
row_data[this.id].value, this, options.value_if_empty));
}
});
instance.web.list.MetaColumn = instance.web.list.Column.extend({
meta: true,
init: function (id, string) {
this._super(id, '', {string: string});
}
});
instance.web.list.Button = instance.web.list.Column.extend({
/**
* Return an actual ``<button>`` tag
*/
format: function (row_data, options) {
options = options || {};
var attrs = {};
if (options.process_modifiers !== false) {
attrs = this.modifiers_for(row_data);
}
if (attrs.invisible) { return ''; }
return QWeb.render('ListView.row.button', {
widget: this,
prefix: instance.session.prefix,
disabled: attrs.readonly
|| isNaN(row_data.id.value)
|| instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
});
}
});
instance.web.list.Boolean = instance.web.list.Column.extend({
/**
* Return a potentially disabled checkbox input
*
* @private
*/
_format: function (row_data, options) {
return _.str.sprintf('<input type="checkbox" %s readonly="readonly"/>',
row_data[this.id].value ? 'checked="checked"' : '');
}
});
instance.web.list.Binary = instance.web.list.Column.extend({
/**
* Return a link to the binary data as a file
*
* @private
*/
_format: function (row_data, options) {
var text = _t("Download");
var value = row_data[this.id].value;
var download_url;
if (value && value.substr(0, 10).indexOf(' ') == -1) {
download_url = "data:application/octet-stream;base64," + value;
} else {
download_url = instance.session.url('/web/binary/saveas', {model: options.model, field: this.id, id: options.id});
if (this.filename) {
download_url += '&filename_field=' + this.filename;
}
}
if (this.filename && row_data[this.filename]) {
text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
row_data[this.filename].value, {type: 'char'}));
}
return _.template('<a href="<%-href%>"><%-text%></a> (<%-size%>)', {
text: text,
href: download_url,
size: instance.web.binary_to_binsize(value),
});
}
});
instance.web.list.Char = instance.web.list.Column.extend({
replacement: '*',
/**
* If password field, only display replacement characters (if value is
* non-empty)
*/
_format: function (row_data, options) {
var value = row_data[this.id].value;
if (value && this.password === 'True') {
return value.replace(/[\s\S]/g, _.escape(this.replacement));
}
return this._super(row_data, options);
}
});
instance.web.list.ProgressBar = instance.web.list.Column.extend({
/**
* Return a formatted progress bar display
*
* @private
*/
_format: function (row_data, options) {
return _.template(
'<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
});
}
});
instance.web.list.Handle = instance.web.list.Column.extend({
init: function () {
this._super.apply(this, arguments);
// Handle overrides the field to not be form-editable.
this.modifiers.readonly = true;
},
/**
* Return styling hooks for a drag handle
*
* @private
*/
_format: function (row_data, options) {
return '<div class="oe_list_handle">';
}
});
instance.web.list.Many2OneButton = instance.web.list.Column.extend({
_format: function (row_data, options) {
this.has_value = !!row_data[this.id].value;
this.icon = this.has_value ? 'gtk-yes' : 'gtk-no';
this.string = this.has_value ? _t('View') : _t('Create');
return QWeb.render('Many2OneButton.cell', {
'widget': this,
'prefix': instance.session.prefix,
});
},
});
instance.web.list.Many2Many = instance.web.list.Column.extend({
_format: function (row_data, options) {
if (!_.isEmpty(row_data[this.id].value)) {
// If value, use __display version for printing
row_data[this.id] = row_data[this.id + '__display'];
}
return this._super(row_data, options);
}
});
})();
// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
|
addons/web/static/src/js/view_list.js
|
(function() {
var instance = openerp;
openerp.web.list = {};
var _t = instance.web._t,
_lt = instance.web._lt;
var QWeb = instance.web.qweb;
instance.web.views.add('list', 'instance.web.ListView');
instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListView# */ {
_template: 'ListView',
display_name: _lt('List'),
defaults: {
// records can be selected one by one
'selectable': true,
// list rows can be deleted
'deletable': false,
// whether the column headers should be displayed
'header': true,
// display addition button, with that label
'addable': _lt("Create"),
// whether the list view can be sorted, note that once a view has been
// sorted it can not be reordered anymore
'sortable': true,
// whether the view rows can be reordered (via vertical drag & drop)
'reorderable': true,
'action_buttons': true,
//whether the editable property of the view has to be disabled
'disable_editable_mode': false,
},
view_type: 'tree',
events: {
'click thead th.oe_sortable[data-id]': 'sort_by_column'
},
/**
* Core class for list-type displays.
*
* As a view, needs a number of view-related parameters to be correctly
* instantiated, provides options and overridable methods for behavioral
* customization.
*
* See constructor parameters and method documentations for information on
* the default behaviors and possible options for the list view.
*
* @constructs instance.web.ListView
* @extends instance.web.View
*
* @param parent parent object
* @param {instance.web.DataSet} dataset the dataset the view should work with
* @param {String} view_id the listview's identifier, if any
* @param {Object} options A set of options used to configure the view
* @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
* @param {Boolean} [options.header=true] should the list's header be displayed
* @param {Boolean} [options.deletable=true] are the list rows deletable
* @param {void|String} [options.addable="New"] should the new-record button be displayed, and what should its label be. Use ``null`` to hide the button.
* @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
* @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
*/
init: function(parent, dataset, view_id, options) {
var self = this;
this._super(parent);
this.set_default_options(_.extend({}, this.defaults, options || {}));
this.dataset = dataset;
this.model = dataset.model;
this.view_id = view_id;
this.previous_colspan = null;
this.colors = null;
this.fonts = null;
this.columns = [];
this.records = new Collection();
this.set_groups(new (this.options.GroupsType)(this));
if (this.dataset instanceof instance.web.DataSetStatic) {
this.groups.datagroup = new StaticDataGroup(this.dataset);
} else {
this.groups.datagroup = new DataGroup(
this, this.model,
dataset.get_domain(),
dataset.get_context());
this.groups.datagroup.sort = this.dataset._sort;
}
this.page = 0;
this.records.bind('change', function (event, record, key) {
if (!_(self.aggregate_columns).chain()
.pluck('name').contains(key).value()) {
return;
}
self.compute_aggregates();
});
this.no_leaf = false;
this.grouped = false;
},
view_loading: function(r) {
return this.load_list(r);
},
set_default_options: function (options) {
this._super(options);
_.defaults(this.options, {
GroupsType: instance.web.ListView.Groups,
ListType: instance.web.ListView.List
});
},
/**
* Retrieves the view's number of records per page (|| section)
*
* options > defaults > parent.action.limit > indefinite
*
* @returns {Number|null}
*/
limit: function () {
if (this._limit === undefined) {
this._limit = (this.options.limit
|| this.defaults.limit
|| (this.getParent().action || {}).limit
|| 80);
}
return this._limit;
},
/**
* Set a custom Group construct as the root of the List View.
*
* @param {instance.web.ListView.Groups} groups
*/
set_groups: function (groups) {
var self = this;
if (this.groups) {
$(this.groups).unbind("selected deleted action row_link");
delete this.groups;
}
this.groups = groups;
$(this.groups).bind({
'selected': function (e, ids, records, deselected) {
self.do_select(ids, records, deselected);
},
'deleted': function (e, ids) {
self.do_delete(ids);
},
'action': function (e, action_name, id, callback) {
self.do_button_action(action_name, id, callback);
},
'row_link': function (e, id, dataset, view) {
self.do_activate_record(dataset.index, id, dataset, view);
}
});
},
/**
* View startup method, the default behavior is to set the ``oe_list``
* class on its root element and to perform an RPC load call.
*
* @returns {$.Deferred} loading promise
*/
start: function() {
this.$el.addClass('oe_list');
return this._super();
},
/**
* Returns the style for the provided record in the current view (from the
* ``@colors`` and ``@fonts`` attributes)
*
* @param {Record} record record for the current row
* @returns {String} CSS style declaration
*/
style_for: function (record) {
var style= '';
var context = _.extend({}, record.attributes, {
uid: this.session.uid,
current_date: new Date().toString('yyyy-MM-dd')
// TODO: time, datetime, relativedelta
});
var i;
var pair;
var expression;
if (this.fonts) {
for(i=0, len=this.fonts.length; i<len; ++i) {
pair = this.fonts[i];
var font = pair[0];
expression = pair[1];
if (py.evaluate(expression, context).toJSON()) {
switch(font) {
case 'bold':
style += 'font-weight: bold;';
break;
case 'italic':
style += 'font-style: italic;';
break;
case 'underline':
style += 'text-decoration: underline;';
break;
}
}
}
}
if (!this.colors) { return style; }
for(i=0, len=this.colors.length; i<len; ++i) {
pair = this.colors[i];
var color = pair[0];
expression = pair[1];
if (py.evaluate(expression, context).toJSON()) {
return style += 'color: ' + color + ';';
}
// TODO: handle evaluation errors
}
return style;
},
/**
* Called after loading the list view's description, sets up such things
* as the view table's columns, renders the table itself and hooks up the
* various table-level and row-level DOM events (action buttons, deletion
* buttons, selection of records, [New] button, selection of a given
* record, ...)
*
* Sets up the following:
*
* * Processes arch and fields to generate a complete field descriptor for each field
* * Create the table itself and allocate visible columns
* * Hook in the top-level (header) [New|Add] and [Delete] button
* * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
* * Sets up event handlers for action buttons and per-row deletion button
* * Hooks global callback for clicking on a row
* * Sets up its sidebar, if any
*
* @param {Object} data wrapped fields_view_get result
* @param {Object} data.fields_view fields_view_get result (processed)
* @param {Object} data.fields_view.fields mapping of fields for the current model
* @param {Object} data.fields_view.arch current list view descriptor
* @param {Boolean} grouped Is the list view grouped
*/
load_list: function(data) {
var self = this;
this.fields_view = data;
this.name = "" + this.fields_view.arch.attrs.string;
if (this.fields_view.arch.attrs.colors) {
this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
.compact()
.map(function(color_pair) {
var pair = color_pair.split(':'),
color = pair[0],
expr = pair[1];
return [color, py.parse(py.tokenize(expr)), expr];
}).value();
}
if (this.fields_view.arch.attrs.fonts) {
this.fonts = _(this.fields_view.arch.attrs.fonts.split(';')).chain().compact()
.map(function(font_pair) {
var pair = font_pair.split(':'),
font = pair[0],
expr = pair[1];
return [font, py.parse(py.tokenize(expr)), expr];
}).value();
}
this.setup_columns(this.fields_view.fields, this.grouped);
this.$el.html(QWeb.render(this._template, this));
this.$el.addClass(this.fields_view.arch.attrs['class']);
// Head hook
// Selecting records
this.$el.find('.oe_list_record_selector').click(function(){
self.$el.find('.oe_list_record_selector input').prop('checked',
self.$el.find('.oe_list_record_selector').prop('checked') || false);
var selection = self.groups.get_selection();
$(self.groups).trigger(
'selected', [selection.ids, selection.records]);
});
// Add button
if (!this.$buttons) {
this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self}));
if (this.options.$buttons) {
this.$buttons.appendTo(this.options.$buttons);
} else {
this.$el.find('.oe_list_buttons').replaceWith(this.$buttons);
}
this.$buttons.find('.oe_list_add')
.click(this.proxy('do_add_record'))
.prop('disabled', this.grouped);
}
// Pager
if (!this.$pager) {
this.$pager = $(QWeb.render("ListView.pager", {'widget':self}));
if (this.options.$buttons) {
this.$pager.appendTo(this.options.$pager);
} else {
this.$el.find('.oe_list_pager').replaceWith(this.$pager);
}
this.$pager
.on('click', 'a[data-pager-action]', function () {
var $this = $(this);
var max_page = Math.floor(self.dataset.size() / self.limit());
switch ($this.data('pager-action')) {
case 'first':
self.page = 0; break;
case 'last':
self.page = max_page - 1;
break;
case 'next':
self.page += 1; break;
case 'previous':
self.page -= 1; break;
}
if (self.page < 0) {
self.page = max_page;
} else if (self.page > max_page) {
self.page = 0;
}
self.reload_content();
}).find('.oe_list_pager_state')
.click(function (e) {
e.stopPropagation();
var $this = $(this);
var $select = $('<select>')
.appendTo($this.empty())
.click(function (e) {e.stopPropagation();})
.append('<option value="80">80</option>' +
'<option value="200">200</option>' +
'<option value="500">500</option>' +
'<option value="2000">2000</option>' +
'<option value="NaN">' + _t("Unlimited") + '</option>')
.change(function () {
var val = parseInt($select.val(), 10);
self._limit = (isNaN(val) ? null : val);
self.page = 0;
self.reload_content();
}).blur(function() {
$(this).trigger('change');
})
.val(self._limit || 'NaN');
});
}
// Sidebar
if (!this.sidebar && this.options.$sidebar) {
this.sidebar = new instance.web.Sidebar(this);
this.sidebar.appendTo(this.options.$sidebar);
this.sidebar.add_items('other', _.compact([
{ label: _t("Export"), callback: this.on_sidebar_export },
self.is_action_enabled('delete') && { label: _t('Delete'), callback: this.do_delete_selected }
]));
this.sidebar.add_toolbar(this.fields_view.toolbar);
this.sidebar.$el.hide();
}
//Sort
if(this.dataset._sort.length){
if(this.dataset._sort[0].indexOf('-') == -1){
this.$el.find('th[data-id=' + this.dataset._sort[0] + ']').addClass("sortdown");
}else {
this.$el.find('th[data-id=' + this.dataset._sort[0].split('-')[1] + ']').addClass("sortup");
}
}
this.trigger('list_view_loaded', data, this.grouped);
},
sort_by_column: function (e) {
e.stopPropagation();
var $column = $(e.currentTarget);
var col_name = $column.data('id');
var field = this.fields_view.fields[col_name];
// test if the field is a function field with store=false, since it's impossible
// for the server to sort those fields we desactivate the feature
if (field && field.store === false) {
return false;
}
this.dataset.sort(col_name);
if($column.hasClass("sortdown") || $column.hasClass("sortup")) {
$column.toggleClass("sortup sortdown");
} else {
$column.addClass("sortdown");
}
$column.siblings('.oe_sortable').removeClass("sortup sortdown");
this.reload_content();
},
/**
* Configures the ListView pager based on the provided dataset's information
*
* Horrifying side-effect: sets the dataset's data on this.dataset?
*
* @param {instance.web.DataSet} dataset
*/
configure_pager: function (dataset) {
this.dataset.ids = dataset.ids;
// Not exactly clean
if (dataset._length) {
this.dataset._length = dataset._length;
}
var total = dataset.size();
var limit = this.limit() || total;
if (total === 0)
this.$pager.hide();
else
this.$pager.css("display", "");
this.$pager.toggleClass('oe_list_pager_single_page', (total <= limit));
var spager = '-';
if (total) {
var range_start = this.page * limit + 1;
var range_stop = range_start - 1 + limit;
if (range_stop > total) {
range_stop = total;
}
spager = _.str.sprintf(_t("%d-%d of %d"), range_start, range_stop, total);
}
this.$pager.find('.oe_list_pager_state').text(spager);
},
/**
* Sets up the listview's columns: merges view and fields data, move
* grouped-by columns to the front of the columns list and make them all
* visible.
*
* @param {Object} fields fields_view_get's fields section
* @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
*/
setup_columns: function (fields, grouped) {
var registry = instance.web.list.columns;
this.columns.splice(0, this.columns.length);
this.columns.push.apply(this.columns,
_(this.fields_view.arch.children).map(function (field) {
var id = field.attrs.name;
return registry.for_(id, fields[id], field);
}));
if (grouped) {
this.columns.unshift(
new instance.web.list.MetaColumn('_group', _t("Group")));
}
this.visible_columns = _.filter(this.columns, function (column) {
return column.invisible !== '1';
});
this.aggregate_columns = _(this.visible_columns).invoke('to_aggregate');
},
/**
* Used to handle a click on a table row, if no other handler caught the
* event.
*
* The default implementation asks the list view's view manager to switch
* to a different view (by calling
* :js:func:`~instance.web.ViewManager.on_mode_switch`), using the
* provided record index (within the current list view's dataset).
*
* If the index is null, ``switch_to_record`` asks for the creation of a
* new record.
*
* @param {Number|void} index the record index (in the current dataset) to switch to
* @param {String} [view="page"] the view type to switch to
*/
select_record:function (index, view) {
view = view || index === null || index === undefined ? 'form' : 'form';
this.dataset.index = index;
_.delay(_.bind(function () {
this.do_switch_view(view);
}, this));
},
do_show: function () {
this._super();
if (this.$buttons) {
this.$buttons.show();
}
if (this.$pager) {
this.$pager.show();
}
},
do_hide: function () {
if (this.sidebar) {
this.sidebar.$el.hide();
}
if (this.$buttons) {
this.$buttons.hide();
}
if (this.$pager) {
this.$pager.hide();
}
this._super();
},
/**
* Reloads the list view based on the current settings (dataset & al)
*
* @deprecated
* @param {Boolean} [grouped] Should the list be displayed grouped
* @param {Object} [context] context to send the server while loading the view
*/
reload_view: function (grouped, context, initial) {
return this.load_view(context);
},
/**
* re-renders the content of the list view
*
* @returns {$.Deferred} promise to content reloading
*/
reload_content: function () {
var self = this;
self.$el.find('.oe_list_record_selector').prop('checked', false);
this.records.reset();
var reloaded = $.Deferred();
this.$el.find('.oe_list_content').append(
this.groups.render(function () {
if ((self.dataset.index === null || self.dataset.index === undefined) && self.records.length ||
self.dataset.index >= self.records.length) {
self.dataset.index = 0;
}
self.compute_aggregates();
reloaded.resolve();
}));
this.do_push_state({
page: this.page,
limit: this._limit
});
return reloaded.promise();
},
reload: function () {
return this.reload_content();
},
reload_record: function (record) {
var self = this;
return this.dataset.read_ids(
[record.get('id')],
_.pluck(_(this.columns).filter(function (r) {
return r.tag === 'field';
}), 'name')
).done(function (records) {
var values = records[0];
if (!values) {
self.records.remove(record);
return;
}
_(_.keys(values)).each(function(key){
record.set(key, values[key], {silent: true});
});
record.trigger('change', record);
});
},
do_load_state: function(state, warm) {
var reload = false;
if (state.page && this.page !== state.page) {
this.page = state.page;
reload = true;
}
if (state.limit) {
if (_.isString(state.limit)) {
state.limit = null;
}
if (state.limit !== this._limit) {
this._limit = state.limit;
reload = true;
}
}
if (reload) {
this.reload_content();
}
},
/**
* Handler for the result of eval_domain_and_context, actually perform the
* searching
*
* @param {Object} results results of evaluating domain and process for a search
*/
do_search: function (domain, context, group_by) {
this.page = 0;
this.groups.datagroup = new DataGroup(
this, this.model, domain, context, group_by);
this.groups.datagroup.sort = this.dataset._sort;
if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
group_by = null;
}
this.no_leaf = !!context['group_by_no_leaf'];
this.grouped = !!group_by;
return this.alive(this.load_view(context)).then(
this.proxy('reload_content'));
},
/**
* Handles the signal to delete lines from the records list
*
* @param {Array} ids the ids of the records to delete
*/
do_delete: function (ids) {
if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
return;
}
var self = this;
return $.when(this.dataset.unlink(ids)).done(function () {
_(ids).each(function (id) {
self.records.remove(self.records.get(id));
});
self.configure_pager(self.dataset);
self.compute_aggregates();
});
},
/**
* Handles the signal indicating that a new record has been selected
*
* @param {Array} ids selected record ids
* @param {Array} records selected record values
*/
do_select: function (ids, records, deselected) {
// uncheck header hook if at least one row has been deselected
if (deselected) {
this.$('.oe_list_record_selector').prop('checked', false);
}
if (!ids.length) {
this.dataset.index = 0;
if (this.sidebar) {
this.sidebar.$el.hide();
}
this.compute_aggregates();
return;
}
this.dataset.index = _(this.dataset.ids).indexOf(ids[0]);
if (this.sidebar) {
this.options.$sidebar.show();
this.sidebar.$el.show();
}
this.compute_aggregates(_(records).map(function (record) {
return {count: 1, values: record};
}));
},
/**
* Handles action button signals on a record
*
* @param {String} name action name
* @param {Object} id id of the record the action should be called on
* @param {Function} callback should be called after the action is executed, if non-null
*/
do_button_action: function (name, id, callback) {
this.handle_button(name, id, callback);
},
/**
* Base handling of buttons, can be called when overriding do_button_action
* in order to bypass parent overrides.
*
* The callback will be provided with the ``id`` as its parameter, in case
* handle_button's caller had to alter the ``id`` (or even create one)
* while not being ``callback``'s creator.
*
* This method should not be overridden.
*
* @param {String} name action name
* @param {Object} id id of the record the action should be called on
* @param {Function} callback should be called after the action is executed, if non-null
*/
handle_button: function (name, id, callback) {
var action = _.detect(this.columns, function (field) {
return field.name === name;
});
if (!action) { return; }
if ('confirm' in action && !window.confirm(action.confirm)) {
return;
}
var c = new instance.web.CompoundContext();
c.set_eval_context(_.extend({
active_id: id,
active_ids: [id],
active_model: this.dataset.model
}, this.records.get(id).toContext()));
if (action.context) {
c.add(action.context);
}
action.context = c;
this.do_execute_action(
action, this.dataset, id, _.bind(callback, null, id));
},
/**
* Handles the activation of a record (clicking on it)
*
* @param {Number} index index of the record in the dataset
* @param {Object} id identifier of the activated record
* @param {instance.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
*/
do_activate_record: function (index, id, dataset, view) {
this.dataset.ids = dataset.ids;
this.select_record(index, view);
},
/**
* Handles signal for the addition of a new record (can be a creation,
* can be the addition from a remote source, ...)
*
* The default implementation is to switch to a new record on the form view
*/
do_add_record: function () {
this.select_record(null);
},
/**
* Handles deletion of all selected lines
*/
do_delete_selected: function () {
var ids = this.groups.get_selection().ids;
if (ids.length) {
this.do_delete(this.groups.get_selection().ids);
} else {
this.do_warn(_t("Warning"), _t("You must select at least one record."));
}
},
/**
* Computes the aggregates for the current list view, either on the
* records provided or on the records of the internal
* :js:class:`~instance.web.ListView.Group`, by calling
* :js:func:`~instance.web.ListView.group.get_records`.
*
* Then displays the aggregates in the table through
* :js:method:`~instance.web.ListView.display_aggregates`.
*
* @param {Array} [records]
*/
compute_aggregates: function (records) {
var columns = _(this.aggregate_columns).filter(function (column) {
return column['function']; });
if (_.isEmpty(columns)) { return; }
if (_.isEmpty(records)) {
records = this.groups.get_records();
}
records = _(records).compact();
var count = 0, sums = {};
_(columns).each(function (column) {
switch (column['function']) {
case 'max':
sums[column.id] = -Infinity;
break;
case 'min':
sums[column.id] = Infinity;
break;
default:
sums[column.id] = 0;
}
});
_(records).each(function (record) {
count += record.count || 1;
_(columns).each(function (column) {
var field = column.id,
value = record.values[field];
switch (column['function']) {
case 'sum':
sums[field] += value;
break;
case 'avg':
sums[field] += record.count * value;
break;
case 'min':
if (sums[field] > value) {
sums[field] = value;
}
break;
case 'max':
if (sums[field] < value) {
sums[field] = value;
}
break;
}
});
});
var aggregates = {};
_(columns).each(function (column) {
var field = column.id;
switch (column['function']) {
case 'avg':
aggregates[field] = {value: sums[field] / count};
break;
default:
aggregates[field] = {value: sums[field]};
}
});
this.display_aggregates(aggregates);
},
display_aggregates: function (aggregation) {
var self = this;
var $footer_cells = this.$el.find('.oe_list_footer');
_(this.aggregate_columns).each(function (column) {
if (!column['function']) {
return;
}
$footer_cells.filter(_.str.sprintf('[data-field=%s]', column.id))
.html(column.format(aggregation, { process_modifiers: false }));
});
},
get_selected_ids: function() {
var ids = this.groups.get_selection().ids;
return ids;
},
/**
* Calculate the active domain of the list view. This should be done only
* if the header checkbox has been checked.
*/
get_active_domain: function () {
if (this.$('.oe_list_record_selector').prop('checked')) {
var search_view = this.getParent().searchview;
var search_data = search_view.build_search_data();
return instance.web.pyeval.eval_domains_and_contexts({
domains: search_data.domains,
contexts: search_data.contexts,
group_by_seq: search_data.groupbys || []
}).then(function (results) {
return results.domain;
});
}
else {
return $.Deferred().resolve();
}
},
/**
* Adds padding columns at the start or end of all table rows (including
* field names row)
*
* @param {Number} count number of columns to add
* @param {Object} options
* @param {"before"|"after"} [options.position="after"] insertion position for the new columns
* @param {Object} [options.except] content row to not pad
*/
pad_columns: function (count, options) {
options = options || {};
// padding for action/pager header
var $first_header = this.$el.find('thead tr:first th');
var colspan = $first_header.attr('colspan');
if (colspan) {
if (!this.previous_colspan) {
this.previous_colspan = colspan;
}
$first_header.attr('colspan', parseInt(colspan, 10) + count);
}
// Padding for column titles, footer and data rows
var $rows = this.$el
.find('.oe_list_header_columns, tr:not(thead tr)')
.not(options['except']);
var newcols = new Array(count+1).join('<td class="oe_list_padding"></td>');
if (options.position === 'before') {
$rows.prepend(newcols);
} else {
$rows.append(newcols);
}
},
/**
* Removes all padding columns of the table
*/
unpad_columns: function () {
this.$el.find('.oe_list_padding').remove();
if (this.previous_colspan) {
this.$el
.find('thead tr:first th')
.attr('colspan', this.previous_colspan);
this.previous_colspan = null;
}
},
no_result: function () {
this.$el.find('.oe_view_nocontent').remove();
if (this.groups.group_by
|| !this.options.action
|| !this.options.action.help) {
return;
}
this.$el.find('table:first').hide();
this.$el.prepend(
$('<div class="oe_view_nocontent">').html(this.options.action.help)
);
var create_nocontent = this.$buttons;
this.$el.find('.oe_view_nocontent').click(function() {
create_nocontent.openerpBounce();
});
}
});
instance.web.ListView.List = instance.web.Class.extend( /** @lends instance.web.ListView.List# */{
/**
* List display for the ListView, handles basic DOM events and transforms
* them in the relevant higher-level events, to which the list view (or
* other consumers) can subscribe.
*
* Events on this object are registered via jQuery.
*
* Available events:
*
* `selected`
* Triggered when a row is selected (using check boxes), provides an
* array of ids of all the selected records.
* `deleted`
* Triggered when deletion buttons are hit, provide an array of ids of
* all the records being marked for suppression.
* `action`
* Triggered when an action button is clicked, provides two parameters:
*
* * The name of the action to execute (as a string)
* * The id of the record to execute the action on
* `row_link`
* Triggered when a row of the table is clicked, provides the index (in
* the rows array) and id of the selected record to the handle function.
*
* @constructs instance.web.ListView.List
* @extends instance.web.Class
*
* @param {Object} opts display options, identical to those of :js:class:`instance.web.ListView`
*/
init: function (group, opts) {
var self = this;
this.group = group;
this.view = group.view;
this.session = this.view.session;
this.options = opts.options;
this.columns = opts.columns;
this.dataset = opts.dataset;
this.records = opts.records;
this.record_callbacks = {
'remove': function (event, record) {
var id = record.get('id');
self.dataset.remove_ids([id]);
var $row = self.$current.children('[data-id=' + id + ']');
var index = $row.data('index');
$row.remove();
},
'reset': function () { return self.on_records_reset(); },
'change': function (event, record, attribute, value, old_value) {
var $row;
if (attribute === 'id') {
if (old_value) {
throw new Error(_.str.sprintf( _t("Setting 'id' attribute on existing record %s"),
JSON.stringify(record.attributes) ));
}
self.dataset.add_ids([value], self.records.indexOf(record));
// Set id on new record
$row = self.$current.children('[data-id=false]');
} else {
$row = self.$current.children(
'[data-id=' + record.get('id') + ']');
}
$row.replaceWith(self.render_record(record));
},
'add': function (ev, records, record, index) {
var $new_row = $(self.render_record(record));
var id = record.get('id');
if (id) { self.dataset.add_ids([id], index); }
if (index === 0) {
$new_row.prependTo(self.$current);
} else {
var previous_record = records.at(index-1),
$previous_sibling = self.$current.children(
'[data-id=' + previous_record.get('id') + ']');
$new_row.insertAfter($previous_sibling);
}
}
};
_(this.record_callbacks).each(function (callback, event) {
this.records.bind(event, callback);
}, this);
this.$current = $('<tbody>')
.delegate('input[readonly=readonly]', 'click', function (e) {
/*
Against all logic and sense, as of right now @readonly
apparently does nothing on checkbox and radio inputs, so
the trick of using @readonly to have, well, readonly
checkboxes (which still let clicks go through) does not
work out of the box. We *still* need to preventDefault()
on the event, otherwise the checkbox's state *will* toggle
on click
*/
e.preventDefault();
})
.delegate('th.oe_list_record_selector', 'click', function (e) {
e.stopPropagation();
var selection = self.get_selection();
var checked = $(e.currentTarget).find('input').prop('checked');
$(self).trigger(
'selected', [selection.ids, selection.records, ! checked]);
})
.delegate('td.oe_list_record_delete button', 'click', function (e) {
e.stopPropagation();
var $row = $(e.target).closest('tr');
$(self).trigger('deleted', [[self.row_id($row)]]);
})
.delegate('td.oe_list_field_cell button', 'click', function (e) {
e.stopPropagation();
var $target = $(e.currentTarget),
field = $target.closest('td').data('field'),
$row = $target.closest('tr'),
record_id = self.row_id($row);
if ($target.attr('disabled')) {
return;
}
$target.attr('disabled', 'disabled');
// note: $.data converts data to number if it's composed only
// of digits, nice when storing actual numbers, not nice when
// storing strings composed only of digits. Force the action
// name to be a string
$(self).trigger('action', [field.toString(), record_id, function (id) {
$target.removeAttr('disabled');
return self.reload_record(self.records.get(id));
}]);
})
.delegate('a', 'click', function (e) {
e.stopPropagation();
})
.delegate('tr', 'click', function (e) {
var row_id = self.row_id(e.currentTarget);
if (row_id) {
e.stopPropagation();
if (!self.dataset.select_id(row_id)) {
throw new Error(_t("Could not find id in dataset"));
}
self.row_clicked(e);
}
});
},
row_clicked: function (e, view) {
$(this).trigger(
'row_link',
[this.dataset.ids[this.dataset.index],
this.dataset, view]);
},
render_cell: function (record, column) {
var value;
if(column.type === 'reference') {
value = record.get(column.id);
var ref_match;
// Ensure that value is in a reference "shape", otherwise we're
// going to loop on performing name_get after we've resolved (and
// set) a human-readable version. m2o does not have this issue
// because the non-human-readable is just a number, where the
// human-readable version is a pair
if (value && (ref_match = /^([\w\.]+),(\d+)$/.exec(value))) {
// reference values are in the shape "$model,$id" (as a
// string), we need to split and name_get this pair in order
// to get a correctly displayable value in the field
var model = ref_match[1],
id = parseInt(ref_match[2], 10);
new instance.web.DataSet(this.view, model).name_get([id]).done(function(names) {
if (!names.length) { return; }
record.set(column.id, names[0][1]);
});
}
} else if (column.type === 'many2one') {
value = record.get(column.id);
// m2o values are usually name_get formatted, [Number, String]
// pairs, but in some cases only the id is provided. In these
// cases, we need to perform a name_get call to fetch the actual
// displayable value
if (typeof value === 'number' || value instanceof Number) {
// fetch the name, set it on the record (in the right field)
// and let the various registered events handle refreshing the
// row
new instance.web.DataSet(this.view, column.relation)
.name_get([value]).done(function (names) {
if (!names.length) { return; }
record.set(column.id, names[0]);
});
}
} else if (column.type === 'many2many') {
value = record.get(column.id);
// non-resolved (string) m2m values are arrays
if (value instanceof Array && !_.isEmpty(value)
&& !record.get(column.id + '__display')) {
var ids;
// they come in two shapes:
if (value[0] instanceof Array) {
var command = value[0];
// 1. an array of m2m commands (usually (6, false, ids))
if (command[0] !== 6) {
throw new Error(_.str.sprintf( _t("Unknown m2m command %s"), command[0]));
}
ids = command[2];
} else {
// 2. an array of ids
ids = value;
}
new instance.web.Model(column.relation)
.call('name_get', [ids]).done(function (names) {
// FIXME: nth horrible hack in this poor listview
record.set(column.id + '__display',
_(names).pluck(1).join(', '));
record.set(column.id, ids);
});
// temp empty value
record.set(column.id, false);
}
}
return column.format(record.toForm().data, {
model: this.dataset.model,
id: record.get('id')
});
},
render: function () {
this.$current.empty().append(
QWeb.render('ListView.rows', _.extend({
render_cell: function () {
return self.render_cell.apply(self, arguments); }
}, this)));
this.pad_table_to(4);
},
pad_table_to: function (count) {
if (this.records.length >= count ||
_(this.columns).any(function(column) { return column.meta; })) {
return;
}
var cells = [];
if (this.options.selectable) {
cells.push('<th class="oe_list_record_selector"></td>');
}
_(this.columns).each(function(column) {
if (column.invisible === '1') {
return;
}
if (column.tag === 'button') {
cells.push('<td class="oe_button" title="' + column.string + '"> </td>');
} else {
cells.push('<td title="' + column.string + '"> </td>');
}
});
if (this.options.deletable) {
cells.push('<td class="oe_list_record_delete"><button type="button" style="visibility: hidden"> </button></td>');
}
cells.unshift('<tr>');
cells.push('</tr>');
var row = cells.join('');
this.$current
.children('tr:not([data-id])').remove().end()
.append(new Array(count - this.records.length + 1).join(row));
},
/**
* Gets the ids of all currently selected records, if any
* @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
*/
get_selection: function () {
var result = {ids: [], records: []};
if (!this.options.selectable) {
return result;
}
var records = this.records;
this.$current.find('th.oe_list_record_selector input:checked')
.closest('tr').each(function () {
var record = records.get($(this).data('id'));
result.ids.push(record.get('id'));
result.records.push(record.attributes);
});
return result;
},
/**
* Returns the identifier of the object displayed in the provided table
* row
*
* @param {Object} row the selected table row
* @returns {Number|String} the identifier of the row's object
*/
row_id: function (row) {
return $(row).data('id');
},
/**
* Death signal, cleans up list display
*/
on_records_reset: function () {
_(this.record_callbacks).each(function (callback, event) {
this.records.unbind(event, callback);
}, this);
if (!this.$current) { return; }
this.$current.remove();
},
get_records: function () {
return this.records.map(function (record) {
return {count: 1, values: record.attributes};
});
},
/**
* Reloads the provided record by re-reading its content from the server.
*
* @param {Record} record
* @returns {$.Deferred} promise to the finalization of the reloading
*/
reload_record: function (record) {
return this.view.reload_record(record);
},
/**
* Renders a list record to HTML
*
* @param {Record} record index of the record to render in ``this.rows``
* @returns {String} QWeb rendering of the selected record
*/
render_record: function (record) {
var self = this;
var index = this.records.indexOf(record);
return QWeb.render('ListView.row', {
columns: this.columns,
options: this.options,
record: record,
row_parity: (index % 2 === 0) ? 'even' : 'odd',
view: this.view,
render_cell: function () {
return self.render_cell.apply(self, arguments); }
});
}
});
instance.web.ListView.Groups = instance.web.Class.extend( /** @lends instance.web.ListView.Groups# */{
passthrough_events: 'action deleted row_link',
/**
* Grouped display for the ListView. Handles basic DOM events and interacts
* with the :js:class:`~DataGroup` bound to it.
*
* Provides events similar to those of
* :js:class:`~instance.web.ListView.List`
*
* @constructs instance.web.ListView.Groups
* @extends instance.web.Class
*
* @param {instance.web.ListView} view
* @param {Object} [options]
* @param {Collection} [options.records]
* @param {Object} [options.options]
* @param {Array} [options.columns]
*/
init: function (view, options) {
options = options || {};
this.view = view;
this.records = options.records || view.records;
this.options = options.options || view.options;
this.columns = options.columns || view.columns;
this.datagroup = null;
this.$row = null;
this.children = {};
this.page = 0;
var self = this;
this.records.bind('reset', function () {
return self.on_records_reset(); });
},
make_fragment: function () {
return document.createDocumentFragment();
},
/**
* Returns a DOM node after which a new tbody can be inserted, so that it
* follows the provided row.
*
* Necessary to insert the result of a new group or list view within an
* existing groups render, without losing track of the groups's own
* elements
*
* @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
* @returns {HTMLTableSectionElement} element after which a tbody can be inserted
*/
point_insertion: function (row) {
var $row = $(row);
var red_letter_tboday = $row.closest('tbody')[0];
var $next_siblings = $row.nextAll();
if ($next_siblings.length) {
var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
$root_kanal.append($next_siblings);
this.elements.splice(
_.indexOf(this.elements, red_letter_tboday),
0,
$root_kanal[0]);
}
return red_letter_tboday;
},
make_paginator: function () {
var self = this;
var $prev = $('<button type="button" data-pager-action="previous"><</button>')
.click(function (e) {
e.stopPropagation();
self.page -= 1;
self.$row.closest('tbody').next()
.replaceWith(self.render());
});
var $next = $('<button type="button" data-pager-action="next">></button>')
.click(function (e) {
e.stopPropagation();
self.page += 1;
self.$row.closest('tbody').next()
.replaceWith(self.render());
});
this.$row.children().last()
.addClass('oe_list_group_pagination')
.append($prev)
.append('<span class="oe_list_pager_state"></span>')
.append($next);
},
open: function (point_insertion) {
this.render().insertAfter(point_insertion);
var no_subgroups = _(this.datagroup.group_by).isEmpty(),
records_terminated = !this.datagroup.context['group_by_no_leaf'];
if (no_subgroups && records_terminated) {
this.make_paginator();
}
},
close: function () {
this.$row.children().last().empty();
this.records.reset();
},
/**
* Prefixes ``$node`` with floated spaces in order to indent it relative
* to its own left margin/baseline
*
* @param {jQuery} $node jQuery object to indent
* @param {Number} level current nesting level, >= 1
* @returns {jQuery} the indentation node created
*/
indent: function ($node, level) {
return $('<span>')
.css({'float': 'left', 'white-space': 'pre'})
.text(new Array(level).join(' '))
.prependTo($node);
},
render_groups: function (datagroups) {
var self = this;
var placeholder = this.make_fragment();
_(datagroups).each(function (group) {
if (self.children[group.value]) {
self.records.proxy(group.value).reset();
delete self.children[group.value];
}
var child = self.children[group.value] = new (self.view.options.GroupsType)(self.view, {
records: self.records.proxy(group.value),
options: self.options,
columns: self.columns
});
self.bind_child_events(child);
child.datagroup = group;
var $row = child.$row = $('<tr class="oe_group_header">');
if (group.openable && group.length) {
$row.click(function (e) {
if (!$row.data('open')) {
$row.data('open', true)
.find('span.ui-icon')
.removeClass('ui-icon-triangle-1-e')
.addClass('ui-icon-triangle-1-s');
child.open(self.point_insertion(e.currentTarget));
} else {
$row.removeData('open')
.find('span.ui-icon')
.removeClass('ui-icon-triangle-1-s')
.addClass('ui-icon-triangle-1-e');
child.close();
}
});
}
placeholder.appendChild($row[0]);
var $group_column = $('<th class="oe_list_group_name">').appendTo($row);
// Don't fill this if group_by_no_leaf but no group_by
if (group.grouped_on) {
var row_data = {};
row_data[group.grouped_on] = group;
var group_column = _(self.columns).detect(function (column) {
return column.id === group.grouped_on; });
if (! group_column) {
throw new Error(_.str.sprintf(
_t("Grouping on field '%s' is not possible because that field does not appear in the list view."),
group.grouped_on));
}
var group_label;
try {
group_label = group_column.format(row_data, {
value_if_empty: _t("Undefined"),
process_modifiers: false
});
} catch (e) {
group_label = _.str.escapeHTML(row_data[group_column.id].value);
}
// group_label is html-clean (through format or explicit
// escaping if format failed), can inject straight into HTML
$group_column.html(_.str.sprintf(_t("%s (%d)"),
group_label, group.length));
if (group.length && group.openable) {
// Make openable if not terminal group & group_by_no_leaf
$group_column.prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
} else {
// Kinda-ugly hack: jquery-ui has no "empty" icon, so set
// wonky background position to ensure nothing is displayed
// there but the rest of the behavior is ui-icon's
$group_column.prepend('<span class="ui-icon" style="float: left; background-position: 150px 150px">');
}
}
self.indent($group_column, group.level);
if (self.options.selectable) {
$row.append('<td>');
}
_(self.columns).chain()
.filter(function (column) { return column.invisible !== '1'; })
.each(function (column) {
if (column.meta) {
// do not do anything
} else if (column.id in group.aggregates) {
var r = {};
r[column.id] = {value: group.aggregates[column.id]};
$('<td class="oe_number">')
.html(column.format(r, {process_modifiers: false}))
.appendTo($row);
} else {
$row.append('<td>');
}
});
if (self.options.deletable) {
$row.append('<td class="oe_list_group_pagination">');
}
});
return placeholder;
},
bind_child_events: function (child) {
var $this = $(this),
self = this;
$(child).bind('selected', function (e, _0, _1, deselected) {
// can have selections spanning multiple links
var selection = self.get_selection();
$this.trigger(e, [selection.ids, selection.records, deselected]);
}).bind(this.passthrough_events, function (e) {
// additional positional parameters are provided to trigger as an
// Array, following the event type or event object, but are
// provided to the .bind event handler as *args.
// Convert our *args back into an Array in order to trigger them
// on the group itself, so it can ultimately be forwarded wherever
// it's supposed to go.
var args = Array.prototype.slice.call(arguments, 1);
$this.trigger.call($this, e, args);
});
},
render_dataset: function (dataset) {
var self = this,
list = new (this.view.options.ListType)(this, {
options: this.options,
columns: this.columns,
dataset: dataset,
records: this.records
});
this.bind_child_events(list);
var view = this.view,
limit = view.limit(),
d = new $.Deferred(),
page = this.datagroup.openable ? this.page : view.page;
var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field";}), 'name');
var options = { offset: page * limit, limit: limit, context: {bin_size: true} };
//TODO xmo: investigate why we need to put the setTimeout
$.async_when().done(function() {
dataset.read_slice(fields, options).done(function (records) {
// FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
if (self.records.length) {
self.records.reset(null, {silent: true});
}
if (!self.datagroup.openable) {
view.configure_pager(dataset);
} else {
if (dataset.size() == records.length) {
// only one page
self.$row.find('td.oe_list_group_pagination').empty();
} else {
var pages = Math.ceil(dataset.size() / limit);
self.$row
.find('.oe_list_pager_state')
.text(_.str.sprintf(_t("%(page)d/%(page_count)d"), {
page: page + 1,
page_count: pages
}))
.end()
.find('button[data-pager-action=previous]')
.css('visibility',
page === 0 ? 'hidden' : '')
.end()
.find('button[data-pager-action=next]')
.css('visibility',
page === pages - 1 ? 'hidden' : '');
}
}
self.records.add(records, {silent: true});
list.render();
d.resolve(list);
if (_.isEmpty(records)) {
view.no_result();
}
});
});
return d.promise();
},
setup_resequence_rows: function (list, dataset) {
// drag and drop enabled if list is not sorted and there is a
// visible column with @widget=handle or "sequence" column in the view.
if ((dataset.sort && dataset.sort())
|| !_(this.columns).any(function (column) {
return column.widget === 'handle'
|| column.name === 'sequence'; })) {
return;
}
var sequence_field = _(this.columns).find(function (c) {
return c.widget === 'handle';
});
var seqname = sequence_field ? sequence_field.name : 'sequence';
// ondrop, move relevant record & fix sequences
list.$current.sortable({
axis: 'y',
items: '> tr[data-id]',
helper: 'clone'
});
if (sequence_field) {
list.$current.sortable('option', 'handle', '.oe_list_field_handle');
}
list.$current.sortable('option', {
start: function (e, ui) {
ui.placeholder.height(ui.item.height());
},
stop: function (event, ui) {
var to_move = list.records.get(ui.item.data('id')),
target_id = ui.item.prev().data('id'),
from_index = list.records.indexOf(to_move),
target = list.records.get(target_id);
if (list.records.at(from_index - 1) == target) {
return;
}
list.records.remove(to_move);
var to = target_id ? list.records.indexOf(target) + 1 : 0;
list.records.add(to_move, { at: to });
// resequencing time!
var record, index = to,
// if drag to 1st row (to = 0), start sequencing from 0
// (exclusive lower bound)
seq = to ? list.records.at(to - 1).get(seqname) : 0;
var fct = function (dataset, id, seq) {
$.async_when().done(function () {
var attrs = {};
attrs[seqname] = seq;
dataset.write(id, attrs);
});
};
while (++seq, (record = list.records.at(index++))) {
// write are independent from one another, so we can just
// launch them all at the same time and we don't really
// give a fig about when they're done
// FIXME: breaks on o2ms (e.g. Accounting > Financial
// Accounting > Taxes > Taxes, child tax accounts)
// when synchronous (without setTimeout)
fct(dataset, record.get('id'), seq);
record.set(seqname, seq);
}
}
});
},
render: function (post_render) {
var self = this;
var $el = $('<tbody>');
this.elements = [$el[0]];
this.datagroup.list(
_(this.view.visible_columns).chain()
.filter(function (column) { return column.tag === 'field';})
.pluck('name').value(),
function (groups) {
$el[0].appendChild(
self.render_groups(groups));
if (post_render) { post_render(); }
}, function (dataset) {
self.render_dataset(dataset).done(function (list) {
self.children[null] = list;
self.elements =
[list.$current.replaceAll($el)[0]];
self.setup_resequence_rows(list, dataset);
if (post_render) { post_render(); }
});
});
return $el;
},
/**
* Returns the ids of all selected records for this group, and the records
* themselves
*/
get_selection: function () {
var ids = [], records = [];
_(this.children)
.each(function (child) {
var selection = child.get_selection();
ids.push.apply(ids, selection.ids);
records.push.apply(records, selection.records);
});
return {ids: ids, records: records};
},
on_records_reset: function () {
this.children = {};
$(this.elements).remove();
},
get_records: function () {
if (_(this.children).isEmpty()) {
if (!this.datagroup.length) {
return;
}
return {
count: this.datagroup.length,
values: this.datagroup.aggregates
};
}
return _(this.children).chain()
.map(function (child) {
return child.get_records();
}).flatten().value();
}
});
var DataGroup = instance.web.Class.extend({
init: function(parent, model, domain, context, group_by, level) {
this.model = new instance.web.Model(model, context, domain);
this.group_by = group_by;
this.context = context;
this.domain = domain;
this.level = level || 0;
},
list: function (fields, ifGroups, ifRecords) {
var self = this;
var query = this.model.query(fields).order_by(this.sort).group_by(this.group_by);
$.when(query).done(function (querygroups) {
// leaf node
if (!querygroups) {
var ds = new instance.web.DataSetSearch(self, self.model.name, self.model.context(), self.model.domain());
ds._sort = self.sort;
ifRecords(ds);
return;
}
// internal node
var child_datagroups = _(querygroups).map(function (group) {
var child_context = _.extend(
{}, self.model.context(), group.model.context());
var child_dg = new DataGroup(
self, self.model.name, group.model.domain(),
child_context, group.model._context.group_by,
self.level + 1);
child_dg.sort = self.sort;
// copy querygroup properties
child_dg.__context = child_context;
child_dg.__domain = group.model.domain();
child_dg.folded = group.get('folded');
child_dg.grouped_on = group.get('grouped_on');
child_dg.length = group.get('length');
child_dg.value = group.get('value');
child_dg.openable = group.get('has_children');
child_dg.aggregates = group.get('aggregates');
return child_dg;
});
ifGroups(child_datagroups);
});
}
});
var StaticDataGroup = DataGroup.extend({
init: function (dataset) {
this.dataset = dataset;
},
list: function (fields, ifGroups, ifRecords) {
ifRecords(this.dataset);
}
});
/**
* @mixin Events
*/
var Events = /** @lends Events# */{
/**
* @param {String} event event to listen to on the current object, null for all events
* @param {Function} handler event handler to bind to the relevant event
* @returns this
*/
bind: function (event, handler) {
var calls = this['_callbacks'] || (this._callbacks = {});
if (event in calls) {
calls[event].push(handler);
} else {
calls[event] = [handler];
}
return this;
},
/**
* @param {String} event event to unbind on the current object
* @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
* @returns this
*/
unbind: function (event, handler) {
var calls = this._callbacks || {};
if (!(event in calls)) { return this; }
if (!handler) {
delete calls[event];
} else {
var handlers = calls[event];
handlers.splice(
_(handlers).indexOf(handler),
1);
}
return this;
},
/**
* @param {String} event
* @returns this
*/
trigger: function (event) {
var calls;
if (!(calls = this._callbacks)) { return this; }
var callbacks = (calls[event] || []).concat(calls[null] || []);
for(var i=0, length=callbacks.length; i<length; ++i) {
callbacks[i].apply(this, arguments);
}
return this;
}
};
var Record = instance.web.Class.extend(/** @lends Record# */{
/**
* @constructs Record
* @extends instance.web.Class
*
* @mixes Events
* @param {Object} [data]
*/
init: function (data) {
this.attributes = data || {};
},
/**
* @param {String} key
* @returns {Object}
*/
get: function (key) {
return this.attributes[key];
},
/**
* @param key
* @param value
* @param {Object} [options]
* @param {Boolean} [options.silent=false]
* @returns {Record}
*/
set: function (key, value, options) {
options = options || {};
var old_value = this.attributes[key];
if (old_value === value) {
return this;
}
this.attributes[key] = value;
if (!options.silent) {
this.trigger('change:' + key, this, value, old_value);
this.trigger('change', this, key, value, old_value);
}
return this;
},
/**
* Converts the current record to the format expected by form views:
*
* .. code-block:: javascript
*
* data: {
* $fieldname: {
* value: $value
* }
* }
*
*
* @returns {Object} record displayable in a form view
*/
toForm: function () {
var form_data = {}, attrs = this.attributes;
for(var k in attrs) {
form_data[k] = {value: attrs[k]};
}
return {data: form_data};
},
/**
* Converts the current record to a format expected by context evaluations
* (identical to record.attributes, except m2o fields are their integer
* value rather than a pair)
*/
toContext: function () {
var output = {}, attrs = this.attributes;
for(var k in attrs) {
var val = attrs[k];
if (typeof val !== 'object') {
output[k] = val;
} else if (val instanceof Array) {
output[k] = val[0];
} else {
throw new Error(_.str.sprintf(_t("Can't convert value %s to context"), val));
}
}
return output;
}
});
Record.include(Events);
var Collection = instance.web.Class.extend(/** @lends Collection# */{
/**
* Smarter collections, with events, very strongly inspired by Backbone's.
*
* Using a "dumb" array of records makes synchronization between the
* various serious
*
* @constructs Collection
* @extends instance.web.Class
*
* @mixes Events
* @param {Array} [records] records to initialize the collection with
* @param {Object} [options]
*/
init: function (records, options) {
options = options || {};
_.bindAll(this, '_onRecordEvent');
this.length = 0;
this.records = [];
this._byId = {};
this._proxies = {};
this._key = options.key;
this._parent = options.parent;
if (records) {
this.add(records);
}
},
/**
* @param {Object|Array} record
* @param {Object} [options]
* @param {Number} [options.at]
* @param {Boolean} [options.silent=false]
* @returns this
*/
add: function (record, options) {
options = options || {};
var records = record instanceof Array ? record : [record];
for(var i=0, length=records.length; i<length; ++i) {
var instance_ = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
instance_.bind(null, this._onRecordEvent);
this._byId[instance_.get('id')] = instance_;
if (options.at === undefined || options.at === null) {
this.records.push(instance_);
if (!options.silent) {
this.trigger('add', this, instance_, this.records.length-1);
}
} else {
var insertion_index = options.at + i;
this.records.splice(insertion_index, 0, instance_);
if (!options.silent) {
this.trigger('add', this, instance_, insertion_index);
}
}
this.length++;
}
return this;
},
/**
* Get a record by its index in the collection, can also take a group if
* the collection is not degenerate
*
* @param {Number} index
* @param {String} [group]
* @returns {Record|undefined}
*/
at: function (index, group) {
if (group) {
var groups = group.split('.');
return this._proxies[groups[0]].at(index, groups.join('.'));
}
return this.records[index];
},
/**
* Get a record by its database id
*
* @param {Number} id
* @returns {Record|undefined}
*/
get: function (id) {
if (!_(this._proxies).isEmpty()) {
var record = null;
_(this._proxies).detect(function (proxy) {
record = proxy.get(id);
return record;
});
return record;
}
return this._byId[id];
},
/**
* Builds a proxy (insert/retrieve) to a subtree of the collection, by
* the subtree's group
*
* @param {String} section group path section
* @returns {Collection}
*/
proxy: function (section) {
this._proxies[section] = new Collection(null, {
parent: this,
key: section
}).bind(null, this._onRecordEvent);
return this._proxies[section];
},
/**
* @param {Array} [records]
* @returns this
*/
reset: function (records, options) {
options = options || {};
_(this._proxies).each(function (proxy) {
proxy.reset();
});
this._proxies = {};
_(this.records).invoke('unbind', null, this._onRecordEvent);
this.length = 0;
this.records = [];
this._byId = {};
if (records) {
this.add(records);
}
if (!options.silent) {
this.trigger('reset', this);
}
return this;
},
/**
* Removes the provided record from the collection
*
* @param {Record} record
* @returns this
*/
remove: function (record) {
var index = this.indexOf(record);
if (index === -1) {
_(this._proxies).each(function (proxy) {
proxy.remove(record);
});
return this;
}
record.unbind(null, this._onRecordEvent);
this.records.splice(index, 1);
delete this._byId[record.get('id')];
this.length--;
this.trigger('remove', record, this);
return this;
},
_onRecordEvent: function (event) {
switch(event) {
// don't propagate reset events
case 'reset': return;
case 'change:id':
var record = arguments[1];
var new_value = arguments[2];
var old_value = arguments[3];
// [change:id, record, new_value, old_value]
if (this._byId[old_value] === record) {
delete this._byId[old_value];
this._byId[new_value] = record;
}
break;
}
this.trigger.apply(this, arguments);
},
// underscore-type methods
find: function (callback) {
var record;
for(var section in this._proxies) {
if (!this._proxies.hasOwnProperty(section)) {
continue;
}
if ((record = this._proxies[section].find(callback))) {
return record;
}
}
for(var i=0; i<this.length; ++i) {
record = this.records[i];
if (callback(record)) {
return record;
}
}
},
each: function (callback) {
for(var section in this._proxies) {
if (this._proxies.hasOwnProperty(section)) {
this._proxies[section].each(callback);
}
}
for(var i=0; i<this.length; ++i) {
callback(this.records[i]);
}
},
map: function (callback) {
var results = [];
this.each(function (record) {
results.push(callback(record));
});
return results;
},
pluck: function (fieldname) {
return this.map(function (record) {
return record.get(fieldname);
});
},
indexOf: function (record) {
return _(this.records).indexOf(record);
},
succ: function (record, options) {
options = options || {wraparound: false};
var result;
for(var section in this._proxies) {
if (!this._proxies.hasOwnProperty(section)) {
continue;
}
if ((result = this._proxies[section].succ(record, options))) {
return result;
}
}
var index = this.indexOf(record);
if (index === -1) { return null; }
var next_index = index + 1;
if (options.wraparound && (next_index === this.length)) {
return this.at(0);
}
return this.at(next_index);
},
pred: function (record, options) {
options = options || {wraparound: false};
var result;
for (var section in this._proxies) {
if (!this._proxies.hasOwnProperty(section)) {
continue;
}
if ((result = this._proxies[section].pred(record, options))) {
return result;
}
}
var index = this.indexOf(record);
if (index === -1) { return null; }
var next_index = index - 1;
if (options.wraparound && (next_index === -1)) {
return this.at(this.length - 1);
}
return this.at(next_index);
}
});
Collection.include(Events);
instance.web.list = {
Events: Events,
Record: Record,
Collection: Collection
};
/**
* Registry for column objects used to format table cells (and some other tasks
* e.g. aggregation computations).
*
* Maps a field or button to a Column type via its ``$tag.$widget``,
* ``$tag.$type`` or its ``$tag`` (alone).
*
* This specific registry has a dedicated utility method ``for_`` taking a
* field (from fields_get/fields_view_get.field) and a node (from a view) and
* returning the right object *already instantiated from the data provided*.
*
* @type {instance.web.Registry}
*/
instance.web.list.columns = new instance.web.Registry({
'field': 'instance.web.list.Column',
'field.boolean': 'instance.web.list.Boolean',
'field.binary': 'instance.web.list.Binary',
'field.char': 'instance.web.list.Char',
'field.progressbar': 'instance.web.list.ProgressBar',
'field.handle': 'instance.web.list.Handle',
'button': 'instance.web.list.Button',
'field.many2onebutton': 'instance.web.list.Many2OneButton',
'field.many2many': 'instance.web.list.Many2Many'
});
instance.web.list.columns.for_ = function (id, field, node) {
var description = _.extend({tag: node.tag}, field, node.attrs);
var tag = description.tag;
var Type = this.get_any([
tag + '.' + description.widget,
tag + '.'+ description.type,
tag
]);
return new Type(id, node.tag, description);
};
instance.web.list.Column = instance.web.Class.extend({
init: function (id, tag, attrs) {
_.extend(attrs, {
id: id,
tag: tag
});
this.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
delete attrs.modifiers;
_.extend(this, attrs);
if (this.modifiers['tree_invisible']) {
this.invisible = '1';
} else { delete this.invisible; }
},
modifiers_for: function (fields) {
var out = {};
var domain_computer = instance.web.form.compute_domain;
for (var attr in this.modifiers) {
if (!this.modifiers.hasOwnProperty(attr)) { continue; }
var modifier = this.modifiers[attr];
out[attr] = _.isBoolean(modifier)
? modifier
: domain_computer(modifier, fields);
}
return out;
},
to_aggregate: function () {
if (this.type !== 'integer' && this.type !== 'float') {
return {};
}
var aggregation_func = this['group_operator'] || 'sum';
if (!(aggregation_func in this)) {
return {};
}
var C = function (fn, label) {
this['function'] = fn;
this.label = label;
};
C.prototype = this;
return new C(aggregation_func, this[aggregation_func]);
},
/**
*
* @param row_data record whose values should be displayed in the cell
* @param {Object} [options]
* @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
* @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
* @param {String} [options.model] current record's model
* @param {Number} [options.id] current record's id
* @return {String}
*/
format: function (row_data, options) {
options = options || {};
var attrs = {};
if (options.process_modifiers !== false) {
attrs = this.modifiers_for(row_data);
}
if (attrs.invisible) { return ''; }
if (!row_data[this.id]) {
return options.value_if_empty === undefined
? ''
: options.value_if_empty;
}
return this._format(row_data, options);
},
/**
* Method to override in order to provide alternative HTML content for the
* cell. Column._format will simply call ``instance.web.format_value`` and
* escape the output.
*
* The output of ``_format`` will *not* be escaped by ``format``, any
* escaping *must be done* by ``format``.
*
* @private
*/
_format: function (row_data, options) {
return _.escape(instance.web.format_value(
row_data[this.id].value, this, options.value_if_empty));
}
});
instance.web.list.MetaColumn = instance.web.list.Column.extend({
meta: true,
init: function (id, string) {
this._super(id, '', {string: string});
}
});
instance.web.list.Button = instance.web.list.Column.extend({
/**
* Return an actual ``<button>`` tag
*/
format: function (row_data, options) {
options = options || {};
var attrs = {};
if (options.process_modifiers !== false) {
attrs = this.modifiers_for(row_data);
}
if (attrs.invisible) { return ''; }
return QWeb.render('ListView.row.button', {
widget: this,
prefix: instance.session.prefix,
disabled: attrs.readonly
|| isNaN(row_data.id.value)
|| instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
});
}
});
instance.web.list.Boolean = instance.web.list.Column.extend({
/**
* Return a potentially disabled checkbox input
*
* @private
*/
_format: function (row_data, options) {
return _.str.sprintf('<input type="checkbox" %s readonly="readonly"/>',
row_data[this.id].value ? 'checked="checked"' : '');
}
});
instance.web.list.Binary = instance.web.list.Column.extend({
/**
* Return a link to the binary data as a file
*
* @private
*/
_format: function (row_data, options) {
var text = _t("Download");
var value = row_data[this.id].value;
var download_url;
if (value && value.substr(0, 10).indexOf(' ') == -1) {
download_url = "data:application/octet-stream;base64," + value;
} else {
download_url = instance.session.url('/web/binary/saveas', {model: options.model, field: this.id, id: options.id});
if (this.filename) {
download_url += '&filename_field=' + this.filename;
}
}
if (this.filename && row_data[this.filename]) {
text = _.str.sprintf(_t("Download \"%s\""), instance.web.format_value(
row_data[this.filename].value, {type: 'char'}));
}
return _.template('<a href="<%-href%>"><%-text%></a> (<%-size%>)', {
text: text,
href: download_url,
size: instance.web.binary_to_binsize(value),
});
}
});
instance.web.list.Char = instance.web.list.Column.extend({
replacement: '*',
/**
* If password field, only display replacement characters (if value is
* non-empty)
*/
_format: function (row_data, options) {
var value = row_data[this.id].value;
if (value && this.password === 'True') {
return value.replace(/[\s\S]/g, _.escape(this.replacement));
}
return this._super(row_data, options);
}
});
instance.web.list.ProgressBar = instance.web.list.Column.extend({
/**
* Return a formatted progress bar display
*
* @private
*/
_format: function (row_data, options) {
return _.template(
'<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
value: _.str.sprintf("%.0f", row_data[this.id].value || 0)
});
}
});
instance.web.list.Handle = instance.web.list.Column.extend({
init: function () {
this._super.apply(this, arguments);
// Handle overrides the field to not be form-editable.
this.modifiers.readonly = true;
},
/**
* Return styling hooks for a drag handle
*
* @private
*/
_format: function (row_data, options) {
return '<div class="oe_list_handle">';
}
});
instance.web.list.Many2OneButton = instance.web.list.Column.extend({
_format: function (row_data, options) {
this.has_value = !!row_data[this.id].value;
this.icon = this.has_value ? 'gtk-yes' : 'gtk-no';
this.string = this.has_value ? _t('View') : _t('Create');
return QWeb.render('Many2OneButton.cell', {
'widget': this,
'prefix': instance.session.prefix,
});
},
});
instance.web.list.Many2Many = instance.web.list.Column.extend({
_format: function (row_data, options) {
if (!_.isEmpty(row_data[this.id].value)) {
// If value, use __display version for printing
row_data[this.id] = row_data[this.id + '__display'];
}
return this._super(row_data, options);
}
});
})();
// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
|
[FIX] list_view: when composing the active_domain
in list view because of the list header being checked,
also take into account the current action domain;
bzr revid: [email protected]
|
addons/web/static/src/js/view_list.js
|
[FIX] list_view: when composing the active_domain in list view because of the list header being checked, also take into account the current action domain;
|
<ide><path>ddons/web/static/src/js/view_list.js
<ide> },
<ide> /**
<ide> * Calculate the active domain of the list view. This should be done only
<del> * if the header checkbox has been checked.
<add> * if the header checkbox has been checked. This is done by evaluating the
<add> * search results, and then adding the dataset domain (i.e. action domain).
<ide> */
<ide> get_active_domain: function () {
<add> var self = this;
<ide> if (this.$('.oe_list_record_selector').prop('checked')) {
<ide> var search_view = this.getParent().searchview;
<ide> var search_data = search_view.build_search_data();
<ide> contexts: search_data.contexts,
<ide> group_by_seq: search_data.groupbys || []
<ide> }).then(function (results) {
<del> return results.domain;
<add> var domain = self.dataset.domain.concat(results.domain || []);
<add> return domain
<ide> });
<ide> }
<ide> else {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.